File: /var/www/indoadvisory_new/webapp/node_modules/wrangler/wrangler-dist/cli.js
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __esm = (fn2, res) => function __init() {
return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res;
};
var __commonJS = (cb2, mod) => function __require() {
return mod || (0, cb2[__getOwnPropNames(cb2)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all2) => {
for (var name2 in all2)
__defProp(target, name2, { get: all2[name2], 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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
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);
// import_meta_url.js
var import_meta_url;
var init_import_meta_url = __esm({
"import_meta_url.js"() {
import_meta_url = require("url").pathToFileURL(__filename);
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/yerror.js
var YError;
var init_yerror = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/yerror.js"() {
init_import_meta_url();
YError = class _YError extends Error {
static {
__name(this, "YError");
}
constructor(msg) {
super(msg || "yargs error");
this.name = "YError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, _YError);
}
}
};
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/apply-extends.js
function applyExtends(config, cwd2, mergeExtends, _shim) {
shim = _shim;
let defaultConfig = {};
if (Object.prototype.hasOwnProperty.call(config, "extends")) {
if (typeof config.extends !== "string")
return defaultConfig;
const isPath = /\.json|\..*rc$/.test(config.extends);
let pathToDefault = null;
if (!isPath) {
try {
pathToDefault = require.resolve(config.extends);
} catch (_err) {
return config;
}
} else {
pathToDefault = getPathToDefaultConfig(cwd2, config.extends);
}
checkForCircularExtends(pathToDefault);
previouslyVisitedConfigs.push(pathToDefault);
defaultConfig = isPath ? JSON.parse(shim.readFileSync(pathToDefault, "utf8")) : require(config.extends);
delete config.extends;
defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
}
previouslyVisitedConfigs = [];
return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config);
}
function checkForCircularExtends(cfgPath) {
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
throw new YError(`Circular extended configurations: '${cfgPath}'.`);
}
}
function getPathToDefaultConfig(cwd2, pathToExtend) {
return shim.path.resolve(cwd2, pathToExtend);
}
function mergeDeep(config1, config2) {
const target = {};
function isObject3(obj) {
return obj && typeof obj === "object" && !Array.isArray(obj);
}
__name(isObject3, "isObject");
Object.assign(target, config1);
for (const key of Object.keys(config2)) {
if (isObject3(config2[key]) && isObject3(target[key])) {
target[key] = mergeDeep(config1[key], config2[key]);
} else {
target[key] = config2[key];
}
}
return target;
}
var previouslyVisitedConfigs, shim;
var init_apply_extends = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/apply-extends.js"() {
init_import_meta_url();
init_yerror();
previouslyVisitedConfigs = [];
__name(applyExtends, "applyExtends");
__name(checkForCircularExtends, "checkForCircularExtends");
__name(getPathToDefaultConfig, "getPathToDefaultConfig");
__name(mergeDeep, "mergeDeep");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/process-argv.js
function getProcessArgvBinIndex() {
if (isBundledElectronApp())
return 0;
return 1;
}
function isBundledElectronApp() {
return isElectronApp() && !process.defaultApp;
}
function isElectronApp() {
return !!process.versions.electron;
}
function hideBin(argv) {
return argv.slice(getProcessArgvBinIndex() + 1);
}
function getProcessArgvBin() {
return process.argv[getProcessArgvBinIndex()];
}
var init_process_argv = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/process-argv.js"() {
init_import_meta_url();
__name(getProcessArgvBinIndex, "getProcessArgvBinIndex");
__name(isBundledElectronApp, "isBundledElectronApp");
__name(isElectronApp, "isElectronApp");
__name(hideBin, "hideBin");
__name(getProcessArgvBin, "getProcessArgvBin");
}
});
// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/string-utils.js
function camelCase(str) {
const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
if (!isCamelCase) {
str = str.toLowerCase();
}
if (str.indexOf("-") === -1 && str.indexOf("_") === -1) {
return str;
} else {
let camelcase = "";
let nextChrUpper = false;
const leadingHyphens = str.match(/^-+/);
for (let i5 = leadingHyphens ? leadingHyphens[0].length : 0; i5 < str.length; i5++) {
let chr = str.charAt(i5);
if (nextChrUpper) {
nextChrUpper = false;
chr = chr.toUpperCase();
}
if (i5 !== 0 && (chr === "-" || chr === "_")) {
nextChrUpper = true;
} else if (chr !== "-" && chr !== "_") {
camelcase += chr;
}
}
return camelcase;
}
}
function decamelize(str, joinString) {
const lowercase = str.toLowerCase();
joinString = joinString || "-";
let notCamelcase = "";
for (let i5 = 0; i5 < str.length; i5++) {
const chrLower = lowercase.charAt(i5);
const chrString = str.charAt(i5);
if (chrLower !== chrString && i5 > 0) {
notCamelcase += `${joinString}${lowercase.charAt(i5)}`;
} else {
notCamelcase += chrString;
}
}
return notCamelcase;
}
function looksLikeNumber(x6) {
if (x6 === null || x6 === void 0)
return false;
if (typeof x6 === "number")
return true;
if (/^0x[0-9a-f]+$/i.test(x6))
return true;
if (/^0[^.]/.test(x6))
return false;
return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x6);
}
var init_string_utils = __esm({
"../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/string-utils.js"() {
init_import_meta_url();
__name(camelCase, "camelCase");
__name(decamelize, "decamelize");
__name(looksLikeNumber, "looksLikeNumber");
}
});
// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/tokenize-arg-string.js
function tokenizeArgString(argString) {
if (Array.isArray(argString)) {
return argString.map((e7) => typeof e7 !== "string" ? e7 + "" : e7);
}
argString = argString.trim();
let i5 = 0;
let prevC = null;
let c6 = null;
let opening = null;
const args = [];
for (let ii = 0; ii < argString.length; ii++) {
prevC = c6;
c6 = argString.charAt(ii);
if (c6 === " " && !opening) {
if (!(prevC === " ")) {
i5++;
}
continue;
}
if (c6 === opening) {
opening = null;
} else if ((c6 === "'" || c6 === '"') && !opening) {
opening = c6;
}
if (!args[i5])
args[i5] = "";
args[i5] += c6;
}
return args;
}
var init_tokenize_arg_string = __esm({
"../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/tokenize-arg-string.js"() {
init_import_meta_url();
__name(tokenizeArgString, "tokenizeArgString");
}
});
// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser-types.js
var DefaultValuesForTypeKey;
var init_yargs_parser_types = __esm({
"../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser-types.js"() {
init_import_meta_url();
(function(DefaultValuesForTypeKey2) {
DefaultValuesForTypeKey2["BOOLEAN"] = "boolean";
DefaultValuesForTypeKey2["STRING"] = "string";
DefaultValuesForTypeKey2["NUMBER"] = "number";
DefaultValuesForTypeKey2["ARRAY"] = "array";
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
}
});
// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser.js
function combineAliases(aliases2) {
const aliasArrays = [];
const combined = /* @__PURE__ */ Object.create(null);
let change = true;
Object.keys(aliases2).forEach(function(key) {
aliasArrays.push([].concat(aliases2[key], key));
});
while (change) {
change = false;
for (let i5 = 0; i5 < aliasArrays.length; i5++) {
for (let ii = i5 + 1; ii < aliasArrays.length; ii++) {
const intersect = aliasArrays[i5].filter(function(v7) {
return aliasArrays[ii].indexOf(v7) !== -1;
});
if (intersect.length) {
aliasArrays[i5] = aliasArrays[i5].concat(aliasArrays[ii]);
aliasArrays.splice(ii, 1);
change = true;
break;
}
}
}
}
aliasArrays.forEach(function(aliasArray) {
aliasArray = aliasArray.filter(function(v7, i5, self2) {
return self2.indexOf(v7) === i5;
});
const lastAlias = aliasArray.pop();
if (lastAlias !== void 0 && typeof lastAlias === "string") {
combined[lastAlias] = aliasArray;
}
});
return combined;
}
function increment(orig) {
return orig !== void 0 ? orig + 1 : 1;
}
function sanitizeKey(key) {
if (key === "__proto__")
return "___proto___";
return key;
}
function stripQuotes(val2) {
return typeof val2 === "string" && (val2[0] === "'" || val2[0] === '"') && val2[val2.length - 1] === val2[0] ? val2.substring(1, val2.length - 1) : val2;
}
var mixin, YargsParser;
var init_yargs_parser = __esm({
"../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser.js"() {
init_import_meta_url();
init_tokenize_arg_string();
init_yargs_parser_types();
init_string_utils();
YargsParser = class {
static {
__name(this, "YargsParser");
}
constructor(_mixin) {
mixin = _mixin;
}
parse(argsInput, options) {
const opts = Object.assign({
alias: void 0,
array: void 0,
boolean: void 0,
config: void 0,
configObjects: void 0,
configuration: void 0,
coerce: void 0,
count: void 0,
default: void 0,
envPrefix: void 0,
narg: void 0,
normalize: void 0,
string: void 0,
number: void 0,
__: void 0,
key: void 0
}, options);
const args = tokenizeArgString(argsInput);
const inputIsString = typeof argsInput === "string";
const aliases2 = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias));
const configuration = Object.assign({
"boolean-negation": true,
"camel-case-expansion": true,
"combine-arrays": false,
"dot-notation": true,
"duplicate-arguments-array": true,
"flatten-duplicate-arrays": true,
"greedy-arrays": true,
"halt-at-non-option": false,
"nargs-eats-options": false,
"negation-prefix": "no-",
"parse-numbers": true,
"parse-positional-numbers": true,
"populate--": false,
"set-placeholder-key": false,
"short-option-groups": true,
"strip-aliased": false,
"strip-dashed": false,
"unknown-options-as-args": false
}, opts.configuration);
const defaults = Object.assign(/* @__PURE__ */ Object.create(null), opts.default);
const configObjects = opts.configObjects || [];
const envPrefix = opts.envPrefix;
const notFlagsOption = configuration["populate--"];
const notFlagsArgv = notFlagsOption ? "--" : "_";
const newAliases = /* @__PURE__ */ Object.create(null);
const defaulted = /* @__PURE__ */ Object.create(null);
const __ = opts.__ || mixin.format;
const flags2 = {
aliases: /* @__PURE__ */ Object.create(null),
arrays: /* @__PURE__ */ Object.create(null),
bools: /* @__PURE__ */ Object.create(null),
strings: /* @__PURE__ */ Object.create(null),
numbers: /* @__PURE__ */ Object.create(null),
counts: /* @__PURE__ */ Object.create(null),
normalize: /* @__PURE__ */ Object.create(null),
configs: /* @__PURE__ */ Object.create(null),
nargs: /* @__PURE__ */ Object.create(null),
coercions: /* @__PURE__ */ Object.create(null),
keys: []
};
const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)");
[].concat(opts.array || []).filter(Boolean).forEach(function(opt) {
const key = typeof opt === "object" ? opt.key : opt;
const assignment = Object.keys(opt).map(function(key2) {
const arrayFlagKeys = {
boolean: "bools",
string: "strings",
number: "numbers"
};
return arrayFlagKeys[key2];
}).filter(Boolean).pop();
if (assignment) {
flags2[assignment][key] = true;
}
flags2.arrays[key] = true;
flags2.keys.push(key);
});
[].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
flags2.bools[key] = true;
flags2.keys.push(key);
});
[].concat(opts.string || []).filter(Boolean).forEach(function(key) {
flags2.strings[key] = true;
flags2.keys.push(key);
});
[].concat(opts.number || []).filter(Boolean).forEach(function(key) {
flags2.numbers[key] = true;
flags2.keys.push(key);
});
[].concat(opts.count || []).filter(Boolean).forEach(function(key) {
flags2.counts[key] = true;
flags2.keys.push(key);
});
[].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
flags2.normalize[key] = true;
flags2.keys.push(key);
});
if (typeof opts.narg === "object") {
Object.entries(opts.narg).forEach(([key, value]) => {
if (typeof value === "number") {
flags2.nargs[key] = value;
flags2.keys.push(key);
}
});
}
if (typeof opts.coerce === "object") {
Object.entries(opts.coerce).forEach(([key, value]) => {
if (typeof value === "function") {
flags2.coercions[key] = value;
flags2.keys.push(key);
}
});
}
if (typeof opts.config !== "undefined") {
if (Array.isArray(opts.config) || typeof opts.config === "string") {
;
[].concat(opts.config).filter(Boolean).forEach(function(key) {
flags2.configs[key] = true;
});
} else if (typeof opts.config === "object") {
Object.entries(opts.config).forEach(([key, value]) => {
if (typeof value === "boolean" || typeof value === "function") {
flags2.configs[key] = value;
}
});
}
}
extendAliases(opts.key, aliases2, opts.default, flags2.arrays);
Object.keys(defaults).forEach(function(key) {
(flags2.aliases[key] || []).forEach(function(alias) {
defaults[alias] = defaults[key];
});
});
let error2 = null;
checkConfiguration();
let notFlags = [];
const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
const argvReturn = {};
for (let i5 = 0; i5 < args.length; i5++) {
const arg = args[i5];
const truncatedArg = arg.replace(/^-{3,}/, "---");
let broken;
let key;
let letters;
let m6;
let next;
let value;
if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
pushPositional(arg);
} else if (truncatedArg.match(/^---+(=|$)/)) {
pushPositional(arg);
continue;
} else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) {
m6 = arg.match(/^--?([^=]+)=([\s\S]*)$/);
if (m6 !== null && Array.isArray(m6) && m6.length >= 3) {
if (checkAllAliases(m6[1], flags2.arrays)) {
i5 = eatArray(i5, m6[1], args, m6[2]);
} else if (checkAllAliases(m6[1], flags2.nargs) !== false) {
i5 = eatNargs(i5, m6[1], args, m6[2]);
} else {
setArg(m6[1], m6[2], true);
}
}
} else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
m6 = arg.match(negatedBoolean);
if (m6 !== null && Array.isArray(m6) && m6.length >= 2) {
key = m6[1];
setArg(key, checkAllAliases(key, flags2.arrays) ? [false] : false);
}
} else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
m6 = arg.match(/^--?(.+)/);
if (m6 !== null && Array.isArray(m6) && m6.length >= 2) {
key = m6[1];
if (checkAllAliases(key, flags2.arrays)) {
i5 = eatArray(i5, key, args);
} else if (checkAllAliases(key, flags2.nargs) !== false) {
i5 = eatNargs(i5, key, args);
} else {
next = args[i5 + 1];
if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts)) {
setArg(key, next);
i5++;
} else if (/^(true|false)$/.test(next)) {
setArg(key, next);
i5++;
} else {
setArg(key, defaultValue(key));
}
}
}
} else if (arg.match(/^-.\..+=/)) {
m6 = arg.match(/^-([^=]+)=([\s\S]*)$/);
if (m6 !== null && Array.isArray(m6) && m6.length >= 3) {
setArg(m6[1], m6[2]);
}
} else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
next = args[i5 + 1];
m6 = arg.match(/^-(.\..+)/);
if (m6 !== null && Array.isArray(m6) && m6.length >= 2) {
key = m6[1];
if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts)) {
setArg(key, next);
i5++;
} else {
setArg(key, defaultValue(key));
}
}
} else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
letters = arg.slice(1, -1).split("");
broken = false;
for (let j6 = 0; j6 < letters.length; j6++) {
next = arg.slice(j6 + 2);
if (letters[j6 + 1] && letters[j6 + 1] === "=") {
value = arg.slice(j6 + 3);
key = letters[j6];
if (checkAllAliases(key, flags2.arrays)) {
i5 = eatArray(i5, key, args, value);
} else if (checkAllAliases(key, flags2.nargs) !== false) {
i5 = eatNargs(i5, key, args, value);
} else {
setArg(key, value);
}
broken = true;
break;
}
if (next === "-") {
setArg(letters[j6], next);
continue;
}
if (/[A-Za-z]/.test(letters[j6]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags2.bools) === false) {
setArg(letters[j6], next);
broken = true;
break;
}
if (letters[j6 + 1] && letters[j6 + 1].match(/\W/)) {
setArg(letters[j6], next);
broken = true;
break;
} else {
setArg(letters[j6], defaultValue(letters[j6]));
}
}
key = arg.slice(-1)[0];
if (!broken && key !== "-") {
if (checkAllAliases(key, flags2.arrays)) {
i5 = eatArray(i5, key, args);
} else if (checkAllAliases(key, flags2.nargs) !== false) {
i5 = eatNargs(i5, key, args);
} else {
next = args[i5 + 1];
if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts)) {
setArg(key, next);
i5++;
} else if (/^(true|false)$/.test(next)) {
setArg(key, next);
i5++;
} else {
setArg(key, defaultValue(key));
}
}
}
} else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags2.bools)) {
key = arg.slice(1);
setArg(key, defaultValue(key));
} else if (arg === "--") {
notFlags = args.slice(i5 + 1);
break;
} else if (configuration["halt-at-non-option"]) {
notFlags = args.slice(i5);
break;
} else {
pushPositional(arg);
}
}
applyEnvVars(argv, true);
applyEnvVars(argv, false);
setConfig(argv);
setConfigObjects();
applyDefaultsAndAliases(argv, flags2.aliases, defaults, true);
applyCoercions(argv);
if (configuration["set-placeholder-key"])
setPlaceholderKeys(argv);
Object.keys(flags2.counts).forEach(function(key) {
if (!hasKey2(argv, key.split(".")))
setArg(key, 0);
});
if (notFlagsOption && notFlags.length)
argv[notFlagsArgv] = [];
notFlags.forEach(function(key) {
argv[notFlagsArgv].push(key);
});
if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) {
Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => {
delete argv[key];
});
}
if (configuration["strip-aliased"]) {
;
[].concat(...Object.keys(aliases2).map((k6) => aliases2[k6])).forEach((alias) => {
if (configuration["camel-case-expansion"] && alias.includes("-")) {
delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")];
}
delete argv[alias];
});
}
function pushPositional(arg) {
const maybeCoercedNumber = maybeCoerceNumber("_", arg);
if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") {
argv._.push(maybeCoercedNumber);
}
}
__name(pushPositional, "pushPositional");
function eatNargs(i5, key, args2, argAfterEqualSign) {
let ii;
let toEat = checkAllAliases(key, flags2.nargs);
toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
if (toEat === 0) {
if (!isUndefined(argAfterEqualSign)) {
error2 = Error(__("Argument unexpected for: %s", key));
}
setArg(key, defaultValue(key));
return i5;
}
let available = isUndefined(argAfterEqualSign) ? 0 : 1;
if (configuration["nargs-eats-options"]) {
if (args2.length - (i5 + 1) + available < toEat) {
error2 = Error(__("Not enough arguments following: %s", key));
}
available = toEat;
} else {
for (ii = i5 + 1; ii < args2.length; ii++) {
if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii]))
available++;
else
break;
}
if (available < toEat)
error2 = Error(__("Not enough arguments following: %s", key));
}
let consumed = Math.min(available, toEat);
if (!isUndefined(argAfterEqualSign) && consumed > 0) {
setArg(key, argAfterEqualSign);
consumed--;
}
for (ii = i5 + 1; ii < consumed + i5 + 1; ii++) {
setArg(key, args2[ii]);
}
return i5 + consumed;
}
__name(eatNargs, "eatNargs");
function eatArray(i5, key, args2, argAfterEqualSign) {
let argsToSet = [];
let next = argAfterEqualSign || args2[i5 + 1];
const nargsCount = checkAllAliases(key, flags2.nargs);
if (checkAllAliases(key, flags2.bools) && !/^(true|false)$/.test(next)) {
argsToSet.push(true);
} else if (isUndefined(next) || isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
if (defaults[key] !== void 0) {
const defVal = defaults[key];
argsToSet = Array.isArray(defVal) ? defVal : [defVal];
}
} else {
if (!isUndefined(argAfterEqualSign)) {
argsToSet.push(processValue(key, argAfterEqualSign, true));
}
for (let ii = i5 + 1; ii < args2.length; ii++) {
if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
break;
next = args2[ii];
if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
break;
i5 = ii;
argsToSet.push(processValue(key, next, inputIsString));
}
}
if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
error2 = Error(__("Not enough arguments following: %s", key));
}
setArg(key, argsToSet);
return i5;
}
__name(eatArray, "eatArray");
function setArg(key, val2, shouldStripQuotes = inputIsString) {
if (/-/.test(key) && configuration["camel-case-expansion"]) {
const alias = key.split(".").map(function(prop) {
return camelCase(prop);
}).join(".");
addNewAlias(key, alias);
}
const value = processValue(key, val2, shouldStripQuotes);
const splitKey = key.split(".");
setKey(argv, splitKey, value);
if (flags2.aliases[key]) {
flags2.aliases[key].forEach(function(x6) {
const keyProperties = x6.split(".");
setKey(argv, keyProperties, value);
});
}
if (splitKey.length > 1 && configuration["dot-notation"]) {
;
(flags2.aliases[splitKey[0]] || []).forEach(function(x6) {
let keyProperties = x6.split(".");
const a5 = [].concat(splitKey);
a5.shift();
keyProperties = keyProperties.concat(a5);
if (!(flags2.aliases[key] || []).includes(keyProperties.join("."))) {
setKey(argv, keyProperties, value);
}
});
}
if (checkAllAliases(key, flags2.normalize) && !checkAllAliases(key, flags2.arrays)) {
const keys = [key].concat(flags2.aliases[key] || []);
keys.forEach(function(key2) {
Object.defineProperty(argvReturn, key2, {
enumerable: true,
get() {
return val2;
},
set(value2) {
val2 = typeof value2 === "string" ? mixin.normalize(value2) : value2;
}
});
});
}
}
__name(setArg, "setArg");
function addNewAlias(key, alias) {
if (!(flags2.aliases[key] && flags2.aliases[key].length)) {
flags2.aliases[key] = [alias];
newAliases[alias] = true;
}
if (!(flags2.aliases[alias] && flags2.aliases[alias].length)) {
addNewAlias(alias, key);
}
}
__name(addNewAlias, "addNewAlias");
function processValue(key, val2, shouldStripQuotes) {
if (shouldStripQuotes) {
val2 = stripQuotes(val2);
}
if (checkAllAliases(key, flags2.bools) || checkAllAliases(key, flags2.counts)) {
if (typeof val2 === "string")
val2 = val2 === "true";
}
let value = Array.isArray(val2) ? val2.map(function(v7) {
return maybeCoerceNumber(key, v7);
}) : maybeCoerceNumber(key, val2);
if (checkAllAliases(key, flags2.counts) && (isUndefined(value) || typeof value === "boolean")) {
value = increment();
}
if (checkAllAliases(key, flags2.normalize) && checkAllAliases(key, flags2.arrays)) {
if (Array.isArray(val2))
value = val2.map((val3) => {
return mixin.normalize(val3);
});
else
value = mixin.normalize(val2);
}
return value;
}
__name(processValue, "processValue");
function maybeCoerceNumber(key, value) {
if (!configuration["parse-positional-numbers"] && key === "_")
return value;
if (!checkAllAliases(key, flags2.strings) && !checkAllAliases(key, flags2.bools) && !Array.isArray(value)) {
const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
if (shouldCoerceNumber || !isUndefined(value) && checkAllAliases(key, flags2.numbers)) {
value = Number(value);
}
}
return value;
}
__name(maybeCoerceNumber, "maybeCoerceNumber");
function setConfig(argv2) {
const configLookup = /* @__PURE__ */ Object.create(null);
applyDefaultsAndAliases(configLookup, flags2.aliases, defaults);
Object.keys(flags2.configs).forEach(function(configKey) {
const configPath = argv2[configKey] || configLookup[configKey];
if (configPath) {
try {
let config = null;
const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
const resolveConfig2 = flags2.configs[configKey];
if (typeof resolveConfig2 === "function") {
try {
config = resolveConfig2(resolvedConfigPath);
} catch (e7) {
config = e7;
}
if (config instanceof Error) {
error2 = config;
return;
}
} else {
config = mixin.require(resolvedConfigPath);
}
setConfigObject(config);
} catch (ex) {
if (ex.name === "PermissionDenied")
error2 = ex;
else if (argv2[configKey])
error2 = Error(__("Invalid JSON config file: %s", configPath));
}
}
});
}
__name(setConfig, "setConfig");
function setConfigObject(config, prev) {
Object.keys(config).forEach(function(key) {
const value = config[key];
const fullKey = prev ? prev + "." + key : key;
if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) {
setConfigObject(value, fullKey);
} else {
if (!hasKey2(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags2.arrays) && configuration["combine-arrays"]) {
setArg(fullKey, value);
}
}
});
}
__name(setConfigObject, "setConfigObject");
function setConfigObjects() {
if (typeof configObjects !== "undefined") {
configObjects.forEach(function(configObject) {
setConfigObject(configObject);
});
}
}
__name(setConfigObjects, "setConfigObjects");
function applyEnvVars(argv2, configOnly) {
if (typeof envPrefix === "undefined")
return;
const prefix = typeof envPrefix === "string" ? envPrefix : "";
const env6 = mixin.env();
Object.keys(env6).forEach(function(envVar) {
if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
const keys = envVar.split("__").map(function(key, i5) {
if (i5 === 0) {
key = key.substring(prefix.length);
}
return camelCase(key);
});
if ((configOnly && flags2.configs[keys.join(".")] || !configOnly) && !hasKey2(argv2, keys)) {
setArg(keys.join("."), env6[envVar]);
}
}
});
}
__name(applyEnvVars, "applyEnvVars");
function applyCoercions(argv2) {
let coerce2;
const applied = /* @__PURE__ */ new Set();
Object.keys(argv2).forEach(function(key) {
if (!applied.has(key)) {
coerce2 = checkAllAliases(key, flags2.coercions);
if (typeof coerce2 === "function") {
try {
const value = maybeCoerceNumber(key, coerce2(argv2[key]));
[].concat(flags2.aliases[key] || [], key).forEach((ali) => {
applied.add(ali);
argv2[ali] = value;
});
} catch (err) {
error2 = err;
}
}
}
});
}
__name(applyCoercions, "applyCoercions");
function setPlaceholderKeys(argv2) {
flags2.keys.forEach((key) => {
if (~key.indexOf("."))
return;
if (typeof argv2[key] === "undefined")
argv2[key] = void 0;
});
return argv2;
}
__name(setPlaceholderKeys, "setPlaceholderKeys");
function applyDefaultsAndAliases(obj, aliases3, defaults2, canLog = false) {
Object.keys(defaults2).forEach(function(key) {
if (!hasKey2(obj, key.split("."))) {
setKey(obj, key.split("."), defaults2[key]);
if (canLog)
defaulted[key] = true;
(aliases3[key] || []).forEach(function(x6) {
if (hasKey2(obj, x6.split(".")))
return;
setKey(obj, x6.split("."), defaults2[key]);
});
}
});
}
__name(applyDefaultsAndAliases, "applyDefaultsAndAliases");
function hasKey2(obj, keys) {
let o5 = obj;
if (!configuration["dot-notation"])
keys = [keys.join(".")];
keys.slice(0, -1).forEach(function(key2) {
o5 = o5[key2] || {};
});
const key = keys[keys.length - 1];
if (typeof o5 !== "object")
return false;
else
return key in o5;
}
__name(hasKey2, "hasKey");
function setKey(obj, keys, value) {
let o5 = obj;
if (!configuration["dot-notation"])
keys = [keys.join(".")];
keys.slice(0, -1).forEach(function(key2) {
key2 = sanitizeKey(key2);
if (typeof o5 === "object" && o5[key2] === void 0) {
o5[key2] = {};
}
if (typeof o5[key2] !== "object" || Array.isArray(o5[key2])) {
if (Array.isArray(o5[key2])) {
o5[key2].push({});
} else {
o5[key2] = [o5[key2], {}];
}
o5 = o5[key2][o5[key2].length - 1];
} else {
o5 = o5[key2];
}
});
const key = sanitizeKey(keys[keys.length - 1]);
const isTypeArray = checkAllAliases(keys.join("."), flags2.arrays);
const isValueArray = Array.isArray(value);
let duplicate = configuration["duplicate-arguments-array"];
if (!duplicate && checkAllAliases(key, flags2.nargs)) {
duplicate = true;
if (!isUndefined(o5[key]) && flags2.nargs[key] === 1 || Array.isArray(o5[key]) && o5[key].length === flags2.nargs[key]) {
o5[key] = void 0;
}
}
if (value === increment()) {
o5[key] = increment(o5[key]);
} else if (Array.isArray(o5[key])) {
if (duplicate && isTypeArray && isValueArray) {
o5[key] = configuration["flatten-duplicate-arrays"] ? o5[key].concat(value) : (Array.isArray(o5[key][0]) ? o5[key] : [o5[key]]).concat([value]);
} else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
o5[key] = value;
} else {
o5[key] = o5[key].concat([value]);
}
} else if (o5[key] === void 0 && isTypeArray) {
o5[key] = isValueArray ? value : [value];
} else if (duplicate && !(o5[key] === void 0 || checkAllAliases(key, flags2.counts) || checkAllAliases(key, flags2.bools))) {
o5[key] = [o5[key], value];
} else {
o5[key] = value;
}
}
__name(setKey, "setKey");
function extendAliases(...args2) {
args2.forEach(function(obj) {
Object.keys(obj || {}).forEach(function(key) {
if (flags2.aliases[key])
return;
flags2.aliases[key] = [].concat(aliases2[key] || []);
flags2.aliases[key].concat(key).forEach(function(x6) {
if (/-/.test(x6) && configuration["camel-case-expansion"]) {
const c6 = camelCase(x6);
if (c6 !== key && flags2.aliases[key].indexOf(c6) === -1) {
flags2.aliases[key].push(c6);
newAliases[c6] = true;
}
}
});
flags2.aliases[key].concat(key).forEach(function(x6) {
if (x6.length > 1 && /[A-Z]/.test(x6) && configuration["camel-case-expansion"]) {
const c6 = decamelize(x6, "-");
if (c6 !== key && flags2.aliases[key].indexOf(c6) === -1) {
flags2.aliases[key].push(c6);
newAliases[c6] = true;
}
}
});
flags2.aliases[key].forEach(function(x6) {
flags2.aliases[x6] = [key].concat(flags2.aliases[key].filter(function(y4) {
return x6 !== y4;
}));
});
});
});
}
__name(extendAliases, "extendAliases");
function checkAllAliases(key, flag) {
const toCheck = [].concat(flags2.aliases[key] || [], key);
const keys = Object.keys(flag);
const setAlias = toCheck.find((key2) => keys.includes(key2));
return setAlias ? flag[setAlias] : false;
}
__name(checkAllAliases, "checkAllAliases");
function hasAnyFlag(key) {
const flagsKeys = Object.keys(flags2);
const toCheck = [].concat(flagsKeys.map((k6) => flags2[k6]));
return toCheck.some(function(flag) {
return Array.isArray(flag) ? flag.includes(key) : flag[key];
});
}
__name(hasAnyFlag, "hasAnyFlag");
function hasFlagsMatching(arg, ...patterns) {
const toCheck = [].concat(...patterns);
return toCheck.some(function(pattern) {
const match2 = arg.match(pattern);
return match2 && hasAnyFlag(match2[1]);
});
}
__name(hasFlagsMatching, "hasFlagsMatching");
function hasAllShortFlags(arg) {
if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
return false;
}
let hasAllFlags = true;
let next;
const letters = arg.slice(1).split("");
for (let j6 = 0; j6 < letters.length; j6++) {
next = arg.slice(j6 + 2);
if (!hasAnyFlag(letters[j6])) {
hasAllFlags = false;
break;
}
if (letters[j6 + 1] && letters[j6 + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j6]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j6 + 1] && letters[j6 + 1].match(/\W/)) {
break;
}
}
return hasAllFlags;
}
__name(hasAllShortFlags, "hasAllShortFlags");
function isUnknownOptionAsArg(arg) {
return configuration["unknown-options-as-args"] && isUnknownOption(arg);
}
__name(isUnknownOptionAsArg, "isUnknownOptionAsArg");
function isUnknownOption(arg) {
arg = arg.replace(/^-{3,}/, "--");
if (arg.match(negative)) {
return false;
}
if (hasAllShortFlags(arg)) {
return false;
}
const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
const normalFlag = /^-+([^=]+?)$/;
const flagEndingInHyphen = /^-+([^=]+?)-$/;
const flagEndingInDigits = /^-+([^=]+?\d+)$/;
const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
}
__name(isUnknownOption, "isUnknownOption");
function defaultValue(key) {
if (!checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts) && `${key}` in defaults) {
return defaults[key];
} else {
return defaultForType(guessType2(key));
}
}
__name(defaultValue, "defaultValue");
function defaultForType(type) {
const def = {
[DefaultValuesForTypeKey.BOOLEAN]: true,
[DefaultValuesForTypeKey.STRING]: "",
[DefaultValuesForTypeKey.NUMBER]: void 0,
[DefaultValuesForTypeKey.ARRAY]: []
};
return def[type];
}
__name(defaultForType, "defaultForType");
function guessType2(key) {
let type = DefaultValuesForTypeKey.BOOLEAN;
if (checkAllAliases(key, flags2.strings))
type = DefaultValuesForTypeKey.STRING;
else if (checkAllAliases(key, flags2.numbers))
type = DefaultValuesForTypeKey.NUMBER;
else if (checkAllAliases(key, flags2.bools))
type = DefaultValuesForTypeKey.BOOLEAN;
else if (checkAllAliases(key, flags2.arrays))
type = DefaultValuesForTypeKey.ARRAY;
return type;
}
__name(guessType2, "guessType");
function isUndefined(num) {
return num === void 0;
}
__name(isUndefined, "isUndefined");
function checkConfiguration() {
Object.keys(flags2.counts).find((key) => {
if (checkAllAliases(key, flags2.arrays)) {
error2 = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
return true;
} else if (checkAllAliases(key, flags2.nargs)) {
error2 = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
return true;
}
return false;
});
}
__name(checkConfiguration, "checkConfiguration");
return {
aliases: Object.assign({}, flags2.aliases),
argv: Object.assign(argvReturn, argv),
configuration,
defaulted: Object.assign({}, defaulted),
error: error2,
newAliases: Object.assign({}, newAliases)
};
}
};
__name(combineAliases, "combineAliases");
__name(increment, "increment");
__name(sanitizeKey, "sanitizeKey");
__name(stripQuotes, "stripQuotes");
}
});
// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/index.js
var import_util, import_path, import_fs, _a, _b, _c, minNodeVersion, nodeVersion, env, parser, yargsParser, lib_default;
var init_lib = __esm({
"../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/index.js"() {
init_import_meta_url();
import_util = require("util");
import_path = require("path");
init_string_utils();
init_yargs_parser();
import_fs = require("fs");
minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION ? Number(process.env.YARGS_MIN_NODE_VERSION) : 12;
nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
if (nodeVersion) {
const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
if (major < minNodeVersion) {
throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
}
}
env = process ? process.env : {};
parser = new YargsParser({
cwd: process.cwd,
env: /* @__PURE__ */ __name(() => {
return env;
}, "env"),
format: import_util.format,
normalize: import_path.normalize,
resolve: import_path.resolve,
// TODO: figure out a way to combine ESM and CJS coverage, such that
// we can exercise all the lines below:
require: /* @__PURE__ */ __name((path72) => {
if (typeof require !== "undefined") {
return require(path72);
} else if (path72.match(/\.json$/)) {
return JSON.parse((0, import_fs.readFileSync)(path72, "utf8"));
} else {
throw Error("only .json config files are supported in ESM");
}
}, "require")
});
yargsParser = /* @__PURE__ */ __name(function Parser(args, opts) {
const result = parser.parse(args.slice(), opts);
return result.argv;
}, "Parser");
yargsParser.detailed = function(args, opts) {
return parser.parse(args.slice(), opts);
};
yargsParser.camelCase = camelCase;
yargsParser.decamelize = decamelize;
yargsParser.looksLikeNumber = looksLikeNumber;
lib_default = yargsParser;
}
});
// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/index.js
function addBorder(col, ts, style) {
if (col.border) {
if (/[.']-+[.']/.test(ts)) {
return "";
}
if (ts.trim().length !== 0) {
return style;
}
return " ";
}
return "";
}
function _minWidth(col) {
const padding = col.padding || [];
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
if (col.border) {
return minWidth + 4;
}
return minWidth;
}
function getWindowWidth() {
if (typeof process === "object" && process.stdout && process.stdout.columns) {
return process.stdout.columns;
}
return 80;
}
function alignRight(str, width) {
str = str.trim();
const strWidth = mixin2.stringWidth(str);
if (strWidth < width) {
return " ".repeat(width - strWidth) + str;
}
return str;
}
function alignCenter(str, width) {
str = str.trim();
const strWidth = mixin2.stringWidth(str);
if (strWidth >= width) {
return str;
}
return " ".repeat(width - strWidth >> 1) + str;
}
function cliui(opts, _mixin) {
mixin2 = _mixin;
return new UI({
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
});
}
var align, top, right, bottom, left, UI, mixin2;
var init_lib2 = __esm({
"../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/index.js"() {
"use strict";
init_import_meta_url();
align = {
right: alignRight,
center: alignCenter
};
top = 0;
right = 1;
bottom = 2;
left = 3;
UI = class {
static {
__name(this, "UI");
}
constructor(opts) {
var _a4;
this.width = opts.width;
this.wrap = (_a4 = opts.wrap) !== null && _a4 !== void 0 ? _a4 : true;
this.rows = [];
}
span(...args) {
const cols = this.div(...args);
cols.span = true;
}
resetOutput() {
this.rows = [];
}
div(...args) {
if (args.length === 0) {
this.div("");
}
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === "string") {
return this.applyLayoutDSL(args[0]);
}
const cols = args.map((arg) => {
if (typeof arg === "string") {
return this.colFromString(arg);
}
return arg;
});
this.rows.push(cols);
return cols;
}
shouldApplyLayoutDSL(...args) {
return args.length === 1 && typeof args[0] === "string" && /[\t\n]/.test(args[0]);
}
applyLayoutDSL(str) {
const rows = str.split("\n").map((row) => row.split(" "));
let leftColumnWidth = 0;
rows.forEach((columns) => {
if (columns.length > 1 && mixin2.stringWidth(columns[0]) > leftColumnWidth) {
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin2.stringWidth(columns[0]));
}
});
rows.forEach((columns) => {
this.div(...columns.map((r7, i5) => {
return {
text: r7.trim(),
padding: this.measurePadding(r7),
width: i5 === 0 && columns.length > 1 ? leftColumnWidth : void 0
};
}));
});
return this.rows[this.rows.length - 1];
}
colFromString(text) {
return {
text,
padding: this.measurePadding(text)
};
}
measurePadding(str) {
const noAnsi = mixin2.stripAnsi(str);
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
}
toString() {
const lines = [];
this.rows.forEach((row) => {
this.rowToString(row, lines);
});
return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n");
}
rowToString(row, lines) {
this.rasterize(row).forEach((rrow, r7) => {
let str = "";
rrow.forEach((col, c6) => {
const { width } = row[c6];
const wrapWidth = this.negatePadding(row[c6]);
let ts = col;
if (wrapWidth > mixin2.stringWidth(col)) {
ts += " ".repeat(wrapWidth - mixin2.stringWidth(col));
}
if (row[c6].align && row[c6].align !== "left" && this.wrap) {
const fn2 = align[row[c6].align];
ts = fn2(ts, wrapWidth);
if (mixin2.stringWidth(ts) < wrapWidth) {
ts += " ".repeat((width || 0) - mixin2.stringWidth(ts) - 1);
}
}
const padding = row[c6].padding || [0, 0, 0, 0];
if (padding[left]) {
str += " ".repeat(padding[left]);
}
str += addBorder(row[c6], ts, "| ");
str += ts;
str += addBorder(row[c6], ts, " |");
if (padding[right]) {
str += " ".repeat(padding[right]);
}
if (r7 === 0 && lines.length > 0) {
str = this.renderInline(str, lines[lines.length - 1]);
}
});
lines.push({
text: str.replace(/ +$/, ""),
span: row.span
});
});
return lines;
}
// if the full 'source' can render in
// the target line, do so.
renderInline(source, previousLine) {
const match2 = source.match(/^ */);
const leadingWhitespace = match2 ? match2[0].length : 0;
const target = previousLine.text;
const targetTextWidth = mixin2.stringWidth(target.trimRight());
if (!previousLine.span) {
return source;
}
if (!this.wrap) {
previousLine.hidden = true;
return target + source;
}
if (leadingWhitespace < targetTextWidth) {
return source;
}
previousLine.hidden = true;
return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
}
rasterize(row) {
const rrows = [];
const widths = this.columnWidths(row);
let wrapped;
row.forEach((col, c6) => {
col.width = widths[c6];
if (this.wrap) {
wrapped = mixin2.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n");
} else {
wrapped = col.text.split("\n");
}
if (col.border) {
wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + ".");
wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'");
}
if (col.padding) {
wrapped.unshift(...new Array(col.padding[top] || 0).fill(""));
wrapped.push(...new Array(col.padding[bottom] || 0).fill(""));
}
wrapped.forEach((str, r7) => {
if (!rrows[r7]) {
rrows.push([]);
}
const rrow = rrows[r7];
for (let i5 = 0; i5 < c6; i5++) {
if (rrow[i5] === void 0) {
rrow.push("");
}
}
rrow.push(str);
});
});
return rrows;
}
negatePadding(col) {
let wrapWidth = col.width || 0;
if (col.padding) {
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
}
if (col.border) {
wrapWidth -= 4;
}
return wrapWidth;
}
columnWidths(row) {
if (!this.wrap) {
return row.map((col) => {
return col.width || mixin2.stringWidth(col.text);
});
}
let unset = row.length;
let remainingWidth = this.width;
const widths = row.map((col) => {
if (col.width) {
unset--;
remainingWidth -= col.width;
return col.width;
}
return void 0;
});
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
return widths.map((w6, i5) => {
if (w6 === void 0) {
return Math.max(unsetWidth, _minWidth(row[i5]));
}
return w6;
});
}
};
__name(addBorder, "addBorder");
__name(_minWidth, "_minWidth");
__name(getWindowWidth, "getWindowWidth");
__name(alignRight, "alignRight");
__name(alignCenter, "alignCenter");
__name(cliui, "cliui");
}
});
// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/string-utils.js
function stripAnsi(str) {
return str.replace(ansi, "");
}
function wrap(str, width) {
const [start, end] = str.match(ansi) || ["", ""];
str = stripAnsi(str);
let wrapped = "";
for (let i5 = 0; i5 < str.length; i5++) {
if (i5 !== 0 && i5 % width === 0) {
wrapped += "\n";
}
wrapped += str.charAt(i5);
}
if (start && end) {
wrapped = `${start}${wrapped}${end}`;
}
return wrapped;
}
var ansi;
var init_string_utils2 = __esm({
"../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/string-utils.js"() {
init_import_meta_url();
ansi = new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", "g");
__name(stripAnsi, "stripAnsi");
__name(wrap, "wrap");
}
});
// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/index.mjs
function ui(opts) {
return cliui(opts, {
stringWidth: /* @__PURE__ */ __name((str) => {
return [...str].length;
}, "stringWidth"),
stripAnsi,
wrap
});
}
var init_cliui = __esm({
"../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/index.mjs"() {
init_import_meta_url();
init_lib2();
init_string_utils2();
__name(ui, "ui");
}
});
// ../../node_modules/.pnpm/escalade@3.2.0/node_modules/escalade/sync/index.mjs
function sync_default(start, callback) {
let dir = (0, import_path2.resolve)(".", start);
let tmp, stats = (0, import_fs2.statSync)(dir);
if (!stats.isDirectory()) {
dir = (0, import_path2.dirname)(dir);
}
while (true) {
tmp = callback(dir, (0, import_fs2.readdirSync)(dir));
if (tmp) return (0, import_path2.resolve)(dir, tmp);
dir = (0, import_path2.dirname)(tmp = dir);
if (tmp === dir) break;
}
}
var import_path2, import_fs2;
var init_sync = __esm({
"../../node_modules/.pnpm/escalade@3.2.0/node_modules/escalade/sync/index.mjs"() {
init_import_meta_url();
import_path2 = require("path");
import_fs2 = require("fs");
__name(sync_default, "default");
}
});
// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/build/lib/platform-shims/node.js
var import_fs3, import_util2, import_path3, node_default;
var init_node = __esm({
"../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/build/lib/platform-shims/node.js"() {
init_import_meta_url();
import_fs3 = require("fs");
import_util2 = require("util");
import_path3 = require("path");
node_default = {
fs: {
readFileSync: import_fs3.readFileSync,
writeFile: import_fs3.writeFile
},
format: import_util2.format,
resolve: import_path3.resolve,
exists: /* @__PURE__ */ __name((file) => {
try {
return (0, import_fs3.statSync)(file).isFile();
} catch (err) {
return false;
}
}, "exists")
};
}
});
// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/build/lib/index.js
function y18n(opts, _shim) {
shim2 = _shim;
const y18n3 = new Y18N(opts);
return {
__: y18n3.__.bind(y18n3),
__n: y18n3.__n.bind(y18n3),
setLocale: y18n3.setLocale.bind(y18n3),
getLocale: y18n3.getLocale.bind(y18n3),
updateLocale: y18n3.updateLocale.bind(y18n3),
locale: y18n3.locale
};
}
var shim2, Y18N;
var init_lib3 = __esm({
"../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/build/lib/index.js"() {
init_import_meta_url();
Y18N = class {
static {
__name(this, "Y18N");
}
constructor(opts) {
opts = opts || {};
this.directory = opts.directory || "./locales";
this.updateFiles = typeof opts.updateFiles === "boolean" ? opts.updateFiles : true;
this.locale = opts.locale || "en";
this.fallbackToLanguage = typeof opts.fallbackToLanguage === "boolean" ? opts.fallbackToLanguage : true;
this.cache = /* @__PURE__ */ Object.create(null);
this.writeQueue = [];
}
__(...args) {
if (typeof arguments[0] !== "string") {
return this._taggedLiteral(arguments[0], ...arguments);
}
const str = args.shift();
let cb2 = /* @__PURE__ */ __name(function() {
}, "cb");
if (typeof args[args.length - 1] === "function")
cb2 = args.pop();
cb2 = cb2 || function() {
};
if (!this.cache[this.locale])
this._readLocaleFile();
if (!this.cache[this.locale][str] && this.updateFiles) {
this.cache[this.locale][str] = str;
this._enqueueWrite({
directory: this.directory,
locale: this.locale,
cb: cb2
});
} else {
cb2();
}
return shim2.format.apply(shim2.format, [this.cache[this.locale][str] || str].concat(args));
}
__n() {
const args = Array.prototype.slice.call(arguments);
const singular = args.shift();
const plural2 = args.shift();
const quantity = args.shift();
let cb2 = /* @__PURE__ */ __name(function() {
}, "cb");
if (typeof args[args.length - 1] === "function")
cb2 = args.pop();
if (!this.cache[this.locale])
this._readLocaleFile();
let str = quantity === 1 ? singular : plural2;
if (this.cache[this.locale][singular]) {
const entry = this.cache[this.locale][singular];
str = entry[quantity === 1 ? "one" : "other"];
}
if (!this.cache[this.locale][singular] && this.updateFiles) {
this.cache[this.locale][singular] = {
one: singular,
other: plural2
};
this._enqueueWrite({
directory: this.directory,
locale: this.locale,
cb: cb2
});
} else {
cb2();
}
const values = [str];
if (~str.indexOf("%d"))
values.push(quantity);
return shim2.format.apply(shim2.format, values.concat(args));
}
setLocale(locale) {
this.locale = locale;
}
getLocale() {
return this.locale;
}
updateLocale(obj) {
if (!this.cache[this.locale])
this._readLocaleFile();
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
this.cache[this.locale][key] = obj[key];
}
}
}
_taggedLiteral(parts, ...args) {
let str = "";
parts.forEach(function(part, i5) {
const arg = args[i5 + 1];
str += part;
if (typeof arg !== "undefined") {
str += "%s";
}
});
return this.__.apply(this, [str].concat([].slice.call(args, 1)));
}
_enqueueWrite(work) {
this.writeQueue.push(work);
if (this.writeQueue.length === 1)
this._processWriteQueue();
}
_processWriteQueue() {
const _this = this;
const work = this.writeQueue[0];
const directory = work.directory;
const locale = work.locale;
const cb2 = work.cb;
const languageFile = this._resolveLocaleFile(directory, locale);
const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
shim2.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
_this.writeQueue.shift();
if (_this.writeQueue.length > 0)
_this._processWriteQueue();
cb2(err);
});
}
_readLocaleFile() {
let localeLookup = {};
const languageFile = this._resolveLocaleFile(this.directory, this.locale);
try {
if (shim2.fs.readFileSync) {
localeLookup = JSON.parse(shim2.fs.readFileSync(languageFile, "utf-8"));
}
} catch (err) {
if (err instanceof SyntaxError) {
err.message = "syntax error in " + languageFile;
}
if (err.code === "ENOENT")
localeLookup = {};
else
throw err;
}
this.cache[this.locale] = localeLookup;
}
_resolveLocaleFile(directory, locale) {
let file = shim2.resolve(directory, "./", locale + ".json");
if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf("_")) {
const languageFile = shim2.resolve(directory, "./", locale.split("_")[0] + ".json");
if (this._fileExistsSync(languageFile))
file = languageFile;
}
return file;
}
_fileExistsSync(file) {
return shim2.exists(file);
}
};
__name(y18n, "y18n");
}
});
// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/index.mjs
var y18n2, y18n_default;
var init_y18n = __esm({
"../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/index.mjs"() {
init_import_meta_url();
init_node();
init_lib3();
y18n2 = /* @__PURE__ */ __name((opts) => {
return y18n(opts, node_default);
}, "y18n");
y18n_default = y18n2;
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/lib/platform-shims/esm.mjs
var import_assert, import_util3, import_fs4, import_url, import_path4, REQUIRE_ERROR, REQUIRE_DIRECTORY_ERROR, __dirname2, mainFilename, esm_default;
var init_esm = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/lib/platform-shims/esm.mjs"() {
"use strict";
init_import_meta_url();
import_assert = require("assert");
init_cliui();
init_sync();
import_util3 = require("util");
import_fs4 = require("fs");
import_url = require("url");
init_lib();
import_path4 = require("path");
init_process_argv();
init_yerror();
init_y18n();
REQUIRE_ERROR = "require is not supported by ESM";
REQUIRE_DIRECTORY_ERROR = "loading a directory of commands is not supported yet for ESM";
try {
__dirname2 = (0, import_url.fileURLToPath)(import_meta_url);
} catch (e7) {
__dirname2 = process.cwd();
}
mainFilename = __dirname2.substring(0, __dirname2.lastIndexOf("node_modules"));
esm_default = {
assert: {
notStrictEqual: import_assert.notStrictEqual,
strictEqual: import_assert.strictEqual
},
cliui: ui,
findUp: sync_default,
getEnv: /* @__PURE__ */ __name((key) => {
return process.env[key];
}, "getEnv"),
inspect: import_util3.inspect,
getCallerFile: /* @__PURE__ */ __name(() => {
throw new YError(REQUIRE_DIRECTORY_ERROR);
}, "getCallerFile"),
getProcessArgvBin,
mainFilename: mainFilename || process.cwd(),
Parser: lib_default,
path: {
basename: import_path4.basename,
dirname: import_path4.dirname,
extname: import_path4.extname,
relative: import_path4.relative,
resolve: import_path4.resolve
},
process: {
argv: /* @__PURE__ */ __name(() => process.argv, "argv"),
cwd: process.cwd,
emitWarning: /* @__PURE__ */ __name((warning, type) => process.emitWarning(warning, type), "emitWarning"),
execPath: /* @__PURE__ */ __name(() => process.execPath, "execPath"),
exit: process.exit,
nextTick: process.nextTick,
stdColumns: typeof process.stdout.columns !== "undefined" ? process.stdout.columns : null
},
readFileSync: import_fs4.readFileSync,
require: /* @__PURE__ */ __name(() => {
throw new YError(REQUIRE_ERROR);
}, "require"),
requireDirectory: /* @__PURE__ */ __name(() => {
throw new YError(REQUIRE_DIRECTORY_ERROR);
}, "requireDirectory"),
stringWidth: /* @__PURE__ */ __name((str) => {
return [...str].length;
}, "stringWidth"),
y18n: y18n_default({
directory: (0, import_path4.resolve)(__dirname2, "../../../locales"),
updateFiles: false
})
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/symbols.js
var require_symbols = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/symbols.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
kClose: Symbol("close"),
kDestroy: Symbol("destroy"),
kDispatch: Symbol("dispatch"),
kUrl: Symbol("url"),
kWriting: Symbol("writing"),
kResuming: Symbol("resuming"),
kQueue: Symbol("queue"),
kConnect: Symbol("connect"),
kConnecting: Symbol("connecting"),
kKeepAliveDefaultTimeout: Symbol("default keep alive timeout"),
kKeepAliveMaxTimeout: Symbol("max keep alive timeout"),
kKeepAliveTimeoutThreshold: Symbol("keep alive timeout threshold"),
kKeepAliveTimeoutValue: Symbol("keep alive timeout"),
kKeepAlive: Symbol("keep alive"),
kHeadersTimeout: Symbol("headers timeout"),
kBodyTimeout: Symbol("body timeout"),
kServerName: Symbol("server name"),
kLocalAddress: Symbol("local address"),
kHost: Symbol("host"),
kNoRef: Symbol("no ref"),
kBodyUsed: Symbol("used"),
kBody: Symbol("abstracted request body"),
kRunning: Symbol("running"),
kBlocking: Symbol("blocking"),
kPending: Symbol("pending"),
kSize: Symbol("size"),
kBusy: Symbol("busy"),
kQueued: Symbol("queued"),
kFree: Symbol("free"),
kConnected: Symbol("connected"),
kClosed: Symbol("closed"),
kNeedDrain: Symbol("need drain"),
kReset: Symbol("reset"),
kDestroyed: Symbol.for("nodejs.stream.destroyed"),
kResume: Symbol("resume"),
kOnError: Symbol("on error"),
kMaxHeadersSize: Symbol("max headers size"),
kRunningIdx: Symbol("running index"),
kPendingIdx: Symbol("pending index"),
kError: Symbol("error"),
kClients: Symbol("clients"),
kClient: Symbol("client"),
kParser: Symbol("parser"),
kOnDestroyed: Symbol("destroy callbacks"),
kPipelining: Symbol("pipelining"),
kSocket: Symbol("socket"),
kHostHeader: Symbol("host header"),
kConnector: Symbol("connector"),
kStrictContentLength: Symbol("strict content length"),
kMaxRedirections: Symbol("maxRedirections"),
kMaxRequests: Symbol("maxRequestsPerClient"),
kProxy: Symbol("proxy agent options"),
kCounter: Symbol("socket request counter"),
kMaxResponseSize: Symbol("max response size"),
kHTTP2Session: Symbol("http2Session"),
kHTTP2SessionState: Symbol("http2Session state"),
kRetryHandlerDefaultRetry: Symbol("retry agent default retry"),
kConstruct: Symbol("constructable"),
kListeners: Symbol("listeners"),
kHTTPContext: Symbol("http context"),
kMaxConcurrentStreams: Symbol("max concurrent streams"),
kNoProxyAgent: Symbol("no proxy agent"),
kHttpProxyAgent: Symbol("http proxy agent"),
kHttpsProxyAgent: Symbol("https proxy agent")
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/timers.js
var require_timers = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/timers.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var fastNow = 0;
var RESOLUTION_MS = 1e3;
var TICK_MS = (RESOLUTION_MS >> 1) - 1;
var fastNowTimeout;
var kFastTimer = Symbol("kFastTimer");
var fastTimers = [];
var NOT_IN_LIST = -2;
var TO_BE_CLEARED = -1;
var PENDING = 0;
var ACTIVE = 1;
function onTick() {
fastNow += TICK_MS;
let idx = 0;
let len = fastTimers.length;
while (idx < len) {
const timer = fastTimers[idx];
if (timer._state === PENDING) {
timer._idleStart = fastNow - TICK_MS;
timer._state = ACTIVE;
} else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) {
timer._state = TO_BE_CLEARED;
timer._idleStart = -1;
timer._onTimeout(timer._timerArg);
}
if (timer._state === TO_BE_CLEARED) {
timer._state = NOT_IN_LIST;
if (--len !== 0) {
fastTimers[idx] = fastTimers[len];
}
} else {
++idx;
}
}
fastTimers.length = len;
if (fastTimers.length !== 0) {
refreshTimeout();
}
}
__name(onTick, "onTick");
function refreshTimeout() {
if (fastNowTimeout?.refresh) {
fastNowTimeout.refresh();
} else {
clearTimeout(fastNowTimeout);
fastNowTimeout = setTimeout(onTick, TICK_MS);
fastNowTimeout?.unref();
}
}
__name(refreshTimeout, "refreshTimeout");
var FastTimer = class {
static {
__name(this, "FastTimer");
}
[kFastTimer] = true;
/**
* The state of the timer, which can be one of the following:
* - NOT_IN_LIST (-2)
* - TO_BE_CLEARED (-1)
* - PENDING (0)
* - ACTIVE (1)
*
* @type {-2|-1|0|1}
* @private
*/
_state = NOT_IN_LIST;
/**
* The number of milliseconds to wait before calling the callback.
*
* @type {number}
* @private
*/
_idleTimeout = -1;
/**
* The time in milliseconds when the timer was started. This value is used to
* calculate when the timer should expire.
*
* @type {number}
* @default -1
* @private
*/
_idleStart = -1;
/**
* The function to be executed when the timer expires.
* @type {Function}
* @private
*/
_onTimeout;
/**
* The argument to be passed to the callback when the timer expires.
*
* @type {*}
* @private
*/
_timerArg;
/**
* @constructor
* @param {Function} callback A function to be executed after the timer
* expires.
* @param {number} delay The time, in milliseconds that the timer should wait
* before the specified function or code is executed.
* @param {*} arg
*/
constructor(callback, delay, arg) {
this._onTimeout = callback;
this._idleTimeout = delay;
this._timerArg = arg;
this.refresh();
}
/**
* Sets the timer's start time to the current time, and reschedules the timer
* to call its callback at the previously specified duration adjusted to the
* current time.
* Using this on a timer that has already called its callback will reactivate
* the timer.
*
* @returns {void}
*/
refresh() {
if (this._state === NOT_IN_LIST) {
fastTimers.push(this);
}
if (!fastNowTimeout || fastTimers.length === 1) {
refreshTimeout();
}
this._state = PENDING;
}
/**
* The `clear` method cancels the timer, preventing it from executing.
*
* @returns {void}
* @private
*/
clear() {
this._state = TO_BE_CLEARED;
this._idleStart = -1;
}
};
module3.exports = {
/**
* The setTimeout() method sets a timer which executes a function once the
* timer expires.
* @param {Function} callback A function to be executed after the timer
* expires.
* @param {number} delay The time, in milliseconds that the timer should
* wait before the specified function or code is executed.
* @param {*} [arg] An optional argument to be passed to the callback function
* when the timer expires.
* @returns {NodeJS.Timeout|FastTimer}
*/
setTimeout(callback, delay, arg) {
return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg);
},
/**
* The clearTimeout method cancels an instantiated Timer previously created
* by calling setTimeout.
*
* @param {NodeJS.Timeout|FastTimer} timeout
*/
clearTimeout(timeout2) {
if (timeout2[kFastTimer]) {
timeout2.clear();
} else {
clearTimeout(timeout2);
}
},
/**
* The setFastTimeout() method sets a fastTimer which executes a function once
* the timer expires.
* @param {Function} callback A function to be executed after the timer
* expires.
* @param {number} delay The time, in milliseconds that the timer should
* wait before the specified function or code is executed.
* @param {*} [arg] An optional argument to be passed to the callback function
* when the timer expires.
* @returns {FastTimer}
*/
setFastTimeout(callback, delay, arg) {
return new FastTimer(callback, delay, arg);
},
/**
* The clearTimeout method cancels an instantiated FastTimer previously
* created by calling setFastTimeout.
*
* @param {FastTimer} timeout
*/
clearFastTimeout(timeout2) {
timeout2.clear();
},
/**
* The now method returns the value of the internal fast timer clock.
*
* @returns {number}
*/
now() {
return fastNow;
},
/**
* Trigger the onTick function to process the fastTimers array.
* Exported for testing purposes only.
* Marking as deprecated to discourage any use outside of testing.
* @deprecated
* @param {number} [delay=0] The delay in milliseconds to add to the now value.
*/
tick(delay = 0) {
fastNow += delay - RESOLUTION_MS + 1;
onTick();
onTick();
},
/**
* Reset FastTimers.
* Exported for testing purposes only.
* Marking as deprecated to discourage any use outside of testing.
* @deprecated
*/
reset() {
fastNow = 0;
fastTimers.length = 0;
clearTimeout(fastNowTimeout);
fastNowTimeout = null;
},
/**
* Exporting for testing purposes only.
* Marking as deprecated to discourage any use outside of testing.
* @deprecated
*/
kFastTimer
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/errors.js
var require_errors = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/errors.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var UndiciError = class extends Error {
static {
__name(this, "UndiciError");
}
constructor(message, options) {
super(message, options);
this.name = "UndiciError";
this.code = "UND_ERR";
}
};
var ConnectTimeoutError = class extends UndiciError {
static {
__name(this, "ConnectTimeoutError");
}
constructor(message) {
super(message);
this.name = "ConnectTimeoutError";
this.message = message || "Connect Timeout Error";
this.code = "UND_ERR_CONNECT_TIMEOUT";
}
};
var HeadersTimeoutError = class extends UndiciError {
static {
__name(this, "HeadersTimeoutError");
}
constructor(message) {
super(message);
this.name = "HeadersTimeoutError";
this.message = message || "Headers Timeout Error";
this.code = "UND_ERR_HEADERS_TIMEOUT";
}
};
var HeadersOverflowError = class extends UndiciError {
static {
__name(this, "HeadersOverflowError");
}
constructor(message) {
super(message);
this.name = "HeadersOverflowError";
this.message = message || "Headers Overflow Error";
this.code = "UND_ERR_HEADERS_OVERFLOW";
}
};
var BodyTimeoutError = class extends UndiciError {
static {
__name(this, "BodyTimeoutError");
}
constructor(message) {
super(message);
this.name = "BodyTimeoutError";
this.message = message || "Body Timeout Error";
this.code = "UND_ERR_BODY_TIMEOUT";
}
};
var ResponseStatusCodeError = class extends UndiciError {
static {
__name(this, "ResponseStatusCodeError");
}
constructor(message, statusCode, headers, body) {
super(message);
this.name = "ResponseStatusCodeError";
this.message = message || "Response Status Code Error";
this.code = "UND_ERR_RESPONSE_STATUS_CODE";
this.body = body;
this.status = statusCode;
this.statusCode = statusCode;
this.headers = headers;
}
};
var InvalidArgumentError = class extends UndiciError {
static {
__name(this, "InvalidArgumentError");
}
constructor(message) {
super(message);
this.name = "InvalidArgumentError";
this.message = message || "Invalid Argument Error";
this.code = "UND_ERR_INVALID_ARG";
}
};
var InvalidReturnValueError = class extends UndiciError {
static {
__name(this, "InvalidReturnValueError");
}
constructor(message) {
super(message);
this.name = "InvalidReturnValueError";
this.message = message || "Invalid Return Value Error";
this.code = "UND_ERR_INVALID_RETURN_VALUE";
}
};
var AbortError2 = class extends UndiciError {
static {
__name(this, "AbortError");
}
constructor(message) {
super(message);
this.name = "AbortError";
this.message = message || "The operation was aborted";
}
};
var RequestAbortedError = class extends AbortError2 {
static {
__name(this, "RequestAbortedError");
}
constructor(message) {
super(message);
this.name = "AbortError";
this.message = message || "Request aborted";
this.code = "UND_ERR_ABORTED";
}
};
var InformationalError = class extends UndiciError {
static {
__name(this, "InformationalError");
}
constructor(message) {
super(message);
this.name = "InformationalError";
this.message = message || "Request information";
this.code = "UND_ERR_INFO";
}
};
var RequestContentLengthMismatchError = class extends UndiciError {
static {
__name(this, "RequestContentLengthMismatchError");
}
constructor(message) {
super(message);
this.name = "RequestContentLengthMismatchError";
this.message = message || "Request body length does not match content-length header";
this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
}
};
var ResponseContentLengthMismatchError = class extends UndiciError {
static {
__name(this, "ResponseContentLengthMismatchError");
}
constructor(message) {
super(message);
this.name = "ResponseContentLengthMismatchError";
this.message = message || "Response body length does not match content-length header";
this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
}
};
var ClientDestroyedError = class extends UndiciError {
static {
__name(this, "ClientDestroyedError");
}
constructor(message) {
super(message);
this.name = "ClientDestroyedError";
this.message = message || "The client is destroyed";
this.code = "UND_ERR_DESTROYED";
}
};
var ClientClosedError = class extends UndiciError {
static {
__name(this, "ClientClosedError");
}
constructor(message) {
super(message);
this.name = "ClientClosedError";
this.message = message || "The client is closed";
this.code = "UND_ERR_CLOSED";
}
};
var SocketError = class extends UndiciError {
static {
__name(this, "SocketError");
}
constructor(message, socket) {
super(message);
this.name = "SocketError";
this.message = message || "Socket error";
this.code = "UND_ERR_SOCKET";
this.socket = socket;
}
};
var NotSupportedError = class extends UndiciError {
static {
__name(this, "NotSupportedError");
}
constructor(message) {
super(message);
this.name = "NotSupportedError";
this.message = message || "Not supported error";
this.code = "UND_ERR_NOT_SUPPORTED";
}
};
var BalancedPoolMissingUpstreamError = class extends UndiciError {
static {
__name(this, "BalancedPoolMissingUpstreamError");
}
constructor(message) {
super(message);
this.name = "MissingUpstreamError";
this.message = message || "No upstream has been added to the BalancedPool";
this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
}
};
var HTTPParserError = class extends Error {
static {
__name(this, "HTTPParserError");
}
constructor(message, code, data) {
super(message);
this.name = "HTTPParserError";
this.code = code ? `HPE_${code}` : void 0;
this.data = data ? data.toString() : void 0;
}
};
var ResponseExceededMaxSizeError = class extends UndiciError {
static {
__name(this, "ResponseExceededMaxSizeError");
}
constructor(message) {
super(message);
this.name = "ResponseExceededMaxSizeError";
this.message = message || "Response content exceeded max size";
this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
}
};
var RequestRetryError = class extends UndiciError {
static {
__name(this, "RequestRetryError");
}
constructor(message, code, { headers, data }) {
super(message);
this.name = "RequestRetryError";
this.message = message || "Request retry error";
this.code = "UND_ERR_REQ_RETRY";
this.statusCode = code;
this.data = data;
this.headers = headers;
}
};
var ResponseError = class extends UndiciError {
static {
__name(this, "ResponseError");
}
constructor(message, code, { headers, body }) {
super(message);
this.name = "ResponseError";
this.message = message || "Response error";
this.code = "UND_ERR_RESPONSE";
this.statusCode = code;
this.body = body;
this.headers = headers;
}
};
var SecureProxyConnectionError = class extends UndiciError {
static {
__name(this, "SecureProxyConnectionError");
}
constructor(cause, message, options = {}) {
super(message, { cause, ...options });
this.name = "SecureProxyConnectionError";
this.message = message || "Secure Proxy Connection failed";
this.code = "UND_ERR_PRX_TLS";
this.cause = cause;
}
};
module3.exports = {
AbortError: AbortError2,
HTTPParserError,
UndiciError,
HeadersTimeoutError,
HeadersOverflowError,
BodyTimeoutError,
RequestContentLengthMismatchError,
ConnectTimeoutError,
ResponseStatusCodeError,
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError,
ClientDestroyedError,
ClientClosedError,
InformationalError,
SocketError,
NotSupportedError,
ResponseContentLengthMismatchError,
BalancedPoolMissingUpstreamError,
ResponseExceededMaxSizeError,
RequestRetryError,
ResponseError,
SecureProxyConnectionError
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/constants.js
var require_constants = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/constants.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var wellknownHeaderNames = (
/** @type {const} */
[
"Accept",
"Accept-Encoding",
"Accept-Language",
"Accept-Ranges",
"Access-Control-Allow-Credentials",
"Access-Control-Allow-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Origin",
"Access-Control-Expose-Headers",
"Access-Control-Max-Age",
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Age",
"Allow",
"Alt-Svc",
"Alt-Used",
"Authorization",
"Cache-Control",
"Clear-Site-Data",
"Connection",
"Content-Disposition",
"Content-Encoding",
"Content-Language",
"Content-Length",
"Content-Location",
"Content-Range",
"Content-Security-Policy",
"Content-Security-Policy-Report-Only",
"Content-Type",
"Cookie",
"Cross-Origin-Embedder-Policy",
"Cross-Origin-Opener-Policy",
"Cross-Origin-Resource-Policy",
"Date",
"Device-Memory",
"Downlink",
"ECT",
"ETag",
"Expect",
"Expect-CT",
"Expires",
"Forwarded",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Keep-Alive",
"Last-Modified",
"Link",
"Location",
"Max-Forwards",
"Origin",
"Permissions-Policy",
"Pragma",
"Proxy-Authenticate",
"Proxy-Authorization",
"RTT",
"Range",
"Referer",
"Referrer-Policy",
"Refresh",
"Retry-After",
"Sec-WebSocket-Accept",
"Sec-WebSocket-Extensions",
"Sec-WebSocket-Key",
"Sec-WebSocket-Protocol",
"Sec-WebSocket-Version",
"Server",
"Server-Timing",
"Service-Worker-Allowed",
"Service-Worker-Navigation-Preload",
"Set-Cookie",
"SourceMap",
"Strict-Transport-Security",
"Supports-Loading-Mode",
"TE",
"Timing-Allow-Origin",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Upgrade-Insecure-Requests",
"User-Agent",
"Vary",
"Via",
"WWW-Authenticate",
"X-Content-Type-Options",
"X-DNS-Prefetch-Control",
"X-Frame-Options",
"X-Permitted-Cross-Domain-Policies",
"X-Powered-By",
"X-Requested-With",
"X-XSS-Protection"
]
);
var headerNameLowerCasedRecord = {};
Object.setPrototypeOf(headerNameLowerCasedRecord, null);
var wellknownHeaderNameBuffers = {};
Object.setPrototypeOf(wellknownHeaderNameBuffers, null);
function getHeaderNameAsBuffer(header) {
let buffer = wellknownHeaderNameBuffers[header];
if (buffer === void 0) {
buffer = Buffer.from(header);
}
return buffer;
}
__name(getHeaderNameAsBuffer, "getHeaderNameAsBuffer");
for (let i5 = 0; i5 < wellknownHeaderNames.length; ++i5) {
const key = wellknownHeaderNames[i5];
const lowerCasedKey = key.toLowerCase();
headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey;
}
module3.exports = {
wellknownHeaderNames,
headerNameLowerCasedRecord,
getHeaderNameAsBuffer
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/tree.js
var require_tree = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/tree.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
wellknownHeaderNames,
headerNameLowerCasedRecord
} = require_constants();
var TstNode = class _TstNode {
static {
__name(this, "TstNode");
}
/** @type {any} */
value = null;
/** @type {null | TstNode} */
left = null;
/** @type {null | TstNode} */
middle = null;
/** @type {null | TstNode} */
right = null;
/** @type {number} */
code;
/**
* @param {string} key
* @param {any} value
* @param {number} index
*/
constructor(key, value, index) {
if (index === void 0 || index >= key.length) {
throw new TypeError("Unreachable");
}
const code = this.code = key.charCodeAt(index);
if (code > 127) {
throw new TypeError("key must be ascii string");
}
if (key.length !== ++index) {
this.middle = new _TstNode(key, value, index);
} else {
this.value = value;
}
}
/**
* @param {string} key
* @param {any} value
* @returns {void}
*/
add(key, value) {
const length = key.length;
if (length === 0) {
throw new TypeError("Unreachable");
}
let index = 0;
let node2 = this;
while (true) {
const code = key.charCodeAt(index);
if (code > 127) {
throw new TypeError("key must be ascii string");
}
if (node2.code === code) {
if (length === ++index) {
node2.value = value;
break;
} else if (node2.middle !== null) {
node2 = node2.middle;
} else {
node2.middle = new _TstNode(key, value, index);
break;
}
} else if (node2.code < code) {
if (node2.left !== null) {
node2 = node2.left;
} else {
node2.left = new _TstNode(key, value, index);
break;
}
} else if (node2.right !== null) {
node2 = node2.right;
} else {
node2.right = new _TstNode(key, value, index);
break;
}
}
}
/**
* @param {Uint8Array} key
* @return {TstNode | null}
*/
search(key) {
const keylength = key.length;
let index = 0;
let node2 = this;
while (node2 !== null && index < keylength) {
let code = key[index];
if (code <= 90 && code >= 65) {
code |= 32;
}
while (node2 !== null) {
if (code === node2.code) {
if (keylength === ++index) {
return node2;
}
node2 = node2.middle;
break;
}
node2 = node2.code < code ? node2.left : node2.right;
}
}
return null;
}
};
var TernarySearchTree = class {
static {
__name(this, "TernarySearchTree");
}
/** @type {TstNode | null} */
node = null;
/**
* @param {string} key
* @param {any} value
* @returns {void}
* */
insert(key, value) {
if (this.node === null) {
this.node = new TstNode(key, value, 0);
} else {
this.node.add(key, value);
}
}
/**
* @param {Uint8Array} key
* @returns {any}
*/
lookup(key) {
return this.node?.search(key)?.value ?? null;
}
};
var tree = new TernarySearchTree();
for (let i5 = 0; i5 < wellknownHeaderNames.length; ++i5) {
const key = headerNameLowerCasedRecord[wellknownHeaderNames[i5]];
tree.insert(key, key);
}
module3.exports = {
TernarySearchTree,
tree
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/util.js
var require_util = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
var { IncomingMessage } = require("http");
var stream2 = require("stream");
var net2 = require("net");
var { Blob: Blob6 } = require("buffer");
var { stringify } = require("querystring");
var { EventEmitter: EE } = require("events");
var timers = require_timers();
var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
var { headerNameLowerCasedRecord } = require_constants();
var { tree } = require_tree();
var [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v7) => Number(v7));
var BodyAsyncIterable = class {
static {
__name(this, "BodyAsyncIterable");
}
constructor(body) {
this[kBody] = body;
this[kBodyUsed] = false;
}
async *[Symbol.asyncIterator]() {
assert44(!this[kBodyUsed], "disturbed");
this[kBodyUsed] = true;
yield* this[kBody];
}
};
function noop() {
}
__name(noop, "noop");
function wrapRequestBody(body) {
if (isStream2(body)) {
if (bodyLength(body) === 0) {
body.on("data", function() {
assert44(false);
});
}
if (typeof body.readableDidRead !== "boolean") {
body[kBodyUsed] = false;
EE.prototype.on.call(body, "data", function() {
this[kBodyUsed] = true;
});
}
return body;
} else if (body && typeof body.pipeTo === "function") {
return new BodyAsyncIterable(body);
} else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
return new BodyAsyncIterable(body);
} else {
return body;
}
}
__name(wrapRequestBody, "wrapRequestBody");
function isStream2(obj) {
return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
}
__name(isStream2, "isStream");
function isBlobLike(object) {
if (object === null) {
return false;
} else if (object instanceof Blob6) {
return true;
} else if (typeof object !== "object") {
return false;
} else {
const sTag = object[Symbol.toStringTag];
return (sTag === "Blob" || sTag === "File") && ("stream" in object && typeof object.stream === "function" || "arrayBuffer" in object && typeof object.arrayBuffer === "function");
}
}
__name(isBlobLike, "isBlobLike");
function serializePathWithQuery(url4, queryParams) {
if (url4.includes("?") || url4.includes("#")) {
throw new Error('Query params cannot be passed when url already contains "?" or "#".');
}
const stringified = stringify(queryParams);
if (stringified) {
url4 += "?" + stringified;
}
return url4;
}
__name(serializePathWithQuery, "serializePathWithQuery");
function isValidPort(port) {
const value = parseInt(port, 10);
return value === Number(port) && value >= 0 && value <= 65535;
}
__name(isValidPort, "isValidPort");
function isHttpOrHttpsPrefixed(value) {
return value != null && value[0] === "h" && value[1] === "t" && value[2] === "t" && value[3] === "p" && (value[4] === ":" || value[4] === "s" && value[5] === ":");
}
__name(isHttpOrHttpsPrefixed, "isHttpOrHttpsPrefixed");
function parseURL2(url4) {
if (typeof url4 === "string") {
url4 = new URL(url4);
if (!isHttpOrHttpsPrefixed(url4.origin || url4.protocol)) {
throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
}
return url4;
}
if (!url4 || typeof url4 !== "object") {
throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
}
if (!(url4 instanceof URL)) {
if (url4.port != null && url4.port !== "" && isValidPort(url4.port) === false) {
throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
}
if (url4.path != null && typeof url4.path !== "string") {
throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
}
if (url4.pathname != null && typeof url4.pathname !== "string") {
throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
}
if (url4.hostname != null && typeof url4.hostname !== "string") {
throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
}
if (url4.origin != null && typeof url4.origin !== "string") {
throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
}
if (!isHttpOrHttpsPrefixed(url4.origin || url4.protocol)) {
throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
}
const port = url4.port != null ? url4.port : url4.protocol === "https:" ? 443 : 80;
let origin = url4.origin != null ? url4.origin : `${url4.protocol || ""}//${url4.hostname || ""}:${port}`;
let path72 = url4.path != null ? url4.path : `${url4.pathname || ""}${url4.search || ""}`;
if (origin[origin.length - 1] === "/") {
origin = origin.slice(0, origin.length - 1);
}
if (path72 && path72[0] !== "/") {
path72 = `/${path72}`;
}
return new URL(`${origin}${path72}`);
}
if (!isHttpOrHttpsPrefixed(url4.origin || url4.protocol)) {
throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
}
return url4;
}
__name(parseURL2, "parseURL");
function parseOrigin(url4) {
url4 = parseURL2(url4);
if (url4.pathname !== "/" || url4.search || url4.hash) {
throw new InvalidArgumentError("invalid url");
}
return url4;
}
__name(parseOrigin, "parseOrigin");
function getHostname(host) {
if (host[0] === "[") {
const idx2 = host.indexOf("]");
assert44(idx2 !== -1);
return host.substring(1, idx2);
}
const idx = host.indexOf(":");
if (idx === -1) return host;
return host.substring(0, idx);
}
__name(getHostname, "getHostname");
function getServerName(host) {
if (!host) {
return null;
}
assert44(typeof host === "string");
const servername = getHostname(host);
if (net2.isIP(servername)) {
return "";
}
return servername;
}
__name(getServerName, "getServerName");
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
__name(deepClone, "deepClone");
function isAsyncIterable(obj) {
return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
}
__name(isAsyncIterable, "isAsyncIterable");
function isIterable(obj) {
return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
}
__name(isIterable, "isIterable");
function bodyLength(body) {
if (body == null) {
return 0;
} else if (isStream2(body)) {
const state2 = body._readableState;
return state2 && state2.objectMode === false && state2.ended === true && Number.isFinite(state2.length) ? state2.length : null;
} else if (isBlobLike(body)) {
return body.size != null ? body.size : null;
} else if (isBuffer(body)) {
return body.byteLength;
}
return null;
}
__name(bodyLength, "bodyLength");
function isDestroyed(body) {
return body && !!(body.destroyed || body[kDestroyed] || stream2.isDestroyed?.(body));
}
__name(isDestroyed, "isDestroyed");
function destroy(stream3, err) {
if (stream3 == null || !isStream2(stream3) || isDestroyed(stream3)) {
return;
}
if (typeof stream3.destroy === "function") {
if (Object.getPrototypeOf(stream3).constructor === IncomingMessage) {
stream3.socket = null;
}
stream3.destroy(err);
} else if (err) {
queueMicrotask(() => {
stream3.emit("error", err);
});
}
if (stream3.destroyed !== true) {
stream3[kDestroyed] = true;
}
}
__name(destroy, "destroy");
var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
function parseKeepAliveTimeout(val2) {
const m6 = val2.match(KEEPALIVE_TIMEOUT_EXPR);
return m6 ? parseInt(m6[1], 10) * 1e3 : null;
}
__name(parseKeepAliveTimeout, "parseKeepAliveTimeout");
function headerNameToString(value) {
return typeof value === "string" ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase();
}
__name(headerNameToString, "headerNameToString");
function bufferToLowerCasedHeaderName(value) {
return tree.lookup(value) ?? value.toString("latin1").toLowerCase();
}
__name(bufferToLowerCasedHeaderName, "bufferToLowerCasedHeaderName");
function parseHeaders2(headers, obj) {
if (obj === void 0) obj = {};
for (let i5 = 0; i5 < headers.length; i5 += 2) {
const key = headerNameToString(headers[i5]);
let val2 = obj[key];
if (val2) {
if (typeof val2 === "string") {
val2 = [val2];
obj[key] = val2;
}
val2.push(headers[i5 + 1].toString("utf8"));
} else {
const headersValue = headers[i5 + 1];
if (typeof headersValue === "string") {
obj[key] = headersValue;
} else {
obj[key] = Array.isArray(headersValue) ? headersValue.map((x6) => x6.toString("utf8")) : headersValue.toString("utf8");
}
}
}
if ("content-length" in obj && "content-disposition" in obj) {
obj["content-disposition"] = Buffer.from(obj["content-disposition"]).toString("latin1");
}
return obj;
}
__name(parseHeaders2, "parseHeaders");
function parseRawHeaders(headers) {
const headersLength = headers.length;
const ret = new Array(headersLength);
let hasContentLength = false;
let contentDispositionIdx = -1;
let key;
let val2;
let kLen = 0;
for (let n6 = 0; n6 < headersLength; n6 += 2) {
key = headers[n6];
val2 = headers[n6 + 1];
typeof key !== "string" && (key = key.toString());
typeof val2 !== "string" && (val2 = val2.toString("utf8"));
kLen = key.length;
if (kLen === 14 && key[7] === "-" && (key === "content-length" || key.toLowerCase() === "content-length")) {
hasContentLength = true;
} else if (kLen === 19 && key[7] === "-" && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) {
contentDispositionIdx = n6 + 1;
}
ret[n6] = key;
ret[n6 + 1] = val2;
}
if (hasContentLength && contentDispositionIdx !== -1) {
ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
}
return ret;
}
__name(parseRawHeaders, "parseRawHeaders");
function encodeRawHeaders(headers) {
if (!Array.isArray(headers)) {
throw new TypeError("expected headers to be an array");
}
return headers.map((x6) => Buffer.from(x6));
}
__name(encodeRawHeaders, "encodeRawHeaders");
function isBuffer(buffer) {
return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
}
__name(isBuffer, "isBuffer");
function assertRequestHandler(handler, method, upgrade) {
if (!handler || typeof handler !== "object") {
throw new InvalidArgumentError("handler must be an object");
}
if (typeof handler.onRequestStart === "function") {
return;
}
if (typeof handler.onConnect !== "function") {
throw new InvalidArgumentError("invalid onConnect method");
}
if (typeof handler.onError !== "function") {
throw new InvalidArgumentError("invalid onError method");
}
if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
throw new InvalidArgumentError("invalid onBodySent method");
}
if (upgrade || method === "CONNECT") {
if (typeof handler.onUpgrade !== "function") {
throw new InvalidArgumentError("invalid onUpgrade method");
}
} else {
if (typeof handler.onHeaders !== "function") {
throw new InvalidArgumentError("invalid onHeaders method");
}
if (typeof handler.onData !== "function") {
throw new InvalidArgumentError("invalid onData method");
}
if (typeof handler.onComplete !== "function") {
throw new InvalidArgumentError("invalid onComplete method");
}
}
}
__name(assertRequestHandler, "assertRequestHandler");
function isDisturbed(body) {
return !!(body && (stream2.isDisturbed(body) || body[kBodyUsed]));
}
__name(isDisturbed, "isDisturbed");
function getSocketInfo(socket) {
return {
localAddress: socket.localAddress,
localPort: socket.localPort,
remoteAddress: socket.remoteAddress,
remotePort: socket.remotePort,
remoteFamily: socket.remoteFamily,
timeout: socket.timeout,
bytesWritten: socket.bytesWritten,
bytesRead: socket.bytesRead
};
}
__name(getSocketInfo, "getSocketInfo");
function ReadableStreamFrom(iterable) {
let iterator;
return new ReadableStream(
{
async start() {
iterator = iterable[Symbol.asyncIterator]();
},
pull(controller) {
async function pull() {
const { done, value } = await iterator.next();
if (done) {
queueMicrotask(() => {
controller.close();
controller.byobRequest?.respond(0);
});
} else {
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
if (buf.byteLength) {
controller.enqueue(new Uint8Array(buf));
} else {
return await pull();
}
}
}
__name(pull, "pull");
return pull();
},
async cancel() {
await iterator.return();
},
type: "bytes"
}
);
}
__name(ReadableStreamFrom, "ReadableStreamFrom");
function isFormDataLike(object) {
return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData";
}
__name(isFormDataLike, "isFormDataLike");
function addAbortListener(signal, listener) {
if ("addEventListener" in signal) {
signal.addEventListener("abort", listener, { once: true });
return () => signal.removeEventListener("abort", listener);
}
signal.once("abort", listener);
return () => signal.removeListener("abort", listener);
}
__name(addAbortListener, "addAbortListener");
function isTokenCharCode(c6) {
switch (c6) {
case 34:
case 40:
case 41:
case 44:
case 47:
case 58:
case 59:
case 60:
case 61:
case 62:
case 63:
case 64:
case 91:
case 92:
case 93:
case 123:
case 125:
return false;
default:
return c6 >= 33 && c6 <= 126;
}
}
__name(isTokenCharCode, "isTokenCharCode");
function isValidHTTPToken(characters) {
if (characters.length === 0) {
return false;
}
for (let i5 = 0; i5 < characters.length; ++i5) {
if (!isTokenCharCode(characters.charCodeAt(i5))) {
return false;
}
}
return true;
}
__name(isValidHTTPToken, "isValidHTTPToken");
var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
function isValidHeaderValue(characters) {
return !headerCharRegex.test(characters);
}
__name(isValidHeaderValue, "isValidHeaderValue");
var rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/;
function parseRangeHeader(range) {
if (range == null || range === "") return { start: 0, end: null, size: null };
const m6 = range ? range.match(rangeHeaderRegex) : null;
return m6 ? {
start: parseInt(m6[1]),
end: m6[2] ? parseInt(m6[2]) : null,
size: m6[3] ? parseInt(m6[3]) : null
} : null;
}
__name(parseRangeHeader, "parseRangeHeader");
function addListener(obj, name2, listener) {
const listeners = obj[kListeners] ??= [];
listeners.push([name2, listener]);
obj.on(name2, listener);
return obj;
}
__name(addListener, "addListener");
function removeAllListeners(obj) {
if (obj[kListeners] != null) {
for (const [name2, listener] of obj[kListeners]) {
obj.removeListener(name2, listener);
}
obj[kListeners] = null;
}
return obj;
}
__name(removeAllListeners, "removeAllListeners");
function errorRequest(client, request4, err) {
try {
request4.onError(err);
assert44(request4.aborted);
} catch (err2) {
client.emit("error", err2);
}
}
__name(errorRequest, "errorRequest");
var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
if (!opts.timeout) {
return noop;
}
let s1 = null;
let s22 = null;
const fastTimer = timers.setFastTimeout(() => {
s1 = setImmediate(() => {
s22 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
});
}, opts.timeout);
return () => {
timers.clearFastTimeout(fastTimer);
clearImmediate(s1);
clearImmediate(s22);
};
} : (socketWeakRef, opts) => {
if (!opts.timeout) {
return noop;
}
let s1 = null;
const fastTimer = timers.setFastTimeout(() => {
s1 = setImmediate(() => {
onConnectTimeout(socketWeakRef.deref(), opts);
});
}, opts.timeout);
return () => {
timers.clearFastTimeout(fastTimer);
clearImmediate(s1);
};
};
function onConnectTimeout(socket, opts) {
if (socket == null) {
return;
}
let message = "Connect Timeout Error";
if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
} else {
message += ` (attempted address: ${opts.hostname}:${opts.port},`;
}
message += ` timeout: ${opts.timeout}ms)`;
destroy(socket, new ConnectTimeoutError(message));
}
__name(onConnectTimeout, "onConnectTimeout");
var kEnumerableProperty = /* @__PURE__ */ Object.create(null);
kEnumerableProperty.enumerable = true;
var normalizedMethodRecordsBase = {
delete: "DELETE",
DELETE: "DELETE",
get: "GET",
GET: "GET",
head: "HEAD",
HEAD: "HEAD",
options: "OPTIONS",
OPTIONS: "OPTIONS",
post: "POST",
POST: "POST",
put: "PUT",
PUT: "PUT"
};
var normalizedMethodRecords = {
...normalizedMethodRecordsBase,
patch: "patch",
PATCH: "PATCH"
};
Object.setPrototypeOf(normalizedMethodRecordsBase, null);
Object.setPrototypeOf(normalizedMethodRecords, null);
module3.exports = {
kEnumerableProperty,
isDisturbed,
isBlobLike,
parseOrigin,
parseURL: parseURL2,
getServerName,
isStream: isStream2,
isIterable,
isAsyncIterable,
isDestroyed,
headerNameToString,
bufferToLowerCasedHeaderName,
addListener,
removeAllListeners,
errorRequest,
parseRawHeaders,
encodeRawHeaders,
parseHeaders: parseHeaders2,
parseKeepAliveTimeout,
destroy,
bodyLength,
deepClone,
ReadableStreamFrom,
isBuffer,
assertRequestHandler,
getSocketInfo,
isFormDataLike,
serializePathWithQuery,
addAbortListener,
isValidHTTPToken,
isValidHeaderValue,
isTokenCharCode,
parseRangeHeader,
normalizedMethodRecordsBase,
normalizedMethodRecords,
isValidPort,
isHttpOrHttpsPrefixed,
nodeMajor,
nodeMinor,
safeHTTPMethods: Object.freeze(["GET", "HEAD", "OPTIONS", "TRACE"]),
wrapRequestBody,
setupConnectTimeout
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/stats.js
var require_stats = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/stats.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
kConnected,
kPending,
kRunning,
kSize,
kFree,
kQueued
} = require_symbols();
var ClientStats = class {
static {
__name(this, "ClientStats");
}
constructor(client) {
this.connected = client[kConnected];
this.pending = client[kPending];
this.running = client[kRunning];
this.size = client[kSize];
}
};
var PoolStats = class {
static {
__name(this, "PoolStats");
}
constructor(pool) {
this.connected = pool[kConnected];
this.free = pool[kFree];
this.pending = pool[kPending];
this.queued = pool[kQueued];
this.running = pool[kRunning];
this.size = pool[kSize];
}
};
module3.exports = { ClientStats, PoolStats };
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/diagnostics.js
var require_diagnostics = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/diagnostics.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var diagnosticsChannel = require("diagnostics_channel");
var util3 = require("util");
var undiciDebugLog = util3.debuglog("undici");
var fetchDebuglog = util3.debuglog("fetch");
var websocketDebuglog = util3.debuglog("websocket");
var channels = {
// Client
beforeConnect: diagnosticsChannel.channel("undici:client:beforeConnect"),
connected: diagnosticsChannel.channel("undici:client:connected"),
connectError: diagnosticsChannel.channel("undici:client:connectError"),
sendHeaders: diagnosticsChannel.channel("undici:client:sendHeaders"),
// Request
create: diagnosticsChannel.channel("undici:request:create"),
bodySent: diagnosticsChannel.channel("undici:request:bodySent"),
bodyChunkSent: diagnosticsChannel.channel("undici:request:bodyChunkSent"),
bodyChunkReceived: diagnosticsChannel.channel("undici:request:bodyChunkReceived"),
headers: diagnosticsChannel.channel("undici:request:headers"),
trailers: diagnosticsChannel.channel("undici:request:trailers"),
error: diagnosticsChannel.channel("undici:request:error"),
// WebSocket
open: diagnosticsChannel.channel("undici:websocket:open"),
close: diagnosticsChannel.channel("undici:websocket:close"),
socketError: diagnosticsChannel.channel("undici:websocket:socket_error"),
ping: diagnosticsChannel.channel("undici:websocket:ping"),
pong: diagnosticsChannel.channel("undici:websocket:pong")
};
var isTrackingClientEvents = false;
function trackClientEvents(debugLog = undiciDebugLog) {
if (isTrackingClientEvents) {
return;
}
isTrackingClientEvents = true;
diagnosticsChannel.subscribe(
"undici:client:beforeConnect",
(evt) => {
const {
connectParams: { version: version5, protocol, port, host }
} = evt;
debugLog(
"connecting to %s%s using %s%s",
host,
port ? `:${port}` : "",
protocol,
version5
);
}
);
diagnosticsChannel.subscribe(
"undici:client:connected",
(evt) => {
const {
connectParams: { version: version5, protocol, port, host }
} = evt;
debugLog(
"connected to %s%s using %s%s",
host,
port ? `:${port}` : "",
protocol,
version5
);
}
);
diagnosticsChannel.subscribe(
"undici:client:connectError",
(evt) => {
const {
connectParams: { version: version5, protocol, port, host },
error: error2
} = evt;
debugLog(
"connection to %s%s using %s%s errored - %s",
host,
port ? `:${port}` : "",
protocol,
version5,
error2.message
);
}
);
diagnosticsChannel.subscribe(
"undici:client:sendHeaders",
(evt) => {
const {
request: { method, path: path72, origin }
} = evt;
debugLog("sending request to %s %s%s", method, origin, path72);
}
);
}
__name(trackClientEvents, "trackClientEvents");
var isTrackingRequestEvents = false;
function trackRequestEvents(debugLog = undiciDebugLog) {
if (isTrackingRequestEvents) {
return;
}
isTrackingRequestEvents = true;
diagnosticsChannel.subscribe(
"undici:request:headers",
(evt) => {
const {
request: { method, path: path72, origin },
response: { statusCode }
} = evt;
debugLog(
"received response to %s %s%s - HTTP %d",
method,
origin,
path72,
statusCode
);
}
);
diagnosticsChannel.subscribe(
"undici:request:trailers",
(evt) => {
const {
request: { method, path: path72, origin }
} = evt;
debugLog("trailers received from %s %s%s", method, origin, path72);
}
);
diagnosticsChannel.subscribe(
"undici:request:error",
(evt) => {
const {
request: { method, path: path72, origin },
error: error2
} = evt;
debugLog(
"request to %s %s%s errored - %s",
method,
origin,
path72,
error2.message
);
}
);
}
__name(trackRequestEvents, "trackRequestEvents");
var isTrackingWebSocketEvents = false;
function trackWebSocketEvents(debugLog = websocketDebuglog) {
if (isTrackingWebSocketEvents) {
return;
}
isTrackingWebSocketEvents = true;
diagnosticsChannel.subscribe(
"undici:websocket:open",
(evt) => {
const {
address: { address, port }
} = evt;
debugLog("connection opened %s%s", address, port ? `:${port}` : "");
}
);
diagnosticsChannel.subscribe(
"undici:websocket:close",
(evt) => {
const { websocket, code, reason } = evt;
debugLog(
"closed connection to %s - %s %s",
websocket.url,
code,
reason
);
}
);
diagnosticsChannel.subscribe(
"undici:websocket:socket_error",
(err) => {
debugLog("connection errored - %s", err.message);
}
);
diagnosticsChannel.subscribe(
"undici:websocket:ping",
(evt) => {
debugLog("ping received");
}
);
diagnosticsChannel.subscribe(
"undici:websocket:pong",
(evt) => {
debugLog("pong received");
}
);
}
__name(trackWebSocketEvents, "trackWebSocketEvents");
if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
}
if (websocketDebuglog.enabled) {
trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog);
trackWebSocketEvents(websocketDebuglog);
}
module3.exports = {
channels
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/request.js
var require_request = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/request.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
InvalidArgumentError,
NotSupportedError
} = require_errors();
var assert44 = require("assert");
var {
isValidHTTPToken,
isValidHeaderValue,
isStream: isStream2,
destroy,
isBuffer,
isFormDataLike,
isIterable,
isBlobLike,
serializePathWithQuery,
assertRequestHandler,
getServerName,
normalizedMethodRecords
} = require_util();
var { channels } = require_diagnostics();
var { headerNameLowerCasedRecord } = require_constants();
var invalidPathRegex = /[^\u0021-\u00ff]/;
var kHandler = Symbol("handler");
var Request4 = class {
static {
__name(this, "Request");
}
constructor(origin, {
path: path72,
method,
body,
headers,
query,
idempotent,
blocking,
upgrade,
headersTimeout,
bodyTimeout,
reset,
expectContinue,
servername,
throwOnError
}, handler) {
if (typeof path72 !== "string") {
throw new InvalidArgumentError("path must be a string");
} else if (path72[0] !== "/" && !(path72.startsWith("http://") || path72.startsWith("https://")) && method !== "CONNECT") {
throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
} else if (invalidPathRegex.test(path72)) {
throw new InvalidArgumentError("invalid request path");
}
if (typeof method !== "string") {
throw new InvalidArgumentError("method must be a string");
} else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) {
throw new InvalidArgumentError("invalid request method");
}
if (upgrade && typeof upgrade !== "string") {
throw new InvalidArgumentError("upgrade must be a string");
}
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError("invalid headersTimeout");
}
if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
throw new InvalidArgumentError("invalid bodyTimeout");
}
if (reset != null && typeof reset !== "boolean") {
throw new InvalidArgumentError("invalid reset");
}
if (expectContinue != null && typeof expectContinue !== "boolean") {
throw new InvalidArgumentError("invalid expectContinue");
}
if (throwOnError != null) {
throw new InvalidArgumentError("invalid throwOnError");
}
this.headersTimeout = headersTimeout;
this.bodyTimeout = bodyTimeout;
this.method = method;
this.abort = null;
if (body == null) {
this.body = null;
} else if (isStream2(body)) {
this.body = body;
const rState = this.body._readableState;
if (!rState || !rState.autoDestroy) {
this.endHandler = /* @__PURE__ */ __name(function autoDestroy() {
destroy(this);
}, "autoDestroy");
this.body.on("end", this.endHandler);
}
this.errorHandler = (err) => {
if (this.abort) {
this.abort(err);
} else {
this.error = err;
}
};
this.body.on("error", this.errorHandler);
} else if (isBuffer(body)) {
this.body = body.byteLength ? body : null;
} else if (ArrayBuffer.isView(body)) {
this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
} else if (body instanceof ArrayBuffer) {
this.body = body.byteLength ? Buffer.from(body) : null;
} else if (typeof body === "string") {
this.body = body.length ? Buffer.from(body) : null;
} else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
this.body = body;
} else {
throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
}
this.completed = false;
this.aborted = false;
this.upgrade = upgrade || null;
this.path = query ? serializePathWithQuery(path72, query) : path72;
this.origin = origin;
this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
this.blocking = blocking ?? this.method !== "HEAD";
this.reset = reset == null ? null : reset;
this.host = null;
this.contentLength = null;
this.contentType = null;
this.headers = [];
this.expectContinue = expectContinue != null ? expectContinue : false;
if (Array.isArray(headers)) {
if (headers.length % 2 !== 0) {
throw new InvalidArgumentError("headers array must be even");
}
for (let i5 = 0; i5 < headers.length; i5 += 2) {
processHeader(this, headers[i5], headers[i5 + 1]);
}
} else if (headers && typeof headers === "object") {
if (headers[Symbol.iterator]) {
for (const header of headers) {
if (!Array.isArray(header) || header.length !== 2) {
throw new InvalidArgumentError("headers must be in key-value pair format");
}
processHeader(this, header[0], header[1]);
}
} else {
const keys = Object.keys(headers);
for (let i5 = 0; i5 < keys.length; ++i5) {
processHeader(this, keys[i5], headers[keys[i5]]);
}
}
} else if (headers != null) {
throw new InvalidArgumentError("headers must be an object or an array");
}
assertRequestHandler(handler, method, upgrade);
this.servername = servername || getServerName(this.host) || null;
this[kHandler] = handler;
if (channels.create.hasSubscribers) {
channels.create.publish({ request: this });
}
}
onBodySent(chunk) {
if (channels.bodyChunkSent.hasSubscribers) {
channels.bodyChunkSent.publish({ request: this, chunk });
}
if (this[kHandler].onBodySent) {
try {
return this[kHandler].onBodySent(chunk);
} catch (err) {
this.abort(err);
}
}
}
onRequestSent() {
if (channels.bodySent.hasSubscribers) {
channels.bodySent.publish({ request: this });
}
if (this[kHandler].onRequestSent) {
try {
return this[kHandler].onRequestSent();
} catch (err) {
this.abort(err);
}
}
}
onConnect(abort) {
assert44(!this.aborted);
assert44(!this.completed);
if (this.error) {
abort(this.error);
} else {
this.abort = abort;
return this[kHandler].onConnect(abort);
}
}
onResponseStarted() {
return this[kHandler].onResponseStarted?.();
}
onHeaders(statusCode, headers, resume, statusText) {
assert44(!this.aborted);
assert44(!this.completed);
if (channels.headers.hasSubscribers) {
channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
}
try {
return this[kHandler].onHeaders(statusCode, headers, resume, statusText);
} catch (err) {
this.abort(err);
}
}
onData(chunk) {
assert44(!this.aborted);
assert44(!this.completed);
if (channels.bodyChunkReceived.hasSubscribers) {
channels.bodyChunkReceived.publish({ request: this, chunk });
}
try {
return this[kHandler].onData(chunk);
} catch (err) {
this.abort(err);
return false;
}
}
onUpgrade(statusCode, headers, socket) {
assert44(!this.aborted);
assert44(!this.completed);
return this[kHandler].onUpgrade(statusCode, headers, socket);
}
onComplete(trailers) {
this.onFinally();
assert44(!this.aborted);
assert44(!this.completed);
this.completed = true;
if (channels.trailers.hasSubscribers) {
channels.trailers.publish({ request: this, trailers });
}
try {
return this[kHandler].onComplete(trailers);
} catch (err) {
this.onError(err);
}
}
onError(error2) {
this.onFinally();
if (channels.error.hasSubscribers) {
channels.error.publish({ request: this, error: error2 });
}
if (this.aborted) {
return;
}
this.aborted = true;
return this[kHandler].onError(error2);
}
onFinally() {
if (this.errorHandler) {
this.body.off("error", this.errorHandler);
this.errorHandler = null;
}
if (this.endHandler) {
this.body.off("end", this.endHandler);
this.endHandler = null;
}
}
addHeader(key, value) {
processHeader(this, key, value);
return this;
}
};
function processHeader(request4, key, val2) {
if (val2 && (typeof val2 === "object" && !Array.isArray(val2))) {
throw new InvalidArgumentError(`invalid ${key} header`);
} else if (val2 === void 0) {
return;
}
let headerName = headerNameLowerCasedRecord[key];
if (headerName === void 0) {
headerName = key.toLowerCase();
if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
throw new InvalidArgumentError("invalid header key");
}
}
if (Array.isArray(val2)) {
const arr = [];
for (let i5 = 0; i5 < val2.length; i5++) {
if (typeof val2[i5] === "string") {
if (!isValidHeaderValue(val2[i5])) {
throw new InvalidArgumentError(`invalid ${key} header`);
}
arr.push(val2[i5]);
} else if (val2[i5] === null) {
arr.push("");
} else if (typeof val2[i5] === "object") {
throw new InvalidArgumentError(`invalid ${key} header`);
} else {
arr.push(`${val2[i5]}`);
}
}
val2 = arr;
} else if (typeof val2 === "string") {
if (!isValidHeaderValue(val2)) {
throw new InvalidArgumentError(`invalid ${key} header`);
}
} else if (val2 === null) {
val2 = "";
} else {
val2 = `${val2}`;
}
if (request4.host === null && headerName === "host") {
if (typeof val2 !== "string") {
throw new InvalidArgumentError("invalid host header");
}
request4.host = val2;
} else if (request4.contentLength === null && headerName === "content-length") {
request4.contentLength = parseInt(val2, 10);
if (!Number.isFinite(request4.contentLength)) {
throw new InvalidArgumentError("invalid content-length header");
}
} else if (request4.contentType === null && headerName === "content-type") {
request4.contentType = val2;
request4.headers.push(key, val2);
} else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") {
throw new InvalidArgumentError(`invalid ${headerName} header`);
} else if (headerName === "connection") {
const value = typeof val2 === "string" ? val2.toLowerCase() : null;
if (value !== "close" && value !== "keep-alive") {
throw new InvalidArgumentError("invalid connection header");
}
if (value === "close") {
request4.reset = true;
}
} else if (headerName === "expect") {
throw new NotSupportedError("expect header not supported");
} else {
request4.headers.push(key, val2);
}
}
__name(processHeader, "processHeader");
module3.exports = Request4;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/wrap-handler.js
var require_wrap_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/wrap-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { InvalidArgumentError } = require_errors();
module3.exports = class WrapHandler {
static {
__name(this, "WrapHandler");
}
#handler;
constructor(handler) {
this.#handler = handler;
}
static wrap(handler) {
return handler.onRequestStart ? handler : new WrapHandler(handler);
}
// Unwrap Interface
onConnect(abort, context2) {
return this.#handler.onConnect?.(abort, context2);
}
onHeaders(statusCode, rawHeaders, resume, statusMessage) {
return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage);
}
onUpgrade(statusCode, rawHeaders, socket) {
return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
}
onData(data) {
return this.#handler.onData?.(data);
}
onComplete(trailers) {
return this.#handler.onComplete?.(trailers);
}
onError(err) {
if (!this.#handler.onError) {
throw err;
}
return this.#handler.onError?.(err);
}
// Wrap Interface
onRequestStart(controller, context2) {
this.#handler.onConnect?.((reason) => controller.abort(reason), context2);
}
onRequestUpgrade(controller, statusCode, headers, socket) {
const rawHeaders = [];
for (const [key, val2] of Object.entries(headers)) {
rawHeaders.push(Buffer.from(key), Array.isArray(val2) ? val2.map((v7) => Buffer.from(v7)) : Buffer.from(val2));
}
this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
const rawHeaders = [];
for (const [key, val2] of Object.entries(headers)) {
rawHeaders.push(Buffer.from(key), Array.isArray(val2) ? val2.map((v7) => Buffer.from(v7)) : Buffer.from(val2));
}
if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
controller.pause();
}
}
onResponseData(controller, data) {
if (this.#handler.onData?.(data) === false) {
controller.pause();
}
}
onResponseEnd(controller, trailers) {
const rawTrailers = [];
for (const [key, val2] of Object.entries(trailers)) {
rawTrailers.push(Buffer.from(key), Array.isArray(val2) ? val2.map((v7) => Buffer.from(v7)) : Buffer.from(val2));
}
this.#handler.onComplete?.(rawTrailers);
}
onResponseError(controller, err) {
if (!this.#handler.onError) {
throw new InvalidArgumentError("invalid onError method");
}
this.#handler.onError?.(err);
}
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/dispatcher.js
var require_dispatcher = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var EventEmitter5 = require("events");
var WrapHandler = require_wrap_handler();
var wrapInterceptor = /* @__PURE__ */ __name((dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)), "wrapInterceptor");
var Dispatcher2 = class extends EventEmitter5 {
static {
__name(this, "Dispatcher");
}
dispatch() {
throw new Error("not implemented");
}
close() {
throw new Error("not implemented");
}
destroy() {
throw new Error("not implemented");
}
compose(...args) {
const interceptors = Array.isArray(args[0]) ? args[0] : args;
let dispatch = this.dispatch.bind(this);
for (const interceptor of interceptors) {
if (interceptor == null) {
continue;
}
if (typeof interceptor !== "function") {
throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
}
dispatch = interceptor(dispatch);
dispatch = wrapInterceptor(dispatch);
if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
throw new TypeError("invalid interceptor");
}
}
return new Proxy(this, {
get: /* @__PURE__ */ __name((target, key) => key === "dispatch" ? dispatch : target[key], "get")
});
}
};
module3.exports = Dispatcher2;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/unwrap-handler.js
var require_unwrap_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/unwrap-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { parseHeaders: parseHeaders2 } = require_util();
var { InvalidArgumentError } = require_errors();
var kResume = Symbol("resume");
var UnwrapController = class {
static {
__name(this, "UnwrapController");
}
#paused = false;
#reason = null;
#aborted = false;
#abort;
[kResume] = null;
constructor(abort) {
this.#abort = abort;
}
pause() {
this.#paused = true;
}
resume() {
if (this.#paused) {
this.#paused = false;
this[kResume]?.();
}
}
abort(reason) {
if (!this.#aborted) {
this.#aborted = true;
this.#reason = reason;
this.#abort(reason);
}
}
get aborted() {
return this.#aborted;
}
get reason() {
return this.#reason;
}
get paused() {
return this.#paused;
}
};
module3.exports = class UnwrapHandler {
static {
__name(this, "UnwrapHandler");
}
#handler;
#controller;
constructor(handler) {
this.#handler = handler;
}
static unwrap(handler) {
return !handler.onRequestStart ? handler : new UnwrapHandler(handler);
}
onConnect(abort, context2) {
this.#controller = new UnwrapController(abort);
this.#handler.onRequestStart?.(this.#controller, context2);
}
onUpgrade(statusCode, rawHeaders, socket) {
this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders2(rawHeaders), socket);
}
onHeaders(statusCode, rawHeaders, resume, statusMessage) {
this.#controller[kResume] = resume;
this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders2(rawHeaders), statusMessage);
return !this.#controller.paused;
}
onData(data) {
this.#handler.onResponseData?.(this.#controller, data);
return !this.#controller.paused;
}
onComplete(rawTrailers) {
this.#handler.onResponseEnd?.(this.#controller, parseHeaders2(rawTrailers));
}
onError(err) {
if (!this.#handler.onResponseError) {
throw new InvalidArgumentError("invalid onError method");
}
this.#handler.onResponseError?.(this.#controller, err);
}
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var Dispatcher2 = require_dispatcher();
var UnwrapHandler = require_unwrap_handler();
var {
ClientDestroyedError,
ClientClosedError,
InvalidArgumentError
} = require_errors();
var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
var kOnDestroyed = Symbol("onDestroyed");
var kOnClosed = Symbol("onClosed");
var DispatcherBase = class extends Dispatcher2 {
static {
__name(this, "DispatcherBase");
}
constructor() {
super();
this[kDestroyed] = false;
this[kOnDestroyed] = null;
this[kClosed] = false;
this[kOnClosed] = [];
}
get destroyed() {
return this[kDestroyed];
}
get closed() {
return this[kClosed];
}
close(callback) {
if (callback === void 0) {
return new Promise((resolve25, reject) => {
this.close((err, data) => {
return err ? reject(err) : resolve25(data);
});
});
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (this[kDestroyed]) {
queueMicrotask(() => callback(new ClientDestroyedError(), null));
return;
}
if (this[kClosed]) {
if (this[kOnClosed]) {
this[kOnClosed].push(callback);
} else {
queueMicrotask(() => callback(null, null));
}
return;
}
this[kClosed] = true;
this[kOnClosed].push(callback);
const onClosed = /* @__PURE__ */ __name(() => {
const callbacks = this[kOnClosed];
this[kOnClosed] = null;
for (let i5 = 0; i5 < callbacks.length; i5++) {
callbacks[i5](null, null);
}
}, "onClosed");
this[kClose]().then(() => this.destroy()).then(() => {
queueMicrotask(onClosed);
});
}
destroy(err, callback) {
if (typeof err === "function") {
callback = err;
err = null;
}
if (callback === void 0) {
return new Promise((resolve25, reject) => {
this.destroy(err, (err2, data) => {
return err2 ? (
/* istanbul ignore next: should never error */
reject(err2)
) : resolve25(data);
});
});
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (this[kDestroyed]) {
if (this[kOnDestroyed]) {
this[kOnDestroyed].push(callback);
} else {
queueMicrotask(() => callback(null, null));
}
return;
}
if (!err) {
err = new ClientDestroyedError();
}
this[kDestroyed] = true;
this[kOnDestroyed] = this[kOnDestroyed] || [];
this[kOnDestroyed].push(callback);
const onDestroyed = /* @__PURE__ */ __name(() => {
const callbacks = this[kOnDestroyed];
this[kOnDestroyed] = null;
for (let i5 = 0; i5 < callbacks.length; i5++) {
callbacks[i5](null, null);
}
}, "onDestroyed");
this[kDestroy](err).then(() => {
queueMicrotask(onDestroyed);
});
}
dispatch(opts, handler) {
if (!handler || typeof handler !== "object") {
throw new InvalidArgumentError("handler must be an object");
}
handler = UnwrapHandler.unwrap(handler);
try {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("opts must be an object.");
}
if (this[kDestroyed] || this[kOnDestroyed]) {
throw new ClientDestroyedError();
}
if (this[kClosed]) {
throw new ClientClosedError();
}
return this[kDispatch](opts, handler);
} catch (err) {
if (typeof handler.onError !== "function") {
throw err;
}
handler.onError(err);
return false;
}
}
};
module3.exports = DispatcherBase;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/connect.js
var require_connect = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/core/connect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var net2 = require("net");
var assert44 = require("assert");
var util3 = require_util();
var { InvalidArgumentError } = require_errors();
var tls;
var SessionCache = class WeakSessionCache {
static {
__name(this, "WeakSessionCache");
}
constructor(maxCachedSessions) {
this._maxCachedSessions = maxCachedSessions;
this._sessionCache = /* @__PURE__ */ new Map();
this._sessionRegistry = new FinalizationRegistry((key) => {
if (this._sessionCache.size < this._maxCachedSessions) {
return;
}
const ref = this._sessionCache.get(key);
if (ref !== void 0 && ref.deref() === void 0) {
this._sessionCache.delete(key);
}
});
}
get(sessionKey) {
const ref = this._sessionCache.get(sessionKey);
return ref ? ref.deref() : null;
}
set(sessionKey, session) {
if (this._maxCachedSessions === 0) {
return;
}
this._sessionCache.set(sessionKey, new WeakRef(session));
this._sessionRegistry.register(session, sessionKey);
}
};
function buildConnector({ allowH2, maxCachedSessions, socketPath, timeout: timeout2, session: customSession, ...opts }) {
if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
throw new InvalidArgumentError("maxCachedSessions must be a positive integer or zero");
}
const options = { path: socketPath, ...opts };
const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions);
timeout2 = timeout2 == null ? 1e4 : timeout2;
allowH2 = allowH2 != null ? allowH2 : false;
return /* @__PURE__ */ __name(function connect({ hostname: hostname2, host, protocol, port, servername, localAddress, httpSocket }, callback) {
let socket;
if (protocol === "https:") {
if (!tls) {
tls = require("tls");
}
servername = servername || options.servername || util3.getServerName(host) || null;
const sessionKey = servername || hostname2;
assert44(sessionKey);
const session = customSession || sessionCache.get(sessionKey) || null;
port = port || 443;
socket = tls.connect({
highWaterMark: 16384,
// TLS in node can't have bigger HWM anyway...
...options,
servername,
session,
localAddress,
ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
socket: httpSocket,
// upgrade socket connection
port,
host: hostname2
});
socket.on("session", function(session2) {
sessionCache.set(sessionKey, session2);
});
} else {
assert44(!httpSocket, "httpSocket can only be sent on TLS update");
port = port || 80;
socket = net2.connect({
highWaterMark: 64 * 1024,
// Same as nodejs fs streams.
...options,
localAddress,
port,
host: hostname2
});
}
if (options.keepAlive == null || options.keepAlive) {
const keepAliveInitialDelay = options.keepAliveInitialDelay === void 0 ? 6e4 : options.keepAliveInitialDelay;
socket.setKeepAlive(true, keepAliveInitialDelay);
}
const clearConnectTimeout = util3.setupConnectTimeout(new WeakRef(socket), { timeout: timeout2, hostname: hostname2, port });
socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
queueMicrotask(clearConnectTimeout);
if (callback) {
const cb2 = callback;
callback = null;
cb2(null, this);
}
}).on("error", function(err) {
queueMicrotask(clearConnectTimeout);
if (callback) {
const cb2 = callback;
callback = null;
cb2(err);
}
});
return socket;
}, "connect");
}
__name(buildConnector, "buildConnector");
module3.exports = buildConnector;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/utils.js
var require_utils = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/utils.js"(exports2) {
"use strict";
init_import_meta_url();
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.enumToMap = void 0;
function enumToMap(obj, filter = [], exceptions = []) {
var _a4, _b2;
const emptyFilter = ((_a4 = filter === null || filter === void 0 ? void 0 : filter.length) !== null && _a4 !== void 0 ? _a4 : 0) === 0;
const emptyExceptions = ((_b2 = exceptions === null || exceptions === void 0 ? void 0 : exceptions.length) !== null && _b2 !== void 0 ? _b2 : 0) === 0;
return Object.fromEntries(Object.entries(obj).filter(([, value]) => {
return typeof value === "number" && (emptyFilter || filter.includes(value)) && (emptyExceptions || !exceptions.includes(value));
}));
}
__name(enumToMap, "enumToMap");
exports2.enumToMap = enumToMap;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/constants.js
var require_constants2 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/constants.js"(exports2) {
"use strict";
init_import_meta_url();
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.SPECIAL_HEADERS = exports2.MINOR = exports2.MAJOR = exports2.HTAB_SP_VCHAR_OBS_TEXT = exports2.QUOTED_STRING = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.STATUSES_HTTP = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.HEADER_STATE = exports2.FINISH = exports2.STATUSES = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0;
var utils_1 = require_utils();
exports2.ERROR = {
OK: 0,
INTERNAL: 1,
STRICT: 2,
CR_EXPECTED: 25,
LF_EXPECTED: 3,
UNEXPECTED_CONTENT_LENGTH: 4,
UNEXPECTED_SPACE: 30,
CLOSED_CONNECTION: 5,
INVALID_METHOD: 6,
INVALID_URL: 7,
INVALID_CONSTANT: 8,
INVALID_VERSION: 9,
INVALID_HEADER_TOKEN: 10,
INVALID_CONTENT_LENGTH: 11,
INVALID_CHUNK_SIZE: 12,
INVALID_STATUS: 13,
INVALID_EOF_STATE: 14,
INVALID_TRANSFER_ENCODING: 15,
CB_MESSAGE_BEGIN: 16,
CB_HEADERS_COMPLETE: 17,
CB_MESSAGE_COMPLETE: 18,
CB_CHUNK_HEADER: 19,
CB_CHUNK_COMPLETE: 20,
PAUSED: 21,
PAUSED_UPGRADE: 22,
PAUSED_H2_UPGRADE: 23,
USER: 24,
CB_URL_COMPLETE: 26,
CB_STATUS_COMPLETE: 27,
CB_METHOD_COMPLETE: 32,
CB_VERSION_COMPLETE: 33,
CB_HEADER_FIELD_COMPLETE: 28,
CB_HEADER_VALUE_COMPLETE: 29,
CB_CHUNK_EXTENSION_NAME_COMPLETE: 34,
CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35,
CB_RESET: 31
};
exports2.TYPE = {
BOTH: 0,
// default
REQUEST: 1,
RESPONSE: 2
};
exports2.FLAGS = {
CONNECTION_KEEP_ALIVE: 1 << 0,
CONNECTION_CLOSE: 1 << 1,
CONNECTION_UPGRADE: 1 << 2,
CHUNKED: 1 << 3,
UPGRADE: 1 << 4,
CONTENT_LENGTH: 1 << 5,
SKIPBODY: 1 << 6,
TRAILING: 1 << 7,
// 1 << 8 is unused
TRANSFER_ENCODING: 1 << 9
};
exports2.LENIENT_FLAGS = {
HEADERS: 1 << 0,
CHUNKED_LENGTH: 1 << 1,
KEEP_ALIVE: 1 << 2,
TRANSFER_ENCODING: 1 << 3,
VERSION: 1 << 4,
DATA_AFTER_CLOSE: 1 << 5,
OPTIONAL_LF_AFTER_CR: 1 << 6,
OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7,
OPTIONAL_CR_BEFORE_LF: 1 << 8,
SPACES_AFTER_CHUNK_SIZE: 1 << 9
};
exports2.METHODS = {
"DELETE": 0,
"GET": 1,
"HEAD": 2,
"POST": 3,
"PUT": 4,
/* pathological */
"CONNECT": 5,
"OPTIONS": 6,
"TRACE": 7,
/* WebDAV */
"COPY": 8,
"LOCK": 9,
"MKCOL": 10,
"MOVE": 11,
"PROPFIND": 12,
"PROPPATCH": 13,
"SEARCH": 14,
"UNLOCK": 15,
"BIND": 16,
"REBIND": 17,
"UNBIND": 18,
"ACL": 19,
/* subversion */
"REPORT": 20,
"MKACTIVITY": 21,
"CHECKOUT": 22,
"MERGE": 23,
/* upnp */
"M-SEARCH": 24,
"NOTIFY": 25,
"SUBSCRIBE": 26,
"UNSUBSCRIBE": 27,
/* RFC-5789 */
"PATCH": 28,
"PURGE": 29,
/* CalDAV */
"MKCALENDAR": 30,
/* RFC-2068, section 19.6.1.2 */
"LINK": 31,
"UNLINK": 32,
/* icecast */
"SOURCE": 33,
/* RFC-7540, section 11.6 */
"PRI": 34,
/* RFC-2326 RTSP */
"DESCRIBE": 35,
"ANNOUNCE": 36,
"SETUP": 37,
"PLAY": 38,
"PAUSE": 39,
"TEARDOWN": 40,
"GET_PARAMETER": 41,
"SET_PARAMETER": 42,
"REDIRECT": 43,
"RECORD": 44,
/* RAOP */
"FLUSH": 45,
/* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */
"QUERY": 46
};
exports2.STATUSES = {
CONTINUE: 100,
SWITCHING_PROTOCOLS: 101,
PROCESSING: 102,
EARLY_HINTS: 103,
RESPONSE_IS_STALE: 110,
// Unofficial
REVALIDATION_FAILED: 111,
// Unofficial
DISCONNECTED_OPERATION: 112,
// Unofficial
HEURISTIC_EXPIRATION: 113,
// Unofficial
MISCELLANEOUS_WARNING: 199,
// Unofficial
OK: 200,
CREATED: 201,
ACCEPTED: 202,
NON_AUTHORITATIVE_INFORMATION: 203,
NO_CONTENT: 204,
RESET_CONTENT: 205,
PARTIAL_CONTENT: 206,
MULTI_STATUS: 207,
ALREADY_REPORTED: 208,
TRANSFORMATION_APPLIED: 214,
// Unofficial
IM_USED: 226,
MISCELLANEOUS_PERSISTENT_WARNING: 299,
// Unofficial
MULTIPLE_CHOICES: 300,
MOVED_PERMANENTLY: 301,
FOUND: 302,
SEE_OTHER: 303,
NOT_MODIFIED: 304,
USE_PROXY: 305,
SWITCH_PROXY: 306,
// No longer used
TEMPORARY_REDIRECT: 307,
PERMANENT_REDIRECT: 308,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
PAYMENT_REQUIRED: 402,
FORBIDDEN: 403,
NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
NOT_ACCEPTABLE: 406,
PROXY_AUTHENTICATION_REQUIRED: 407,
REQUEST_TIMEOUT: 408,
CONFLICT: 409,
GONE: 410,
LENGTH_REQUIRED: 411,
PRECONDITION_FAILED: 412,
PAYLOAD_TOO_LARGE: 413,
URI_TOO_LONG: 414,
UNSUPPORTED_MEDIA_TYPE: 415,
RANGE_NOT_SATISFIABLE: 416,
EXPECTATION_FAILED: 417,
IM_A_TEAPOT: 418,
PAGE_EXPIRED: 419,
// Unofficial
ENHANCE_YOUR_CALM: 420,
// Unofficial
MISDIRECTED_REQUEST: 421,
UNPROCESSABLE_ENTITY: 422,
LOCKED: 423,
FAILED_DEPENDENCY: 424,
TOO_EARLY: 425,
UPGRADE_REQUIRED: 426,
PRECONDITION_REQUIRED: 428,
TOO_MANY_REQUESTS: 429,
REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430,
// Unofficial
REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
LOGIN_TIMEOUT: 440,
// Unofficial
NO_RESPONSE: 444,
// Unofficial
RETRY_WITH: 449,
// Unofficial
BLOCKED_BY_PARENTAL_CONTROL: 450,
// Unofficial
UNAVAILABLE_FOR_LEGAL_REASONS: 451,
CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460,
// Unofficial
INVALID_X_FORWARDED_FOR: 463,
// Unofficial
REQUEST_HEADER_TOO_LARGE: 494,
// Unofficial
SSL_CERTIFICATE_ERROR: 495,
// Unofficial
SSL_CERTIFICATE_REQUIRED: 496,
// Unofficial
HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497,
// Unofficial
INVALID_TOKEN: 498,
// Unofficial
CLIENT_CLOSED_REQUEST: 499,
// Unofficial
INTERNAL_SERVER_ERROR: 500,
NOT_IMPLEMENTED: 501,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504,
HTTP_VERSION_NOT_SUPPORTED: 505,
VARIANT_ALSO_NEGOTIATES: 506,
INSUFFICIENT_STORAGE: 507,
LOOP_DETECTED: 508,
BANDWIDTH_LIMIT_EXCEEDED: 509,
NOT_EXTENDED: 510,
NETWORK_AUTHENTICATION_REQUIRED: 511,
WEB_SERVER_UNKNOWN_ERROR: 520,
// Unofficial
WEB_SERVER_IS_DOWN: 521,
// Unofficial
CONNECTION_TIMEOUT: 522,
// Unofficial
ORIGIN_IS_UNREACHABLE: 523,
// Unofficial
TIMEOUT_OCCURED: 524,
// Unofficial
SSL_HANDSHAKE_FAILED: 525,
// Unofficial
INVALID_SSL_CERTIFICATE: 526,
// Unofficial
RAILGUN_ERROR: 527,
// Unofficial
SITE_IS_OVERLOADED: 529,
// Unofficial
SITE_IS_FROZEN: 530,
// Unofficial
IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561,
// Unofficial
NETWORK_READ_TIMEOUT: 598,
// Unofficial
NETWORK_CONNECT_TIMEOUT: 599
// Unofficial
};
exports2.FINISH = {
SAFE: 0,
SAFE_WITH_CB: 1,
UNSAFE: 2
};
exports2.HEADER_STATE = {
GENERAL: 0,
CONNECTION: 1,
CONTENT_LENGTH: 2,
TRANSFER_ENCODING: 3,
UPGRADE: 4,
CONNECTION_KEEP_ALIVE: 5,
CONNECTION_CLOSE: 6,
CONNECTION_UPGRADE: 7,
TRANSFER_ENCODING_CHUNKED: 8
};
exports2.METHODS_HTTP = [
exports2.METHODS.DELETE,
exports2.METHODS.GET,
exports2.METHODS.HEAD,
exports2.METHODS.POST,
exports2.METHODS.PUT,
exports2.METHODS.CONNECT,
exports2.METHODS.OPTIONS,
exports2.METHODS.TRACE,
exports2.METHODS.COPY,
exports2.METHODS.LOCK,
exports2.METHODS.MKCOL,
exports2.METHODS.MOVE,
exports2.METHODS.PROPFIND,
exports2.METHODS.PROPPATCH,
exports2.METHODS.SEARCH,
exports2.METHODS.UNLOCK,
exports2.METHODS.BIND,
exports2.METHODS.REBIND,
exports2.METHODS.UNBIND,
exports2.METHODS.ACL,
exports2.METHODS.REPORT,
exports2.METHODS.MKACTIVITY,
exports2.METHODS.CHECKOUT,
exports2.METHODS.MERGE,
exports2.METHODS["M-SEARCH"],
exports2.METHODS.NOTIFY,
exports2.METHODS.SUBSCRIBE,
exports2.METHODS.UNSUBSCRIBE,
exports2.METHODS.PATCH,
exports2.METHODS.PURGE,
exports2.METHODS.MKCALENDAR,
exports2.METHODS.LINK,
exports2.METHODS.UNLINK,
exports2.METHODS.PRI,
// TODO(indutny): should we allow it with HTTP?
exports2.METHODS.SOURCE,
exports2.METHODS.QUERY
];
exports2.METHODS_ICE = [
exports2.METHODS.SOURCE
];
exports2.METHODS_RTSP = [
exports2.METHODS.OPTIONS,
exports2.METHODS.DESCRIBE,
exports2.METHODS.ANNOUNCE,
exports2.METHODS.SETUP,
exports2.METHODS.PLAY,
exports2.METHODS.PAUSE,
exports2.METHODS.TEARDOWN,
exports2.METHODS.GET_PARAMETER,
exports2.METHODS.SET_PARAMETER,
exports2.METHODS.REDIRECT,
exports2.METHODS.RECORD,
exports2.METHODS.FLUSH,
// For AirPlay
exports2.METHODS.GET,
exports2.METHODS.POST
];
exports2.METHOD_MAP = (0, utils_1.enumToMap)(exports2.METHODS);
exports2.H_METHOD_MAP = Object.fromEntries(Object.entries(exports2.METHODS).filter(([k6]) => k6.startsWith("H")));
exports2.STATUSES_HTTP = [
exports2.STATUSES.CONTINUE,
exports2.STATUSES.SWITCHING_PROTOCOLS,
exports2.STATUSES.PROCESSING,
exports2.STATUSES.EARLY_HINTS,
exports2.STATUSES.RESPONSE_IS_STALE,
exports2.STATUSES.REVALIDATION_FAILED,
exports2.STATUSES.DISCONNECTED_OPERATION,
exports2.STATUSES.HEURISTIC_EXPIRATION,
exports2.STATUSES.MISCELLANEOUS_WARNING,
exports2.STATUSES.OK,
exports2.STATUSES.CREATED,
exports2.STATUSES.ACCEPTED,
exports2.STATUSES.NON_AUTHORITATIVE_INFORMATION,
exports2.STATUSES.NO_CONTENT,
exports2.STATUSES.RESET_CONTENT,
exports2.STATUSES.PARTIAL_CONTENT,
exports2.STATUSES.MULTI_STATUS,
exports2.STATUSES.ALREADY_REPORTED,
exports2.STATUSES.TRANSFORMATION_APPLIED,
exports2.STATUSES.IM_USED,
exports2.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING,
exports2.STATUSES.MULTIPLE_CHOICES,
exports2.STATUSES.MOVED_PERMANENTLY,
exports2.STATUSES.FOUND,
exports2.STATUSES.SEE_OTHER,
exports2.STATUSES.NOT_MODIFIED,
exports2.STATUSES.USE_PROXY,
exports2.STATUSES.SWITCH_PROXY,
exports2.STATUSES.TEMPORARY_REDIRECT,
exports2.STATUSES.PERMANENT_REDIRECT,
exports2.STATUSES.BAD_REQUEST,
exports2.STATUSES.UNAUTHORIZED,
exports2.STATUSES.PAYMENT_REQUIRED,
exports2.STATUSES.FORBIDDEN,
exports2.STATUSES.NOT_FOUND,
exports2.STATUSES.METHOD_NOT_ALLOWED,
exports2.STATUSES.NOT_ACCEPTABLE,
exports2.STATUSES.PROXY_AUTHENTICATION_REQUIRED,
exports2.STATUSES.REQUEST_TIMEOUT,
exports2.STATUSES.CONFLICT,
exports2.STATUSES.GONE,
exports2.STATUSES.LENGTH_REQUIRED,
exports2.STATUSES.PRECONDITION_FAILED,
exports2.STATUSES.PAYLOAD_TOO_LARGE,
exports2.STATUSES.URI_TOO_LONG,
exports2.STATUSES.UNSUPPORTED_MEDIA_TYPE,
exports2.STATUSES.RANGE_NOT_SATISFIABLE,
exports2.STATUSES.EXPECTATION_FAILED,
exports2.STATUSES.IM_A_TEAPOT,
exports2.STATUSES.PAGE_EXPIRED,
exports2.STATUSES.ENHANCE_YOUR_CALM,
exports2.STATUSES.MISDIRECTED_REQUEST,
exports2.STATUSES.UNPROCESSABLE_ENTITY,
exports2.STATUSES.LOCKED,
exports2.STATUSES.FAILED_DEPENDENCY,
exports2.STATUSES.TOO_EARLY,
exports2.STATUSES.UPGRADE_REQUIRED,
exports2.STATUSES.PRECONDITION_REQUIRED,
exports2.STATUSES.TOO_MANY_REQUESTS,
exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL,
exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE,
exports2.STATUSES.LOGIN_TIMEOUT,
exports2.STATUSES.NO_RESPONSE,
exports2.STATUSES.RETRY_WITH,
exports2.STATUSES.BLOCKED_BY_PARENTAL_CONTROL,
exports2.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS,
exports2.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST,
exports2.STATUSES.INVALID_X_FORWARDED_FOR,
exports2.STATUSES.REQUEST_HEADER_TOO_LARGE,
exports2.STATUSES.SSL_CERTIFICATE_ERROR,
exports2.STATUSES.SSL_CERTIFICATE_REQUIRED,
exports2.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT,
exports2.STATUSES.INVALID_TOKEN,
exports2.STATUSES.CLIENT_CLOSED_REQUEST,
exports2.STATUSES.INTERNAL_SERVER_ERROR,
exports2.STATUSES.NOT_IMPLEMENTED,
exports2.STATUSES.BAD_GATEWAY,
exports2.STATUSES.SERVICE_UNAVAILABLE,
exports2.STATUSES.GATEWAY_TIMEOUT,
exports2.STATUSES.HTTP_VERSION_NOT_SUPPORTED,
exports2.STATUSES.VARIANT_ALSO_NEGOTIATES,
exports2.STATUSES.INSUFFICIENT_STORAGE,
exports2.STATUSES.LOOP_DETECTED,
exports2.STATUSES.BANDWIDTH_LIMIT_EXCEEDED,
exports2.STATUSES.NOT_EXTENDED,
exports2.STATUSES.NETWORK_AUTHENTICATION_REQUIRED,
exports2.STATUSES.WEB_SERVER_UNKNOWN_ERROR,
exports2.STATUSES.WEB_SERVER_IS_DOWN,
exports2.STATUSES.CONNECTION_TIMEOUT,
exports2.STATUSES.ORIGIN_IS_UNREACHABLE,
exports2.STATUSES.TIMEOUT_OCCURED,
exports2.STATUSES.SSL_HANDSHAKE_FAILED,
exports2.STATUSES.INVALID_SSL_CERTIFICATE,
exports2.STATUSES.RAILGUN_ERROR,
exports2.STATUSES.SITE_IS_OVERLOADED,
exports2.STATUSES.SITE_IS_FROZEN,
exports2.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR,
exports2.STATUSES.NETWORK_READ_TIMEOUT,
exports2.STATUSES.NETWORK_CONNECT_TIMEOUT
];
exports2.ALPHA = [];
for (let i5 = "A".charCodeAt(0); i5 <= "Z".charCodeAt(0); i5++) {
exports2.ALPHA.push(String.fromCharCode(i5));
exports2.ALPHA.push(String.fromCharCode(i5 + 32));
}
exports2.NUM_MAP = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9
};
exports2.HEX_MAP = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15,
a: 10,
b: 11,
c: 12,
d: 13,
e: 14,
f: 15
};
exports2.NUM = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];
exports2.ALPHANUM = exports2.ALPHA.concat(exports2.NUM);
exports2.MARK = ["-", "_", ".", "!", "~", "*", "'", "(", ")"];
exports2.USERINFO_CHARS = exports2.ALPHANUM.concat(exports2.MARK).concat(["%", ";", ":", "&", "=", "+", "$", ","]);
exports2.URL_CHAR = [
"!",
'"',
"$",
"%",
"&",
"'",
"(",
")",
"*",
"+",
",",
"-",
".",
"/",
":",
";",
"<",
"=",
">",
"@",
"[",
"\\",
"]",
"^",
"_",
"`",
"{",
"|",
"}",
"~"
].concat(exports2.ALPHANUM);
exports2.HEX = exports2.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
exports2.TOKEN = [
"!",
"#",
"$",
"%",
"&",
"'",
"*",
"+",
"-",
".",
"^",
"_",
"`",
"|",
"~"
].concat(exports2.ALPHANUM);
exports2.HEADER_CHARS = [" "];
for (let i5 = 32; i5 <= 255; i5++) {
if (i5 !== 127) {
exports2.HEADER_CHARS.push(i5);
}
}
exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS.filter((c6) => c6 !== 44);
exports2.QUOTED_STRING = [" ", " "];
for (let i5 = 33; i5 <= 255; i5++) {
if (i5 !== 34 && i5 !== 92) {
exports2.QUOTED_STRING.push(i5);
}
}
exports2.HTAB_SP_VCHAR_OBS_TEXT = [" ", " "];
for (let i5 = 33; i5 <= 126; i5++) {
exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i5);
}
for (let i5 = 128; i5 <= 255; i5++) {
exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i5);
}
exports2.MAJOR = exports2.NUM_MAP;
exports2.MINOR = exports2.MAJOR;
exports2.SPECIAL_HEADERS = {
"connection": exports2.HEADER_STATE.CONNECTION,
"content-length": exports2.HEADER_STATE.CONTENT_LENGTH,
"proxy-connection": exports2.HEADER_STATE.CONNECTION,
"transfer-encoding": exports2.HEADER_STATE.TRANSFER_ENCODING,
"upgrade": exports2.HEADER_STATE.UPGRADE
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Buffer: Buffer7 } = require("buffer");
var wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzQzBQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEDAAADAAAABAUBcAESEgUDAQACBggBfwFBgNgECwfFBygGbWVtb3J5AgALX2luaXRpYWxpemUACBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQACRhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUANgxsbGh0dHBfYWxsb2MACwZtYWxsb2MAOAtsbGh0dHBfZnJlZQAMBGZyZWUADA9sbGh0dHBfZ2V0X3R5cGUADRVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADhVsbGh0dHBfZ2V0X2h0dHBfbWlub3IADxFsbGh0dHBfZ2V0X21ldGhvZAAQFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAERJsbGh0dHBfZ2V0X3VwZ3JhZGUAEgxsbGh0dHBfcmVzZXQAEw5sbGh0dHBfZXhlY3V0ZQAUFGxsaHR0cF9zZXR0aW5nc19pbml0ABUNbGxodHRwX2ZpbmlzaAAWDGxsaHR0cF9wYXVzZQAXDWxsaHR0cF9yZXN1bWUAGBtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGRBsbGh0dHBfZ2V0X2Vycm5vABoXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AGxdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAcFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB0RbGxodHRwX2Vycm5vX25hbWUAHhJsbGh0dHBfbWV0aG9kX25hbWUAHxJsbGh0dHBfc3RhdHVzX25hbWUAIBpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAhIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAiHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACMkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACQabGxodHRwX3NldF9sZW5pZW50X3ZlcnNpb24AJSNsbGh0dHBfc2V0X2xlbmllbnRfZGF0YV9hZnRlcl9jbG9zZQAmJ2xsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9sZl9hZnRlcl9jcgAnLGxsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9jcmxmX2FmdGVyX2NodW5rACgobGxodHRwX3NldF9sZW5pZW50X29wdGlvbmFsX2NyX2JlZm9yZV9sZgApKmxsaHR0cF9zZXRfbGVuaWVudF9zcGFjZXNfYWZ0ZXJfY2h1bmtfc2l6ZQAqGGxsaHR0cF9tZXNzYWdlX25lZWRzX2VvZgA1CRcBAEEBCxEBAgMEBQoGBzEzMi0uLCsvMAq8ywIzFgBB/NMAKAIABEAAC0H80wBBATYCAAsUACAAEDcgACACNgI4IAAgAToAKAsUACAAIAAvATQgAC0AMCAAEDYQAAseAQF/QcAAEDkiARA3IAFBgAg2AjggASAAOgAoIAELjwwBB38CQCAARQ0AIABBCGsiASAAQQRrKAIAIgBBeHEiBGohBQJAIABBAXENACAAQQNxRQ0BIAEgASgCACIAayIBQZDUACgCAEkNASAAIARqIQQCQAJAQZTUACgCACABRwRAIABB/wFNBEAgAEEDdiEDIAEoAggiACABKAIMIgJGBEBBgNQAQYDUACgCAEF+IAN3cTYCAAwFCyACIAA2AgggACACNgIMDAQLIAEoAhghBiABIAEoAgwiAEcEQCAAIAEoAggiAjYCCCACIAA2AgwMAwsgAUEUaiIDKAIAIgJFBEAgASgCECICRQ0CIAFBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUoAgQiAEEDcUEDRw0CIAUgAEF+cTYCBEGI1AAgBDYCACAFIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAEoAhwiAkECdEGw1gBqIgMoAgAgAUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECABRhtqIAA2AgAgAEUNAQsgACAGNgIYIAEoAhAiAgRAIAAgAjYCECACIAA2AhgLIAFBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIAVPDQAgBSgCBCIAQQFxRQ0AAkACQAJAAkAgAEECcUUEQEGY1AAoAgAgBUYEQEGY1AAgATYCAEGM1ABBjNQAKAIAIARqIgA2AgAgASAAQQFyNgIEIAFBlNQAKAIARw0GQYjUAEEANgIAQZTUAEEANgIADAYLQZTUACgCACAFRgRAQZTUACABNgIAQYjUAEGI1AAoAgAgBGoiADYCACABIABBAXI2AgQgACABaiAANgIADAYLIABBeHEgBGohBCAAQf8BTQRAIABBA3YhAyAFKAIIIgAgBSgCDCICRgRAQYDUAEGA1AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyAFKAIYIQYgBSAFKAIMIgBHBEBBkNQAKAIAGiAAIAUoAggiAjYCCCACIAA2AgwMAwsgBUEUaiIDKAIAIgJFBEAgBSgCECICRQ0CIAVBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUgAEF+cTYCBCABIARqIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAUoAhwiAkECdEGw1gBqIgMoAgAgBUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECAFRhtqIAA2AgAgAEUNAQsgACAGNgIYIAUoAhAiAgRAIAAgAjYCECACIAA2AhgLIAVBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIARqIAQ2AgAgASAEQQFyNgIEIAFBlNQAKAIARw0AQYjUACAENgIADAELIARB/wFNBEAgBEF4cUGo1ABqIQACf0GA1AAoAgAiAkEBIARBA3Z0IgNxRQRAQYDUACACIANyNgIAIAAMAQsgACgCCAsiAiABNgIMIAAgATYCCCABIAA2AgwgASACNgIIDAELQR8hAiAEQf///wdNBEAgBEEmIARBCHZnIgBrdkEBcSAAQQF0a0E+aiECCyABIAI2AhwgAUIANwIQIAJBAnRBsNYAaiEAAkBBhNQAKAIAIgNBASACdCIHcUUEQCAAIAE2AgBBhNQAIAMgB3I2AgAgASAANgIYIAEgATYCCCABIAE2AgwMAQsgBEEZIAJBAXZrQQAgAkEfRxt0IQIgACgCACEAAkADQCAAIgMoAgRBeHEgBEYNASACQR12IQAgAkEBdCECIAMgAEEEcWpBEGoiBygCACIADQALIAcgATYCACABIAM2AhggASABNgIMIAEgATYCCAwBCyADKAIIIgAgATYCDCADIAE2AgggAUEANgIYIAEgAzYCDCABIAA2AggLQaDUAEGg1AAoAgBBAWsiAEF/IAAbNgIACwsHACAALQAoCwcAIAAtACoLBwAgAC0AKwsHACAALQApCwcAIAAvATQLBwAgAC0AMAtAAQR/IAAoAhghASAALwEuIQIgAC0AKCEDIAAoAjghBCAAEDcgACAENgI4IAAgAzoAKCAAIAI7AS4gACABNgIYC8X4AQIHfwN+IAEgAmohBAJAIAAiAygCDCIADQAgAygCBARAIAMgATYCBAsjAEEQayIJJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQFrDuwB7gEB6AECAwQFBgcICQoLDA0ODxAREucBE+YBFBXlARYX5AEYGRobHB0eHyDvAe0BIeMBIiMkJSYnKCkqK+IBLC0uLzAxMuEB4AEzNN8B3gE1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk/pAVBRUlPdAdwBVNsBVdoBVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHZAdgBxgHXAccB1gHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAQDqAQtBAAzUAQtBDgzTAQtBDQzSAQtBDwzRAQtBEAzQAQtBEQzPAQtBEgzOAQtBEwzNAQtBFAzMAQtBFQzLAQtBFgzKAQtBFwzJAQtBGAzIAQtBGQzHAQtBGgzGAQtBGwzFAQtBHAzEAQtBHQzDAQtBHgzCAQtBHwzBAQtBCAzAAQtBIAy/AQtBIgy+AQtBIQy9AQtBBwy8AQtBIwy7AQtBJAy6AQtBJQy5AQtBJgy4AQtBJwy3AQtBzgEMtgELQSgMtQELQSkMtAELQSoMswELQSsMsgELQc8BDLEBC0EtDLABC0EuDK8BC0EvDK4BC0EwDK0BC0ExDKwBC0EyDKsBC0EzDKoBC0HQAQypAQtBNAyoAQtBOAynAQtBDAymAQtBNQylAQtBNgykAQtBNwyjAQtBPQyiAQtBOQyhAQtB0QEMoAELQQsMnwELQT4MngELQToMnQELQQoMnAELQTsMmwELQTwMmgELQdIBDJkBC0HAAAyYAQtBPwyXAQtBwQAMlgELQQkMlQELQSwMlAELQcIADJMBC0HDAAySAQtBxAAMkQELQcUADJABC0HGAAyPAQtBxwAMjgELQcgADI0BC0HJAAyMAQtBygAMiwELQcsADIoBC0HMAAyJAQtBzQAMiAELQc4ADIcBC0HPAAyGAQtB0AAMhQELQdEADIQBC0HSAAyDAQtB1AAMggELQdMADIEBC0HVAAyAAQtB1gAMfwtB1wAMfgtB2AAMfQtB2QAMfAtB2gAMewtB2wAMegtB0wEMeQtB3AAMeAtB3QAMdwtBBgx2C0HeAAx1C0EFDHQLQd8ADHMLQQQMcgtB4AAMcQtB4QAMcAtB4gAMbwtB4wAMbgtBAwxtC0HkAAxsC0HlAAxrC0HmAAxqC0HoAAxpC0HnAAxoC0HpAAxnC0HqAAxmC0HrAAxlC0HsAAxkC0ECDGMLQe0ADGILQe4ADGELQe8ADGALQfAADF8LQfEADF4LQfIADF0LQfMADFwLQfQADFsLQfUADFoLQfYADFkLQfcADFgLQfgADFcLQfkADFYLQfoADFULQfsADFQLQfwADFMLQf0ADFILQf4ADFELQf8ADFALQYABDE8LQYEBDE4LQYIBDE0LQYMBDEwLQYQBDEsLQYUBDEoLQYYBDEkLQYcBDEgLQYgBDEcLQYkBDEYLQYoBDEULQYsBDEQLQYwBDEMLQY0BDEILQY4BDEELQY8BDEALQZABDD8LQZEBDD4LQZIBDD0LQZMBDDwLQZQBDDsLQZUBDDoLQZYBDDkLQZcBDDgLQZgBDDcLQZkBDDYLQZoBDDULQZsBDDQLQZwBDDMLQZ0BDDILQZ4BDDELQZ8BDDALQaABDC8LQaEBDC4LQaIBDC0LQaMBDCwLQaQBDCsLQaUBDCoLQaYBDCkLQacBDCgLQagBDCcLQakBDCYLQaoBDCULQasBDCQLQawBDCMLQa0BDCILQa4BDCELQa8BDCALQbABDB8LQbEBDB4LQbIBDB0LQbMBDBwLQbQBDBsLQbUBDBoLQbYBDBkLQbcBDBgLQbgBDBcLQQEMFgtBuQEMFQtBugEMFAtBuwEMEwtBvAEMEgtBvQEMEQtBvgEMEAtBvwEMDwtBwAEMDgtBwQEMDQtBwgEMDAtBwwEMCwtBxAEMCgtBxQEMCQtBxgEMCAtB1AEMBwtBxwEMBgtByAEMBQtByQEMBAtBygEMAwtBywEMAgtBzQEMAQtBzAELIQIDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCACDtQBAAECAwQFBgcICQoLDA0ODxARFBUWFxgZGhscHR4fICEjJCUnKCmIA4cDhQOEA/wC9QLuAusC6ALmAuMC4ALfAt0C2wLWAtUC1ALTAtICygLJAsgCxwLGAsUCxALDAr0CvAK6ArkCuAK3ArYCtQK0ArICsQKsAqoCqAKnAqYCpQKkAqMCogKhAqACnwKbApoCmQKYApcCkAKIAoQCgwKCAvkB9gH1AfQB8wHyAfEB8AHvAe0B6wHoAeMB4QHgAd8B3gHdAdwB2wHaAdkB2AHXAdYB1QHUAdIB0QHQAc8BzgHNAcwBywHKAckByAHHAcYBxQHEAcMBwgHBAcABvwG+Ab0BvAG7AboBuQG4AbcBtgG1AbQBswGyAbEBsAGvAa4BrQGsAasBqgGpAagBpwGmAaUBpAGjAaIBoQGgAZ8BngGdAZwBmwGaAZcBlgGRAZABjwGOAY0BjAGLAYoBiQGIAYUBhAGDAX59fHt6d3Z1LFFSU1RVVgsgASAERw1zQewBIQIMqQMLIAEgBEcNkAFB0QEhAgyoAwsgASAERw3pAUGEASECDKcDCyABIARHDfQBQfoAIQIMpgMLIAEgBEcNggJB9QAhAgylAwsgASAERw2JAkHzACECDKQDCyABIARHDYwCQfEAIQIMowMLIAEgBEcNHkEeIQIMogMLIAEgBEcNGUEYIQIMoQMLIAEgBEcNuAJBzQAhAgygAwsgASAERw3DAkHGACECDJ8DCyABIARHDcQCQcMAIQIMngMLIAEgBEcNygJBOCECDJ0DCyADLQAwQQFGDZUDDPICC0EAIQACQAJAAkAgAy0AKkUNACADLQArRQ0AIAMvATIiAkECcUUNAQwCCyADLwEyIgJBAXFFDQELQQEhACADLQAoQQFGDQAgAy8BNCIGQeQAa0HkAEkNACAGQcwBRg0AIAZBsAJGDQAgAkHAAHENAEEAIQAgAkGIBHFBgARGDQAgAkEocUEARyEACyADQQA7ATIgA0EAOgAxAkAgAEUEQCADQQA6ADEgAy0ALkEEcQ0BDJwDCyADQgA3AyALIANBADoAMSADQQE6ADYMSQtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAEUNSSAAQRVHDWMgA0EENgIcIAMgATYCFCADQb0aNgIQIANBFTYCDEEAIQIMmgMLIAEgBEYEQEEGIQIMmgMLIAEtAABBCkYNGQwBCyABIARGBEBBByECDJkDCwJAIAEtAABBCmsOBAIBAQABCyABQQFqIQFBECECDP4CCyADLQAuQYABcQ0YQQAhAiADQQA2AhwgAyABNgIUIANBqR82AhAgA0ECNgIMDJcDCyABQQFqIQEgA0Evai0AAEEBcQ0XQQAhAiADQQA2AhwgAyABNgIUIANBhB82AhAgA0EZNgIMDJYDCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMWg0ZQQghAgyVAwsgASAERwRAIANBCTYCCCADIAE2AgRBEiECDPsCC0EJIQIMlAMLIAMpAyBQDZwCDEQLIAEgBEYEQEELIQIMkwMLIAEtAABBCkcNFyABQQFqIQEMGAsgA0Evai0AAEEBcUUNGgwnC0EAIQACQCADKAI4IgJFDQAgAigCSCICRQ0AIAMgAhEAACEACyAADRoMQwtBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0bDCULQQAhAAJAIAMoAjgiAkUNACACKAJIIgJFDQAgAyACEQAAIQALIAANHAwzCyADQS9qLQAAQQFxRQ0dDCMLQQAhAAJAIAMoAjgiAkUNACACKAJMIgJFDQAgAyACEQAAIQALIAANHQxDC0EAIQACQCADKAI4IgJFDQAgAigCTCICRQ0AIAMgAhEAACEACyAADR4MIQsgASAERgRAQRMhAgyLAwsCQCABLQAAIgBBCmsOBCAkJAAjCyABQQFqIQEMIAtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0jDEMLIAEgBEYEQEEWIQIMiQMLIAEtAABB8D9qLQAAQQFHDSQM7QILAkADQCABLQAAQeA5ai0AACIAQQFHBEACQCAAQQJrDgIDACgLIAFBAWohAUEfIQIM8AILIAQgAUEBaiIBRw0AC0EYIQIMiAMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABQQFqIgEQMyIADSIMQgtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0kDCsLIAEgBEYEQEEcIQIMhgMLIANBCjYCCCADIAE2AgRBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0mQSIhAgzrAgsgASAERwRAA0AgAS0AAEHgO2otAAAiAEEDRwRAIABBAWsOBRkbJ+wCJicLIAQgAUEBaiIBRw0AC0EbIQIMhQMLQRshAgyEAwsDQCABLQAAQeA9ai0AACIAQQNHBEAgAEEBaw4FEBIoFCcoCyAEIAFBAWoiAUcNAAtBHiECDIMDCyABIARHBEAgA0ELNgIIIAMgATYCBEEHIQIM6QILQR8hAgyCAwsgASAERgRAQSAhAgyCAwsCQCABLQAAQQ1rDhQvQEBAQEBAQEBAQEBAQEBAQEBAAEALQQAhAiADQQA2AhwgA0G3CzYCECADQQI2AgwgAyABQQFqNgIUDIEDCyADQS9qIQIDQCABIARGBEBBISECDIIDCwJAAkACQCABLQAAIgBBCWsOGAIAKioBKioqKioqKioqKioqKioqKioqAigLIAFBAWohASADQS9qLQAAQQFxRQ0LDBkLIAFBAWohAQwYCyABQQFqIQEgAi0AAEECcQ0AC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAyAAwsgAUEBaiEBC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADQEM0QILIANCADcDIAw8CyAAQRVGBEAgA0EkNgIcIAMgATYCFCADQYYaNgIQIANBFTYCDEEAIQIM/QILQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDPwCCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDSsgA0EHNgIcIAMgATYCFCADIAA2AgwM+wILIAMtAC5BwABxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAARQ0rIABBFUYEQCADQQo2AhwgAyABNgIUIANB8Rg2AhAgA0EVNgIMQQAhAgz6AgtBACECIANBADYCHCADIAE2AhQgA0GLDDYCECADQRM2AgwM+QILQQAhAiADQQA2AhwgAyABNgIUIANBsRQ2AhAgA0ECNgIMDPgCC0EAIQIgA0EANgIcIAMgATYCFCADQYwUNgIQIANBGTYCDAz3AgtBACECIANBADYCHCADIAE2AhQgA0HRHDYCECADQRk2AgwM9gILIABBFUYNPUEAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAz1AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQ0oIANBDTYCHCADIAE2AhQgAyAANgIMDPQCCyAAQRVGDTpBACECIANBADYCHCADIAE2AhQgA0GiDzYCECADQSI2AgwM8wILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDIiAEUEQCABQQFqIQEMKAsgA0EONgIcIAMgADYCDCADIAFBAWo2AhQM8gILIABBFUYNN0EAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAzxAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQRAIAFBAWohAQwnCyADQQ82AhwgAyAANgIMIAMgAUEBajYCFAzwAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM7wILIABBFUYNM0EAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzuAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMyIARQ0lIANBETYCHCADIAE2AhQgAyAANgIMDO0CCyAAQRVGDTBBACECIANBADYCHCADIAE2AhQgA0HODDYCECADQSM2AgwM7AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEMJQsgA0ESNgIcIAMgADYCDCADIAFBAWo2AhQM6wILIANBL2otAABBAXFFDQELQRUhAgzPAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM6AILIABBO0cNACABQQFqIQEMDAtBACECIANBADYCHCADIAE2AhQgA0GYFzYCECADQQI2AgwM5gILIABBFUYNKEEAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzlAgsgA0EUNgIcIAMgATYCFCADIAA2AgwM5AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEM3AILIANBFTYCHCADIAA2AgwgAyABQQFqNgIUDOMCCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNoCCyADQRc2AhwgAyAANgIMIAMgAUEBajYCFAziAgsgAEEVRg0jQQAhAiADQQA2AhwgAyABNgIUIANBzgw2AhAgA0EjNgIMDOECCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDB0LIANBGTYCHCADIAA2AgwgAyABQQFqNgIUDOACCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNYCCyADQRo2AhwgAyAANgIMIAMgAUEBajYCFAzfAgsgAEEVRg0fQQAhAiADQQA2AhwgAyABNgIUIANBog82AhAgA0EiNgIMDN4CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUDN0CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDNICCyADQR02AhwgAyAANgIMIAMgAUEBajYCFAzcAgsgAEE7Rw0BIAFBAWohAQtBJCECDMACC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAzZAgsgASAERwRAA0AgAS0AAEEgRw3xASAEIAFBAWoiAUcNAAtBLCECDNkCC0EsIQIM2AILIAEgBEYEQEE0IQIM2AILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0E0IQIM2QILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ2MAiADQTI2AhwgAyABNgIUIAMgADYCDEEAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQRAIAFBAWohAQyMAgsgA0EyNgIcIAMgADYCDCADIAFBAWo2AhRBACECDNcCCyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE5IQIMwAILIAMpAyAiC0KZs+bMmbPmzBlWDQEgAyALQgp+Igo3AyAgCiAArUL/AYMiC0J/hVYNASADIAogC3w3AyAgBCABQQFqIgFHDQALQcAAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAFBAWoiARAwIgANFwzJAgtBwAAhAgzWAgsgASAERgRAQckAIQIM1gILAkADQAJAIAEtAABBCWsOGAACjwKPApMCjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CAI8CCyAEIAFBAWoiAUcNAAtByQAhAgzWAgsgAUEBaiEBIANBL2otAABBAXENjwIgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIM1QILIAEgBEcEQANAIAEtAAAiAEEgRwRAAkACQAJAIABByABrDgsAAc0BzQHNAc0BzQHNAc0BzQECzQELIAFBAWohAUHZACECDL8CCyABQQFqIQFB2gAhAgy+AgsgAUEBaiEBQdsAIQIMvQILIAQgAUEBaiIBRw0AC0HuACECDNUCC0HuACECDNQCCyADQQI6ACgMMAtBACECIANBADYCHCADQbcLNgIQIANBAjYCDCADIAFBAWo2AhQM0gILQQAhAgy3AgtBDSECDLYCC0ERIQIMtQILQRMhAgy0AgtBFCECDLMCC0EWIQIMsgILQRchAgyxAgtBGCECDLACC0EZIQIMrwILQRohAgyuAgtBGyECDK0CC0EcIQIMrAILQR0hAgyrAgtBHiECDKoCC0EgIQIMqQILQSEhAgyoAgtBIyECDKcCC0EnIQIMpgILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgy/AgsgA0EbNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMvgILIANBIDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDL0CCyADQRM2AhwgAyABNgIUIANBnhk2AhAgA0EVNgIMQQAhAgy8AgsgA0ELNgIcIAMgATYCFCADQZ4ZNgIQIANBFTYCDEEAIQIMuwILIANBEDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDLoCCyADQSA2AhwgAyABNgIUIANBjxs2AhAgA0EVNgIMQQAhAgy5AgsgA0ELNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMuAILIANBDDYCHCADIAE2AhQgA0GPGzYCECADQRU2AgxBACECDLcCC0EAIQIgA0EANgIcIAMgATYCFCADQa8ONgIQIANBEjYCDAy2AgsCQANAAkAgAS0AAEEKaw4EAAICAAILIAQgAUEBaiIBRw0AC0HsASECDLYCCwJAAkAgAy0ANkEBRw0AQQAhAAJAIAMoAjgiAkUNACACKAJYIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB6wE2AhwgAyABNgIUIANB4hg2AhAgA0EVNgIMQQAhAgy3AgtBzAEhAgycAgsgA0EANgIcIAMgATYCFCADQfELNgIQIANBHzYCDEEAIQIMtQILAkACQCADLQAoQQFrDgIEAQALQcsBIQIMmwILQcQBIQIMmgILIANBAjoAMUEAIQACQCADKAI4IgJFDQAgAigCACICRQ0AIAMgAhEAACEACyAARQRAQc0BIQIMmgILIABBFUcEQCADQQA2AhwgAyABNgIUIANBrAw2AhAgA0EQNgIMQQAhAgy0AgsgA0HqATYCHCADIAE2AhQgA0GHGTYCECADQRU2AgxBACECDLMCCyABIARGBEBB6QEhAgyzAgsgAS0AAEHIAEYNASADQQE6ACgLQbYBIQIMlwILQcoBIQIMlgILIAEgBEcEQCADQQw2AgggAyABNgIEQckBIQIMlgILQegBIQIMrwILIAEgBEYEQEHnASECDK8CCyABLQAAQcgARw0EIAFBAWohAUHIASECDJQCCyABIARGBEBB5gEhAgyuAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQcYBIQIMlAILIAFBAWohAUHHASECDJMCC0HlASECIAEgBEYNrAIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB99MAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMrQILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgBFBEBB1AEhAgyTAgsgA0HkATYCHCADIAE2AhQgAyAANgIMQQAhAgysAgtB4wEhAiABIARGDasCIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQfXTAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADKwCCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB0B42AhAgA0EINgIMDKkCC0HFASECDI4CCyADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDKcCC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ1lIABBFUcEQCADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgynAgsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDKYCC0HhASECIAQgASIARg2lAiAEIAFrIAMoAgAiAWohBSAAIAFrQQRqIQYCQANAIAAtAAAgAUHw0wBqLQAARw0BIAFBBEYNAyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBTYCAAymAgsgA0EANgIcIAMgADYCFCADQYQ3NgIQIANBCDYCDCADQQA2AgBBACECDKUCCyABIARHBEAgA0ENNgIIIAMgATYCBEHCASECDIsCC0HgASECDKQCCyADQQA2AgAgBkEBaiEBC0HDASECDIgCCyABIARGBEBB3wEhAgyiAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBwQEhAgyIAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYgCIANB3gE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAEgBEYEQEHdASECDKECCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYkCIANB3AE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILQcABIQIMhgILIAEgBEYEQEHbASECDKACC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDQIgA0HYATYCHCADIAE2AhQgAyAANgIMQQAhAgyiAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYsCIANB2QE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ2JAiADQdoBNgIcIAMgATYCFCADIAA2AgwMoAILQb8BIQIMhQILQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBnA02AhAgA0EhNgIMQQAhAgygAgtBvgEhAgyFAgsgA0HXATYCHCADIAE2AhQgA0HWGTYCECADQRU2AgxBACECDJ4CCyABIARGBEBB1wEhAgyeAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANB6xA2AhAgA0EJNgIMQQAhAgyeAgtBvQEhAgyDAgsgASAERgRAQdYBIQIMnQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDAyeAgsgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDEEAIQIMnQILQbwBIQIMggILIAEgBEYEQEHVASECDJwCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgwMnQILIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgxBACECDJwCC0G7ASECDIECCyABIARGBEBB1AEhAgybAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMDJwCCyADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMQQAhAgybAgtBugEhAgyAAgsgASAERgRAQdMBIQIMmgILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUG5ASECDIECCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GFCzYCECADQQ02AgxBACECDJoCCyADQQA2AhwgAyABNgIUIANBhQs2AhAgA0ENNgIMQQAhAgyZAgsgASAERwRAIANBDjYCCCADIAE2AgRBASECDP8BC0HSASECDJgCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB0QEhAgyZAgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFBEAgAUEBaiEBDAQLIANB0AE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMmAILIAMoAgQhACADQQA2AgQgAyAAIAEQLCIADQEgAUEBagshAUG3ASECDPwBCyADQc8BNgIcIAMgADYCDCADIAFBAWo2AhRBACECDJUCC0G4ASECDPoBCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQc8bNgIQIANBGTYCDEEAIQIMkwILIAEgBEYEQEHPASECDJMCCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsgAEUNlgEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBvRk2AhAgA0EVNgIMQQAhAgySAgsgA0EANgIcIAMgATYCFCADQfgMNgIQIANBGzYCDEEAIQIMkQILIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDJACCyABIARHBEAgA0EMNgIIIAMgATYCBEG1ASECDPYBC0HOASECDI8CCyABIARGBEBBzQEhAgyPAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQQFqIQFB8QAhAgyEAgsgAUEBaiEBQfIAIQIMgwILIAFBAWohAUH3ACECDIICCyABQQFqIQFB+wAhAgyBAgsgAUEBaiEBQfwAIQIMgAILIAFBAWohAUH/ACECDP8BCyABQQFqIQFBgAEhAgz+AQsgAUEBaiEBQYMBIQIM/QELIAFBAWohAUGMASECDPwBCyABQQFqIQFBjQEhAgz7AQsgAUEBaiEBQY4BIQIM+gELIAFBAWohAUGbASECDPkBCyABQQFqIQFBnAEhAgz4AQsgAUEBaiEBQaIBIQIM9wELIAFBAWohAUGqASECDPYBCyABQQFqIQFBrQEhAgz1AQsgAUEBaiEBQbQBIQIM9AELIAEgBEYEQEHMASECDI4CCyABLQAAQc4ARw1IIAFBAWohAUGzASECDPMBCyABIARGBEBBywEhAgyNAgsCQAJAAkAgAS0AAEHCAGsOEgBKSkpKSkpKSkoBSkpKSkpKAkoLIAFBAWohAUGuASECDPQBCyABQQFqIQFBsQEhAgzzAQsgAUEBaiEBQbIBIQIM8gELQcoBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQdqIQYCQANAIAEtAAAgAEHo0wBqLQAARw1FIABBB0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEbDEULIAEgBEYEQEHJASECDIsCCwJAAkAgAS0AAEHJAGsOBwBHR0dHRwFHCyABQQFqIQFBrwEhAgzxAQsgAUEBaiEBQbABIQIM8AELQcgBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm0wBqLQAARw1DIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEPDEMLQccBIQIgASAERg2IAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk0wBqLQAARw1CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyJAgsgA0EANgIAIAZBAWohAUEgDEILQcYBIQIgASAERg2HAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw1BIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyIAgsgA0EANgIAIAZBAWohAUESDEELIAEgBEYEQEHFASECDIcCCwJAAkAgAS0AAEHFAGsODgBDQ0NDQ0NDQ0NDQ0MBQwsgAUEBaiEBQasBIQIM7QELIAFBAWohAUGsASECDOwBC0HEASECIAEgBEYNhQIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB3tMAai0AAEcNPyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhgILIANBADYCACAGQQFqIQFBBww/C0HDASECIAEgBEYNhAIgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABB2NMAai0AAEcNPiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhQILIANBADYCACAGQQFqIQFBKAw+CyABIARGBEBBwgEhAgyEAgsCQAJAAkAgAS0AAEHFAGsOEQBBQUFBQUFBQUEBQUFBQUECQQsgAUEBaiEBQacBIQIM6wELIAFBAWohAUGoASECDOoBCyABQQFqIQFBqQEhAgzpAQtBwQEhAiABIARGDYICIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQdHTAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIMCCyADQQA2AgAgBkEBaiEBQRoMPAtBwAEhAiABIARGDYECIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQc3TAGotAABHDTsgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIICCyADQQA2AgAgBkEBaiEBQSEMOwsgASAERgRAQb8BIQIMgQILAkACQCABLQAAQcEAaw4UAD09PT09PT09PT09PT09PT09PQE9CyABQQFqIQFBowEhAgznAQsgAUEBaiEBQaYBIQIM5gELIAEgBEYEQEG+ASECDIACCwJAAkAgAS0AAEHVAGsOCwA8PDw8PDw8PDwBPAsgAUEBaiEBQaQBIQIM5gELIAFBAWohAUGlASECDOUBC0G9ASECIAEgBEYN/gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNOCAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/wELIANBADYCACAGQQFqIQFBKgw4CyABIARGBEBBvAEhAgz+AQsgAS0AAEHQAEcNOCABQQFqIQFBJQw3C0G7ASECIAEgBEYN/AEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBwdMAai0AAEcNNiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/QELIANBADYCACAGQQFqIQFBDgw2CyABIARGBEBBugEhAgz8AQsgAS0AAEHFAEcNNiABQQFqIQFBoQEhAgzhAQsgASAERgRAQbkBIQIM+wELAkACQAJAAkAgAS0AAEHCAGsODwABAjk5OTk5OTk5OTk5AzkLIAFBAWohAUGdASECDOMBCyABQQFqIQFBngEhAgziAQsgAUEBaiEBQZ8BIQIM4QELIAFBAWohAUGgASECDOABC0G4ASECIAEgBEYN+QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtMAai0AAEcNMyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+gELIANBADYCACAGQQFqIQFBFAwzC0G3ASECIAEgBEYN+AEgAygCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBudMAai0AAEcNMiAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+QELIANBADYCACAGQQFqIQFBKwwyC0G2ASECIAEgBEYN9wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBttMAai0AAEcNMSAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+AELIANBADYCACAGQQFqIQFBLAwxC0G1ASECIAEgBEYN9gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB4dMAai0AAEcNMCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9wELIANBADYCACAGQQFqIQFBEQwwC0G0ASECIAEgBEYN9QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBstMAai0AAEcNLyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9gELIANBADYCACAGQQFqIQFBLgwvCyABIARGBEBBswEhAgz1AQsCQAJAAkACQAJAIAEtAABBwQBrDhUANDQ0NDQ0NDQ0NAE0NAI0NAM0NAQ0CyABQQFqIQFBkQEhAgzeAQsgAUEBaiEBQZIBIQIM3QELIAFBAWohAUGTASECDNwBCyABQQFqIQFBmAEhAgzbAQsgAUEBaiEBQZoBIQIM2gELIAEgBEYEQEGyASECDPQBCwJAAkAgAS0AAEHSAGsOAwAwATALIAFBAWohAUGZASECDNoBCyABQQFqIQFBBAwtC0GxASECIAEgBEYN8gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBsNMAai0AAEcNLCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM8wELIANBADYCACAGQQFqIQFBHQwsCyABIARGBEBBsAEhAgzyAQsCQAJAIAEtAABByQBrDgcBLi4uLi4ALgsgAUEBaiEBQZcBIQIM2AELIAFBAWohAUEiDCsLIAEgBEYEQEGvASECDPEBCyABLQAAQdAARw0rIAFBAWohAUGWASECDNYBCyABIARGBEBBrgEhAgzwAQsCQAJAIAEtAABBxgBrDgsALCwsLCwsLCwsASwLIAFBAWohAUGUASECDNYBCyABQQFqIQFBlQEhAgzVAQtBrQEhAiABIARGDe4BIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQazTAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO8BCyADQQA2AgAgBkEBaiEBQQ0MKAtBrAEhAiABIARGDe0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQeHTAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO4BCyADQQA2AgAgBkEBaiEBQQwMJwtBqwEhAiABIARGDewBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQarTAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO0BCyADQQA2AgAgBkEBaiEBQQMMJgtBqgEhAiABIARGDesBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQajTAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOwBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQakBIQIM6wELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBjwEhAgzRAQsgAUEBaiEBQZABIQIM0AELQagBIQIgASAERg3pASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm0wBqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzqAQsgA0EANgIAIAZBAWohAUEnDCMLQacBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk0wBqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEcDCILQaYBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGe0wBqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEGDCELQaUBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGZ0wBqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGkASECDOYBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQYQBIQIMzgELIAFBAWohAUGFASECDM0BCyABQQFqIQFBigEhAgzMAQsgAUEBaiEBQYsBIQIMywELQaMBIQIgASAERg3kASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGX0wBqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzlAQsgA0EANgIAIAZBAWohAUELDB4LIAEgBEYEQEGiASECDOQBCwJAAkAgAS0AAEHBAGsOAwAgASALIAFBAWohAUGGASECDMoBCyABQQFqIQFBiQEhAgzJAQsgASAERgRAQaEBIQIM4wELAkACQCABLQAAQcEAaw4PAB8fHx8fHx8fHx8fHx8BHwsgAUEBaiEBQYcBIQIMyQELIAFBAWohAUGIASECDMgBCyABIARGBEBBoAEhAgziAQsgAS0AAEHMAEcNHCABQQFqIQFBCgwbC0GfASECIAEgBEYN4AEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBkdMAai0AAEcNGiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4QELIANBADYCACAGQQFqIQFBHgwaC0GeASECIAEgBEYN3wEgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBitMAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4AELIANBADYCACAGQQFqIQFBFQwZC0GdASECIAEgBEYN3gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBh9MAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3wELIANBADYCACAGQQFqIQFBFwwYC0GcASECIAEgBEYN3QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBgdMAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3gELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBmwEhAgzdAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYEBIQIMwwELIAFBAWohAUGCASECDMIBC0GaASECIAEgBEYN2wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5tMAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3AELIANBADYCACAGQQFqIQFBCQwVC0GZASECIAEgBEYN2gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5NMAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2wELIANBADYCACAGQQFqIQFBHwwUC0GYASECIAEgBEYN2QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB/tIAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2gELIANBADYCACAGQQFqIQFBAgwTC0GXASECIAEgBEYN2AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQfzSAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyABIARGBEBBlgEhAgzYAQtBASABLQAAQd8ARw0RGiABQQFqIQFB/QAhAgy9AQsgA0EANgIAIAZBAWohAUH+ACECDLwBC0GVASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBKQwPC0GUASECIAEgBEYN1AEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB+NIAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1QELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBkwEhAgzUAQsgAS0AAEHFAEcNDiABQQFqIQFB+gAhAgy5AQsgASAERgRAQZIBIQIM0wELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFB+AAhAgy5AQsgAUEBaiEBQfkAIQIMuAELQZEBIQIgASAERg3RASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHz0gBqLQAARw0LIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzSAQsgA0EANgIAIAZBAWohAUEjDAsLQZABIQIgASAERg3QASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHw0gBqLQAARw0KIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzRAQsgA0EANgIAIAZBAWohAUEADAoLIAEgBEYEQEGPASECDNABCwJAAkAgAS0AAEHIAGsOCAAMDAwMDAwBDAsgAUEBaiEBQfMAIQIMtgELIAFBAWohAUH2ACECDLUBCyABIARGBEBBjgEhAgzPAQsCQAJAIAEtAABBzgBrDgMACwELCyABQQFqIQFB9AAhAgy1AQsgAUEBaiEBQfUAIQIMtAELIAEgBEYEQEGNASECDM4BCyABLQAAQdkARw0IIAFBAWohAUEIDAcLQYwBIQIgASAERg3MASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHs0gBqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzNAQsgA0EANgIAIAZBAWohAUEFDAYLQYsBIQIgASAERg3LASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHm0gBqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzMAQsgA0EANgIAIAZBAWohAUEWDAULQYoBIQIgASAERg3KASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzLAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGJASECDMoBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUHvACECDLABCyABQQFqIQFB8AAhAgyvAQtBiAEhAiABIARGDcgBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQeDSAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMkBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGHASECDMcBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC0iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB6R42AhAgA0EGNgIMDMQBC0HuACECDKkBCyADQYYBNgIcIAMgATYCFCADIAA2AgxBACECDMIBC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgzBAQtB7QAhAgymAQsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDL8BCyABIARGBEBBhQEhAgy/AQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GGHjYCECADQQY2AgxBACECDL8BC0ECIQIMpAELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GEASECDL0BCyABIARGBEBBgwEhAgy9AQsCQCABLQAAQQlrDgRAAABAAAtB6wAhAgyiAQsgAy0AKUEFRgRAQewAIQIMogELQeoAIQIMoQELIAEgBEYEQEGCASECDLsBCyADQQ82AgggAyABNgIEDAoLIAEgBEYEQEGBASECDLoBCwJAIAEtAABBCWsOBD0AAD0AC0HpACECDJ8BCyABIARHBEAgA0EPNgIIIAMgATYCBEHnACECDJ8BC0GAASECDLgBCwJAIAEgBEcEQANAIAEtAABB4M4Aai0AACIAQQNHBEACQCAAQQFrDgI/AAQLQeYAIQIMoQELIAQgAUEBaiIBRw0AC0H+ACECDLkBC0H+ACECDLgBCyADQQA2AhwgAyABNgIUIANBxh82AhAgA0EHNgIMQQAhAgy3AQsgASAERgRAQf8AIQIMtwELAkACQAJAIAEtAABB4NAAai0AAEEBaw4DPAIAAQtB6AAhAgyeAQsgA0EANgIcIAMgATYCFCADQYYSNgIQIANBBzYCDEEAIQIMtwELQeAAIQIMnAELIAEgBEcEQCABQQFqIQFB5QAhAgycAQtB/QAhAgy1AQsgBCABIgBGBEBB/AAhAgy1AQsgAC0AACIBQS9GBEAgAEEBaiEBQeQAIQIMmwELIAFBCWsiAkEXSw0BIAAhAUEBIAJ0QZuAgARxDTcMAQsgBCABIgBGBEBB+wAhAgy0AQsgAC0AAEEvRw0AIABBAWohAQwDC0EAIQIgA0EANgIcIAMgADYCFCADQcYfNgIQIANBBzYCDAyyAQsCQAJAAkACQAJAA0AgAS0AAEHgzABqLQAAIgBBBUcEQAJAAkAgAEEBaw4IPQUGBwgABAEIC0HhACECDJ8BCyABQQFqIQFB4wAhAgyeAQsgBCABQQFqIgFHDQALQfoAIQIMtgELIAFBAWoMFAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgy0AQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyzAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyyAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMsQELIAEgBEYEQEH5ACECDLEBCwJAIAEtAABB4MwAai0AAEEBaw4INAQFBgAIAgMHCyABQQFqIQELQQMhAgyVAQsgAUEBagwNC0EAIQIgA0EANgIcIANBoxI2AhAgA0EHNgIMIAMgAUEBajYCFAytAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgysAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMqQELQeIAIQIMjgELIAEgBEYEQEH4ACECDKgBCyABQQFqDAILIAEgBEYEQEH3ACECDKcBCyABQQFqDAELIAEgBEYNASABQQFqCyEBQQQhAgyKAQtB9gAhAgyjAQsDQCABLQAAQeDKAGotAAAiAEECRwRAIABBAUcEQEHfACECDIsBCwwnCyAEIAFBAWoiAUcNAAtB9QAhAgyiAQsgASAERgRAQfQAIQIMogELAkAgAS0AAEEJaw43JQMGJQQGBgYGBgYGBgYGBgYGBgYGBgYFBgYCBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAYLIAFBAWoLIQFBBSECDIYBCyABQQFqDAYLIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMngELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMnQELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB8AA2AhwgAyABNgIUIAMgADYCDEEAIQIMnAELIANBADYCHCADIAE2AhQgA0G8EzYCECADQQc2AgxBACECDJsBCwJAAkACQAJAA0AgAS0AAEHgyABqLQAAIgBBBUcEQAJAIABBAWsOBiQDBAUGAAYLQd4AIQIMhgELIAQgAUEBaiIBRw0AC0HzACECDJ4BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDJ0BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDJwBCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQfAANgIcIAMgATYCFCADIAA2AgxBACECDJsBCyADQQA2AhwgAyABNgIUIANB3Ag2AhAgA0EHNgIMQQAhAgyaAQsgASAERg0BIAFBAWoLIQFBBiECDH4LQfIAIQIMlwELAkACQAJAAkADQCABLQAAQeDGAGotAAAiAEEFRwRAIABBAWsOBB8CAwQFCyAEIAFBAWoiAUcNAAtB8QAhAgyaAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyZAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyYAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyXAQsgA0EANgIcIAMgATYCFCADQbQKNgIQIANBBzYCDEEAIQIMlgELQc4AIQIMewtB0AAhAgx6C0HdACECDHkLIAEgBEYEQEHwACECDJMBCwJAIAEtAABBCWsOBBYAABYACyABQQFqIQFB3AAhAgx4CyABIARGBEBB7wAhAgySAQsCQCABLQAAQQlrDgQVAAAVAAtBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUEQEHTASECDHgLIABBFUcEQCADQQA2AhwgAyABNgIUIANBwQ02AhAgA0EaNgIMQQAhAgySAQsgA0HuADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDJEBC0HtACECIAEgBEYNkAEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB18YAai0AAEcNBCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkQELIANBADYCACAGQQFqIQEgAy0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACECIANBADYCHCADIAE2AhQgA0HlCTYCECADQQg2AgwMkAELQewAIQIgASAERg2PASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHUxgBqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyQAQsgA0EANgIAIAZBAWohASADLQApQSFGDQMgA0EANgIcIAMgATYCFCADQYkKNgIQIANBCDYCDEEAIQIMjwELQesAIQIgASAERg2OASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHQxgBqLQAARw0CIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyPAQsgA0EANgIAIAZBAWohASADLQApIgBBI0kNAiAAQS5GDQIgA0EANgIcIAMgATYCFCADQcEJNgIQIANBCDYCDEEAIQIMjgELIANBADYCAAtBACECIANBADYCHCADIAE2AhQgA0GENzYCECADQQg2AgwMjAELQdgAIQIMcQsgASAERwRAIANBDTYCCCADIAE2AgRB1wAhAgxxC0HqACECDIoBCyABIARGBEBB6QAhAgyKAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1gAhAgxwCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdCADQegANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyABIARGBEBB5wAhAgyJAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ11IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMiQELQdUAIQIMbgsgASAERgRAQeUAIQIMiAELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDIoBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdyADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdSADQeQANgIcIAMgATYCFCADIAA2AgwMiAELQdMAIQIMbQsgAy0AKUEiRg2AAUHSACECDGwLQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALIABFBEBB1AAhAgxsCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQZwNNgIQIANBITYCDEEAIQIMhgELIANB4QA2AhwgAyABNgIUIANB1hk2AhAgA0EVNgIMQQAhAgyFAQsgASAERgRAQeAAIQIMhQELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HRACECDGwLIANBADYCHCADIAE2AhQgA0GIETYCECADQQk2AgxBACECDIUBCyADQQA2AhwgAyABNgIUIANBiBE2AhAgA0EJNgIMQQAhAgyEAQsgASAERgRAQd8AIQIMhAELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBiBE2AhAgA0ECNgIMQQAhAgyDAQsgASAERgRAQd0AIQIMgwELIAEtAAAiAkENRgRAIAFBAWohAUHPACECDGkLIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyCAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0G1LDYCECADQQc2AgwMgAELIAEgBEYEQEHbACECDIABCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc0AIQIMZAsgASAERgRAQdoAIQIMfgsgAS0AAEEJaw4EAAEBAAELQQAhAiADQQA2AhwgA0HsETYCECADQQc2AgwgAyABQQFqNgIUDHwLIANBgBI7ASpBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HZADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDHsLQcwAIQIMYAsgA0EANgIcIAMgATYCFCADQcENNgIQIANBGjYCDEEAIQIMeQsgASAERgRAQdkAIQIMeQsgAS0AAEEgRw06IAFBAWohASADLQAuQQFxDTogA0EANgIcIAMgATYCFCADQa0bNgIQIANBHjYCDEEAIQIMeAsgASAERgRAQdgAIQIMeAsCQAJAAkACQAJAIAEtAAAiAEEKaw4EAgMDAAELIAFBAWohAUErIQIMYQsgAEE6Rw0BIANBADYCHCADIAE2AhQgA0G5ETYCECADQQo2AgxBACECDHoLIAFBAWohASADQS9qLQAAQQFxRQ1tIAMtADJBgAFxRQRAIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsCQAJAIAAOFkpJSAEBAQEBAQEBAQEBAQEBAQEBAQABCyADQSk2AhwgAyABNgIUIANBshg2AhAgA0EVNgIMQQAhAgx7CyADQQA2AhwgAyABNgIUIANB3Qs2AhAgA0ERNgIMQQAhAgx6C0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAARQ1VIABBFUcNASADQQU2AhwgAyABNgIUIANBhho2AhAgA0EVNgIMQQAhAgx5C0HKACECDF4LQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDHcLIAMgAy8BMkGAAXI7ATIMOAsgASAERwRAIANBEDYCCCADIAE2AgRByQAhAgxcC0HXACECDHULIAEgBEYEQEHWACECDHULAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAPT09PT09PT09PT09AT09PQIDPQsgAUEBaiEBQcUAIQIMXQsgAUEBaiEBQcYAIQIMXAsgAUEBaiEBQccAIQIMWwsgAUEBaiEBQcgAIQIMWgtB1QAhAiAEIAEiAEYNcyAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcDQCABQcDGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQhBBCABQQVGDQoaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHMLQdQAIQIgBCABIgBGDXIgBCABayADKAIAIgFqIQYgACABa0EPaiEHA0AgAUGwxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0HQQMgAUEPRg0JGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxyC0HTACECIAQgASIARg1xIAQgAWsgAygCACIBaiEGIAAgAWtBDmohBwNAIAFBksYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNBiABQQ5GDQcgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMcQtB0gAhAiAEIAEiAEYNcCAEIAFrIAMoAgAiAWohBSAAIAFrQQFqIQYDQCABQZDGAGotAAAgAC0AACIHQSByIAcgB0HBAGtB/wFxQRpJG0H/AXFHDQUgAUEBRg0CIAFBAWohASAEIABBAWoiAEcNAAsgAyAFNgIADHALIAEgBEYEQEHRACECDHALAkACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcUHuAGsOBwA2NjY2NgE2CyABQQFqIQFBwgAhAgxWCyABQQFqIQFBwwAhAgxVCyADQQA2AgAgBkEBaiEBQcQAIQIMVAtB0AAhAiAEIAEiAEYNbSAEIAFrIAMoAgAiAWohBiAAIAFrQQlqIQcDQCABQYbGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQJBAiABQQlGDQQaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADG0LQc8AIQIgBCABIgBGDWwgBCABayADKAIAIgFqIQYgACABa0EFaiEHA0AgAUGAxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYNAiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxsCyAAIQEgA0EANgIADDALQQELOgAsIANBADYCACAHQQFqIQELQSwhAgxOCwJAA0AgAS0AAEGAxABqLQAAQQFHDQEgBCABQQFqIgFHDQALQc0AIQIMaAtBwQAhAgxNCyABIARGBEBBzAAhAgxnCyABLQAAQTpGBEAgAygCBCEAIANBADYCBCADIAAgARAvIgBFDTAgA0HLADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxnCyADQQA2AhwgAyABNgIUIANBuRE2AhAgA0EKNgIMQQAhAgxmCwJAAkAgAy0ALEECaw4CAAEkCyADQTNqLQAAQQJxRQ0jIAMtAC5BAnENIyADQQA2AhwgAyABNgIUIANB1RM2AhAgA0ELNgIMQQAhAgxmCyADLQAyQSBxRQ0iIAMtAC5BAnENIiADQQA2AhwgAyABNgIUIANB7BI2AhAgA0EPNgIMQQAhAgxlC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQRAQcAAIQIMSwsgAEEVRwRAIANBADYCHCADIAE2AhQgA0H4DjYCECADQRw2AgxBACECDGULIANBygA2AhwgAyABNgIUIANB8Bo2AhAgA0EVNgIMQQAhAgxkCyABIARHBEADQCABLQAAQfA/ai0AAEEBRw0XIAQgAUEBaiIBRw0AC0HEACECDGQLQcQAIQIMYwsgASAERwRAA0ACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcSIAQQlGDQAgAEEgRg0AAkACQAJAAkAgAEHjAGsOEwADAwMDAwMDAQMDAwMDAwMDAwIDCyABQQFqIQFBNSECDE4LIAFBAWohAUE2IQIMTQsgAUEBaiEBQTchAgxMCwwVCyAEIAFBAWoiAUcNAAtBPCECDGMLQTwhAgxiCyABIARGBEBByAAhAgxiCyADQRE2AgggAyABNgIEAkACQAJAAkACQCADLQAsQQFrDgQUAAECCQsgAy0AMkEgcQ0DQdEBIQIMSwsCQCADLwEyIgBBCHFFDQAgAy0AKEEBRw0AIAMtAC5BCHFFDQILIAMgAEH3+wNxQYAEcjsBMgwLCyADIAMvATJBEHI7ATIMBAsgA0EANgIEIAMgASABEDAiAARAIANBwQA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMYwsgAUEBaiEBDFILIANBADYCHCADIAE2AhQgA0GjEzYCECADQQQ2AgxBACECDGELQccAIQIgASAERg1gIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEHwwwBqLQAAIAEtAABBIHJHDQEgAEEGRg1GIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADGELIANBADYCAAwFCwJAIAEgBEcEQANAIAEtAABB8MEAai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBxQAhAgxhC0HFACECDGALCyADQQA6ACwMAQtBCyECDEMLQT4hAgxCCwJAAkADQCABLQAAIgBBIEcEQAJAIABBCmsOBAMFBQMACyAAQSxGDQMMBAsgBCABQQFqIgFHDQALQcYAIQIMXQsgA0EIOgAsDA4LIAMtAChBAUcNAiADLQAuQQhxDQIgAygCBCEAIANBADYCBCADIAAgARAwIgAEQCADQcIANgIcIAMgADYCDCADIAFBAWo2AhRBACECDFwLIAFBAWohAQxKC0E6IQIMQAsCQANAIAEtAAAiAEEgRyAAQQlHcQ0BIAQgAUEBaiIBRw0AC0HDACECDFoLC0E7IQIMPgsCQAJAIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBAMEBAMECyAEIAFBAWoiAUcNAAtBPyECDFoLQT8hAgxZCyADIAMvATJBIHI7ATIMCgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFDUggA0E+NgIcIAMgATYCFCADIAA2AgxBACECDFcLAkAgASAERwRAA0AgAS0AAEHwwQBqLQAAIgBBAUcEQCAAQQJGDQMMDAsgBCABQQFqIgFHDQALQTchAgxYC0E3IQIMVwsgAUEBaiEBDAQLQTshAiAEIAEiAEYNVSAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcCQANAIAFBwMYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQVGBEBBByEBDDsLIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFYLIANBADYCACAAIQEMBQtBOiECIAQgASIARg1UIAQgAWsgAygCACIBaiEGIAAgAWtBCGohBwJAA0AgAUHkP2otAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAUEIRgRAQQUhAQw6CyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxVCyADQQA2AgAgACEBDAQLQTkhAiAEIAEiAEYNUyAEIAFrIAMoAgAiAWohBiAAIAFrQQNqIQcCQANAIAFB4D9qLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBA0YEQEEGIQEMOQsgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMVAsgA0EANgIAIAAhAQwDCwJAA0AgAS0AACIAQSBHBEAgAEEKaw4EBwQEBwILIAQgAUEBaiIBRw0AC0E4IQIMUwsgAEEsRw0BIAFBAWohAEEBIQECQAJAAkACQAJAIAMtACxBBWsOBAMBAgQACyAAIQEMBAtBAiEBDAELQQQhAQsgA0EBOgAsIAMgAy8BMiABcjsBMiAAIQEMAQsgAyADLwEyQQhyOwEyIAAhAQtBPSECDDcLIANBADoALAtBOCECDDULIAEgBEYEQEE2IQIMTwsCQAJAAkACQAJAIAEtAABBCmsOBAACAgECCyADKAIEIQAgA0EANgIEIAMgACABEDAiAEUNAiADQTM2AhwgAyABNgIUIAMgADYCDEEAIQIMUgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFBEAgAUEBaiEBDAYLIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxRCyADLQAuQQFxBEBB0AEhAgw3CyADKAIEIQAgA0EANgIEIAMgACABEDAiAA0BDEMLQTMhAgw1CyADQTU2AhwgAyABNgIUIAMgADYCDEEAIQIMTgtBNCECDDMLIANBL2otAABBAXENACADQQA2AhwgAyABNgIUIANB8RU2AhAgA0EZNgIMQQAhAgxMC0EyIQIMMQsgASAERgRAQTIhAgxLCwJAIAEtAABBCkYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZgWNgIQIANBAzYCDEEAIQIMSwtBMSECDDALIAEgBEYEQEExIQIMSgsgAS0AACIAQQlHIABBIEdxDQEgAy0ALEEIRw0AIANBADoALAtBPCECDC4LQQEhAgJAAkACQAJAIAMtACxBBWsOBAMBAgAKCyADIAMvATJBCHI7ATIMCQtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgwGCyABIARGBEBBMCECDEcLIAEtAABBCkYEQCABQQFqIQEMAQsgAy0ALkEBcQ0AIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDEYLQS8hAgwrCyABQQFqIQFBMCECDCoLIAEgBEYEQEEvIQIMRAsgAS0AACIAQQlHIABBIEdxRQRAIAFBAWohASADLQAuQQFxDQEgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIMRAtBASECAkACQAJAAkACQAJAIAMtACxBAmsOBwUEBAMBAgAECyADIAMvATJBCHI7ATIMAwtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgtBLiECDCoLIANBADYCHCADIAE2AhQgA0GzEjYCECADQQs2AgxBACECDEMLQdIBIQIMKAsgASAERgRAQS4hAgxCCyADQQA2AgQgA0ERNgIIIAMgASABEDAiAA0BC0EtIQIMJgsgA0EtNgIcIAMgATYCFCADIAA2AgxBACECDD8LQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2AA2AhwgAyABNgIUIANBnho2AhAgA0EVNgIMQQAhAgw+C0HLACECDCMLIANBADYCHCADIAE2AhQgA0GFDjYCECADQR02AgxBACECDDwLIAEgBEYEQEHOACECDDwLIAEtAAAiAEEgRg0CIABBOkYNAQsgA0EAOgAsQQkhAgwgCyADKAIEIQAgA0EANgIEIAMgACABEC8iAA0BDAILIAMtAC5BAXEEQEHPASECDB8LIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ0CIANBKjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgw4CyADQcsANgIcIAMgADYCDCADIAFBAWo2AhRBACECDDcLIAFBAWohAUE/IQIMHAsgAUEBaiEBDCkLIAEgBEYEQEErIQIMNQsCQCABLQAAQQpGBEAgAUEBaiEBDAELIAMtAC5BwABxRQ0GCyADLQAyQYABcQRAQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIABFDREgAEEVRgRAIANBBTYCHCADIAE2AhQgA0GGGjYCECADQRU2AgxBACECDDYLIANBADYCHCADIAE2AhQgA0HiDTYCECADQRQ2AgxBACECDDULIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsgAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIANBAToAMAsgAiACLwEAQcAAcjsBAAtBKiECDBcLIANBKTYCHCADIAE2AhQgA0GyGDYCECADQRU2AgxBACECDDALIANBADYCHCADIAE2AhQgA0HdCzYCECADQRE2AgxBACECDC8LIANBADYCHCADIAE2AhQgA0GdCzYCECADQQI2AgxBACECDC4LQQEhByADLwEyIgVBCHFFBEAgAykDIEIAUiEHCwJAIAMtADAEQEEBIQAgAy0AKUEFRg0BIAVBwABxRSAHcUUNAQsCQCADLQAoIgJBAkYEQEEBIQAgAy8BNCIGQeUARg0CQQAhACAFQcAAcQ0CIAZB5ABGDQIgBkHmAGtBAkkNAiAGQcwBRg0CIAZBsAJGDQIMAQtBACEAIAVBwABxDQELQQIhACAFQQhxDQAgBUGABHEEQAJAIAJBAUcNACADLQAuQQpxDQBBBSEADAILQQQhAAwBCyAFQSBxRQRAIAMQNUEAR0ECdCEADAELQQBBAyADKQMgUBshAAsCQCAAQQFrDgUAAQYHAgMLQQAhAgJAIAMoAjgiAEUNACAAKAIsIgBFDQAgAyAAEQAAIQILIAJFDSYgAkEVRgRAIANBAzYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDC4LQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDC0LQc4BIQIMEgtBACECIANBADYCHCADIAE2AhQgA0HkHzYCECADQQ82AgwMKwtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAA0BC0EOIQIMDwsgAEEVRgRAIANBAjYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDCkLQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDCgLQSkhAgwNCyADQQE6ADEMJAsgASAERwRAIANBCTYCCCADIAE2AgRBKCECDAwLQSYhAgwlCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMVARAQSUhAgwlCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDQAgA0EFNgIcIAMgATYCFCADIAA2AgwMJAtBDyECDAkLIAEgBEYEQEEjIQIMIwtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsONxcWAAECAwQFBgcUFBQUFBQUCAkKCwwNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQODxAREhMUC0ICIQoMFgtCAyEKDBULQgQhCgwUC0IFIQoMEwtCBiEKDBILQgchCgwRC0IIIQoMEAtCCSEKDA8LQgohCgwOC0ILIQoMDQtCDCEKDAwLQg0hCgwLC0IOIQoMCgtCDyEKDAkLQgohCgwIC0ILIQoMBwtCDCEKDAYLQg0hCgwFC0IOIQoMBAtCDyEKDAMLQQAhAiADQQA2AhwgAyABNgIUIANBzhQ2AhAgA0EMNgIMDCILIAEgBEYEQEEiIQIMIgtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQTBrDjcVFAABAgMEBQYHFhYWFhYWFggJCgsMDRYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWDg8QERITFgtCAiEKDBQLQgMhCgwTC0IEIQoMEgtCBSEKDBELQgYhCgwQC0IHIQoMDwtCCCEKDA4LQgkhCgwNC0IKIQoMDAtCCyEKDAsLQgwhCgwKC0INIQoMCQtCDiEKDAgLQg8hCgwHC0IKIQoMBgtCCyEKDAULQgwhCgwEC0INIQoMAwtCDiEKDAILQg8hCgwBC0IBIQoLIAFBAWohASADKQMgIgtC//////////8PWARAIAMgC0IEhiAKhDcDIAwCC0EAIQIgA0EANgIcIAMgATYCFCADQa0JNgIQIANBDDYCDAwfC0ElIQIMBAtBJiECDAMLIAMgAToALCADQQA2AgAgB0EBaiEBQQwhAgwCCyADQQA2AgAgBkEBaiEBQQohAgwBCyABQQFqIQFBCCECDAALAAtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMGAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMFwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMFgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMFQtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMFAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMEwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMEgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMEQtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMEAtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMDwtBACECIANBADYCHCADIAE2AhQgA0HIEjYCECADQQs2AgwMDgtBACECIANBADYCHCADIAE2AhQgA0GVCTYCECADQQs2AgwMDQtBACECIANBADYCHCADIAE2AhQgA0HpDzYCECADQQo2AgwMDAtBACECIANBADYCHCADIAE2AhQgA0GDEDYCECADQQo2AgwMCwtBACECIANBADYCHCADIAE2AhQgA0GmHDYCECADQQI2AgwMCgtBACECIANBADYCHCADIAE2AhQgA0HFFTYCECADQQI2AgwMCQtBACECIANBADYCHCADIAE2AhQgA0H/FzYCECADQQI2AgwMCAtBACECIANBADYCHCADIAE2AhQgA0HKFzYCECADQQI2AgwMBwsgA0ECNgIcIAMgATYCFCADQZQdNgIQIANBFjYCDEEAIQIMBgtB3gAhAiABIARGDQUgCUEIaiEHIAMoAgAhBQJAAkAgASAERwRAIAVBxsYAaiEIIAQgBWogAWshBiAFQX9zQQpqIgUgAWohAANAIAEtAAAgCC0AAEcEQEECIQgMAwsgBUUEQEEAIQggACEBDAMLIAVBAWshBSAIQQFqIQggBCABQQFqIgFHDQALIAYhBSAEIQELIAdBATYCACADIAU2AgAMAQsgA0EANgIAIAcgCDYCAAsgByABNgIEIAkoAgwhACAJKAIIDgMBBQIACwALIANBADYCHCADQa0dNgIQIANBFzYCDCADIABBAWo2AhRBACECDAMLIANBADYCHCADIAA2AhQgA0HCHTYCECADQQk2AgxBACECDAILIAEgBEYEQEEoIQIMAgsgA0EJNgIIIAMgATYCBEEnIQIMAQsgASAERgRAQQEhAgwBCwNAAkACQAJAIAEtAABBCmsOBAABAQABCyABQQFqIQEMAQsgAUEBaiEBIAMtAC5BIHENAEEAIQIgA0EANgIcIAMgATYCFCADQYwgNgIQIANBBTYCDAwCC0EBIQIgASAERw0ACwsgCUEQaiQAIAJFBEAgAygCDCEADAELIAMgAjYCHEEAIQAgAygCBCIBRQ0AIAMgASAEIAMoAggRAQAiAUUNACADIAQ2AhQgAyABNgIMIAEhAAsgAAu+AgECfyAAQQA6AAAgAEHcAGoiAUEBa0EAOgAAIABBADoAAiAAQQA6AAEgAUEDa0EAOgAAIAFBAmtBADoAACAAQQA6AAMgAUEEa0EAOgAAQQAgAGtBA3EiASAAaiIAQQA2AgBB3AAgAWtBfHEiAiAAaiIBQQRrQQA2AgACQCACQQlJDQAgAEEANgIIIABBADYCBCABQQhrQQA2AgAgAUEMa0EANgIAIAJBGUkNACAAQQA2AhggAEEANgIUIABBADYCECAAQQA2AgwgAUEQa0EANgIAIAFBFGtBADYCACABQRhrQQA2AgAgAUEca0EANgIAIAIgAEEEcUEYciICayIBQSBJDQAgACACaiEAA0AgAEIANwMYIABCADcDECAAQgA3AwggAEIANwMAIABBIGohACABQSBrIgFBH0sNAAsLC1YBAX8CQCAAKAIMDQACQAJAAkACQCAALQAxDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgAREAACIBDQMLQQAPCwALIABB0Bg2AhBBDiEBCyABCxoAIAAoAgxFBEAgAEHJHjYCECAAQRU2AgwLCxQAIAAoAgxBFUYEQCAAQQA2AgwLCxQAIAAoAgxBFkYEQCAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsXACAAQSRPBEAACyAAQQJ0QZQ3aigCAAsXACAAQS9PBEAACyAAQQJ0QaQ4aigCAAu/CQEBf0HfLCEBAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHkAGsO9ANjYgABYWFhYWFhAgMEBWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEGBwgJCgsMDQ4PYWFhYWEQYWFhYWFhYWFhYWERYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhEhMUFRYXGBkaG2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEcHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTZhNzg5OmFhYWFhYWFhO2FhYTxhYWFhPT4/YWFhYWFhYWFAYWFBYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhQkNERUZHSElKS0xNTk9QUVJTYWFhYWFhYWFUVVZXWFlaW2FcXWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYV5hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFfYGELQdUrDwtBgyUPC0G/MA8LQfI1DwtBtCgPC0GfKA8LQYEsDwtB1ioPC0H0Mw8LQa0zDwtByygPC0HOIw8LQcAjDwtB2SMPC0HRJA8LQZwzDwtBojYPC0H8Mw8LQeArDwtB4SUPC0HtIA8LQcQyDwtBqScPC0G5Ng8LQbggDwtBqyAPC0GjJA8LQbYkDwtBgSMPC0HhMg8LQZ80DwtByCkPC0HAMg8LQe4yDwtB8C8PC0HGNA8LQdAhDwtBmiQPC0HrLw8LQYQ1DwtByzUPC0GWMQ8LQcgrDwtB1C8PC0GTMA8LQd81DwtBtCMPC0G+NQ8LQdIpDwtBsyIPC0HNIA8LQZs2DwtBkCEPC0H/IA8LQa01DwtBsDQPC0HxJA8LQacqDwtB3TAPC0GLIg8LQcgvDwtB6yoPC0H0KQ8LQY8lDwtB3SIPC0HsJg8LQf0wDwtB1iYPC0GUNQ8LQY0jDwtBuikPC0HHIg8LQfIlDwtBtjMPC0GiIQ8LQf8vDwtBwCEPC0GBMw8LQcklDwtBqDEPC0HGMw8LQdM2DwtBxjYPC0HkNA8LQYgmDwtB7ScPC0H4IQ8LQakwDwtBjzQPC0GGNg8LQaovDwtBoSYPC0HsNg8LQZIpDwtBryYPC0GZIg8LQeAhDwsAC0G1JSEBCyABCxcAIAAgAC8BLkH+/wNxIAFBAEdyOwEuCxoAIAAgAC8BLkH9/wNxIAFBAEdBAXRyOwEuCxoAIAAgAC8BLkH7/wNxIAFBAEdBAnRyOwEuCxoAIAAgAC8BLkH3/wNxIAFBAEdBA3RyOwEuCxoAIAAgAC8BLkHv/wNxIAFBAEdBBHRyOwEuCxoAIAAgAC8BLkHf/wNxIAFBAEdBBXRyOwEuCxoAIAAgAC8BLkG//wNxIAFBAEdBBnRyOwEuCxoAIAAgAC8BLkH//gNxIAFBAEdBB3RyOwEuCxoAIAAgAC8BLkH//QNxIAFBAEdBCHRyOwEuCxoAIAAgAC8BLkH/+wNxIAFBAEdBCXRyOwEuCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBzhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5Ao2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5R02AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBnRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBoh42AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7hQ2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9xs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRU2AhBBGCEECyAECzgAIAACfyAALwEyQRRxQRRGBEBBASAALQAoQQFGDQEaIAAvATRB5QBGDAELIAAtAClBBUYLOgAwC1kBAn8CQCAALQAoQQFGDQAgAC8BNCIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMiIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEyIgFBAnFFDQEMAgsgAC8BMiIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATQiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtXACAAQRhqQgA3AwAgAEIANwMAIABBOGpCADcDACAAQTBqQgA3AwAgAEEoakIANwMAIABBIGpCADcDACAAQRBqQgA3AwAgAEEIakIANwMAIABB7AE2AhwLBgAgABA5C5otAQt/IwBBEGsiCiQAQZjUACgCACIJRQRAQdjXACgCACIFRQRAQeTXAEJ/NwIAQdzXAEKAgISAgIDAADcCAEHY1wAgCkEIakFwcUHYqtWqBXMiBTYCAEHs1wBBADYCAEG81wBBADYCAAtBwNcAQYDYBDYCAEGQ1ABBgNgENgIAQaTUACAFNgIAQaDUAEF/NgIAQcTXAEGAqAM2AgADQCABQbzUAGogAUGw1ABqIgI2AgAgAiABQajUAGoiAzYCACABQbTUAGogAzYCACABQcTUAGogAUG41ABqIgM2AgAgAyACNgIAIAFBzNQAaiABQcDUAGoiAjYCACACIAM2AgAgAUHI1ABqIAI2AgAgAUEgaiIBQYACRw0AC0GM2ARBwacDNgIAQZzUAEHo1wAoAgA2AgBBjNQAQcCnAzYCAEGY1ABBiNgENgIAQcz/B0E4NgIAQYjYBCEJCwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFNBEBBgNQAKAIAIgZBECAAQRNqQXBxIABBC0kbIgRBA3YiAHYiAUEDcQRAAkAgAUEBcSAAckEBcyICQQN0IgBBqNQAaiIBIABBsNQAaigCACIAKAIIIgNGBEBBgNQAIAZBfiACd3E2AgAMAQsgASADNgIIIAMgATYCDAsgAEEIaiEBIAAgAkEDdCICQQNyNgIEIAAgAmoiACAAKAIEQQFyNgIEDBELQYjUACgCACIIIARPDQEgAQRAAkBBAiAAdCICQQAgAmtyIAEgAHRxaCIAQQN0IgJBqNQAaiIBIAJBsNQAaigCACICKAIIIgNGBEBBgNQAIAZBfiAAd3EiBjYCAAwBCyABIAM2AgggAyABNgIMCyACIARBA3I2AgQgAEEDdCIAIARrIQUgACACaiAFNgIAIAIgBGoiBCAFQQFyNgIEIAgEQCAIQXhxQajUAGohAEGU1AAoAgAhAwJ/QQEgCEEDdnQiASAGcUUEQEGA1AAgASAGcjYCACAADAELIAAoAggLIgEgAzYCDCAAIAM2AgggAyAANgIMIAMgATYCCAsgAkEIaiEBQZTUACAENgIAQYjUACAFNgIADBELQYTUACgCACILRQ0BIAtoQQJ0QbDWAGooAgAiACgCBEF4cSAEayEFIAAhAgNAAkAgAigCECIBRQRAIAJBFGooAgAiAUUNAQsgASgCBEF4cSAEayIDIAVJIQIgAyAFIAIbIQUgASAAIAIbIQAgASECDAELCyAAKAIYIQkgACgCDCIDIABHBEBBkNQAKAIAGiADIAAoAggiATYCCCABIAM2AgwMEAsgAEEUaiICKAIAIgFFBEAgACgCECIBRQ0DIABBEGohAgsDQCACIQcgASIDQRRqIgIoAgAiAQ0AIANBEGohAiADKAIQIgENAAsgB0EANgIADA8LQX8hBCAAQb9/Sw0AIABBE2oiAUFwcSEEQYTUACgCACIIRQ0AQQAgBGshBQJAAkACQAJ/QQAgBEGAAkkNABpBHyAEQf///wdLDQAaIARBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgZBAnRBsNYAaigCACICRQRAQQAhAUEAIQMMAQtBACEBIARBGSAGQQF2a0EAIAZBH0cbdCEAQQAhAwNAAkAgAigCBEF4cSAEayIHIAVPDQAgAiEDIAciBQ0AQQAhBSACIQEMAwsgASACQRRqKAIAIgcgByACIABBHXZBBHFqQRBqKAIAIgJGGyABIAcbIQEgAEEBdCEAIAINAAsLIAEgA3JFBEBBACEDQQIgBnQiAEEAIABrciAIcSIARQ0DIABoQQJ0QbDWAGooAgAhAQsgAUUNAQsDQCABKAIEQXhxIARrIgIgBUkhACACIAUgABshBSABIAMgABshAyABKAIQIgAEfyAABSABQRRqKAIACyIBDQALCyADRQ0AIAVBiNQAKAIAIARrTw0AIAMoAhghByADIAMoAgwiAEcEQEGQ1AAoAgAaIAAgAygCCCIBNgIIIAEgADYCDAwOCyADQRRqIgIoAgAiAUUEQCADKAIQIgFFDQMgA0EQaiECCwNAIAIhBiABIgBBFGoiAigCACIBDQAgAEEQaiECIAAoAhAiAQ0ACyAGQQA2AgAMDQtBiNQAKAIAIgMgBE8EQEGU1AAoAgAhAQJAIAMgBGsiAkEQTwRAIAEgBGoiACACQQFyNgIEIAEgA2ogAjYCACABIARBA3I2AgQMAQsgASADQQNyNgIEIAEgA2oiACAAKAIEQQFyNgIEQQAhAEEAIQILQYjUACACNgIAQZTUACAANgIAIAFBCGohAQwPC0GM1AAoAgAiAyAESwRAIAQgCWoiACADIARrIgFBAXI2AgRBmNQAIAA2AgBBjNQAIAE2AgAgCSAEQQNyNgIEIAlBCGohAQwPC0EAIQEgBAJ/QdjXACgCAARAQeDXACgCAAwBC0Hk1wBCfzcCAEHc1wBCgICEgICAwAA3AgBB2NcAIApBDGpBcHFB2KrVqgVzNgIAQezXAEEANgIAQbzXAEEANgIAQYCABAsiACAEQccAaiIFaiIGQQAgAGsiB3EiAk8EQEHw1wBBMDYCAAwPCwJAQbjXACgCACIBRQ0AQbDXACgCACIIIAJqIQAgACABTSAAIAhLcQ0AQQAhAUHw1wBBMDYCAAwPC0G81wAtAABBBHENBAJAAkAgCQRAQcDXACEBA0AgASgCACIAIAlNBEAgACABKAIEaiAJSw0DCyABKAIIIgENAAsLQQAQOiIAQX9GDQUgAiEGQdzXACgCACIBQQFrIgMgAHEEQCACIABrIAAgA2pBACABa3FqIQYLIAQgBk8NBSAGQf7///8HSw0FQbjXACgCACIDBEBBsNcAKAIAIgcgBmohASABIAdNDQYgASADSw0GCyAGEDoiASAARw0BDAcLIAYgA2sgB3EiBkH+////B0sNBCAGEDohACAAIAEoAgAgASgCBGpGDQMgACEBCwJAIAYgBEHIAGpPDQAgAUF/Rg0AQeDXACgCACIAIAUgBmtqQQAgAGtxIgBB/v///wdLBEAgASEADAcLIAAQOkF/RwRAIAAgBmohBiABIQAMBwtBACAGaxA6GgwECyABIgBBf0cNBQwDC0EAIQMMDAtBACEADAoLIABBf0cNAgtBvNcAQbzXACgCAEEEcjYCAAsgAkH+////B0sNASACEDohAEEAEDohASAAQX9GDQEgAUF/Rg0BIAAgAU8NASABIABrIgYgBEE4ak0NAQtBsNcAQbDXACgCACAGaiIBNgIAQbTXACgCACABSQRAQbTXACABNgIACwJAAkACQEGY1AAoAgAiAgRAQcDXACEBA0AgACABKAIAIgMgASgCBCIFakYNAiABKAIIIgENAAsMAgtBkNQAKAIAIgFBAEcgACABT3FFBEBBkNQAIAA2AgALQQAhAUHE1wAgBjYCAEHA1wAgADYCAEGg1ABBfzYCAEGk1ABB2NcAKAIANgIAQczXAEEANgIAA0AgAUG81ABqIAFBsNQAaiICNgIAIAIgAUGo1ABqIgM2AgAgAUG01ABqIAM2AgAgAUHE1ABqIAFBuNQAaiIDNgIAIAMgAjYCACABQczUAGogAUHA1ABqIgI2AgAgAiADNgIAIAFByNQAaiACNgIAIAFBIGoiAUGAAkcNAAtBeCAAa0EPcSIBIABqIgIgBkE4ayIDIAFrIgFBAXI2AgRBnNQAQejXACgCADYCAEGM1AAgATYCAEGY1AAgAjYCACAAIANqQTg2AgQMAgsgACACTQ0AIAIgA0kNACABKAIMQQhxDQBBeCACa0EPcSIAIAJqIgNBjNQAKAIAIAZqIgcgAGsiAEEBcjYCBCABIAUgBmo2AgRBnNQAQejXACgCADYCAEGM1AAgADYCAEGY1AAgAzYCACACIAdqQTg2AgQMAQsgAEGQ1AAoAgBJBEBBkNQAIAA2AgALIAAgBmohA0HA1wAhAQJAAkACQANAIAMgASgCAEcEQCABKAIIIgENAQwCCwsgAS0ADEEIcUUNAQtBwNcAIQEDQCABKAIAIgMgAk0EQCADIAEoAgRqIgUgAksNAwsgASgCCCEBDAALAAsgASAANgIAIAEgASgCBCAGajYCBCAAQXggAGtBD3FqIgkgBEEDcjYCBCADQXggA2tBD3FqIgYgBCAJaiIEayEBIAIgBkYEQEGY1AAgBDYCAEGM1ABBjNQAKAIAIAFqIgA2AgAgBCAAQQFyNgIEDAgLQZTUACgCACAGRgRAQZTUACAENgIAQYjUAEGI1AAoAgAgAWoiADYCACAEIABBAXI2AgQgACAEaiAANgIADAgLIAYoAgQiBUEDcUEBRw0GIAVBeHEhCCAFQf8BTQRAIAVBA3YhAyAGKAIIIgAgBigCDCICRgRAQYDUAEGA1AAoAgBBfiADd3E2AgAMBwsgAiAANgIIIAAgAjYCDAwGCyAGKAIYIQcgBiAGKAIMIgBHBEAgACAGKAIIIgI2AgggAiAANgIMDAULIAZBFGoiAigCACIFRQRAIAYoAhAiBUUNBCAGQRBqIQILA0AgAiEDIAUiAEEUaiICKAIAIgUNACAAQRBqIQIgACgCECIFDQALIANBADYCAAwEC0F4IABrQQ9xIgEgAGoiByAGQThrIgMgAWsiAUEBcjYCBCAAIANqQTg2AgQgAiAFQTcgBWtBD3FqQT9rIgMgAyACQRBqSRsiA0EjNgIEQZzUAEHo1wAoAgA2AgBBjNQAIAE2AgBBmNQAIAc2AgAgA0EQakHI1wApAgA3AgAgA0HA1wApAgA3AghByNcAIANBCGo2AgBBxNcAIAY2AgBBwNcAIAA2AgBBzNcAQQA2AgAgA0EkaiEBA0AgAUEHNgIAIAUgAUEEaiIBSw0ACyACIANGDQAgAyADKAIEQX5xNgIEIAMgAyACayIFNgIAIAIgBUEBcjYCBCAFQf8BTQRAIAVBeHFBqNQAaiEAAn9BgNQAKAIAIgFBASAFQQN2dCIDcUUEQEGA1AAgASADcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbDWAGohAEGE1AAoAgAiA0EBIAF0IgZxRQRAIAAgAjYCAEGE1AAgAyAGcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQMCQANAIAMiACgCBEF4cSAFRg0BIAFBHXYhAyABQQF0IQEgACADQQRxakEQaiIGKAIAIgMNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAtBjNQAKAIAIgEgBE0NAEGY1AAoAgAiACAEaiICIAEgBGsiAUEBcjYCBEGM1AAgATYCAEGY1AAgAjYCACAAIARBA3I2AgQgAEEIaiEBDAgLQQAhAUHw1wBBMDYCAAwHC0EAIQALIAdFDQACQCAGKAIcIgJBAnRBsNYAaiIDKAIAIAZGBEAgAyAANgIAIAANAUGE1ABBhNQAKAIAQX4gAndxNgIADAILIAdBEEEUIAcoAhAgBkYbaiAANgIAIABFDQELIAAgBzYCGCAGKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAGQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAIaiEBIAYgCGoiBigCBCEFCyAGIAVBfnE2AgQgASAEaiABNgIAIAQgAUEBcjYCBCABQf8BTQRAIAFBeHFBqNQAaiEAAn9BgNQAKAIAIgJBASABQQN2dCIBcUUEQEGA1AAgASACcjYCACAADAELIAAoAggLIgEgBDYCDCAAIAQ2AgggBCAANgIMIAQgATYCCAwBC0EfIQUgAUH///8HTQRAIAFBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmohBQsgBCAFNgIcIARCADcCECAFQQJ0QbDWAGohAEGE1AAoAgAiAkEBIAV0IgNxRQRAIAAgBDYCAEGE1AAgAiADcjYCACAEIAA2AhggBCAENgIIIAQgBDYCDAwBCyABQRkgBUEBdmtBACAFQR9HG3QhBSAAKAIAIQACQANAIAAiAigCBEF4cSABRg0BIAVBHXYhACAFQQF0IQUgAiAAQQRxakEQaiIDKAIAIgANAAsgAyAENgIAIAQgAjYCGCAEIAQ2AgwgBCAENgIIDAELIAIoAggiACAENgIMIAIgBDYCCCAEQQA2AhggBCACNgIMIAQgADYCCAsgCUEIaiEBDAILAkAgB0UNAAJAIAMoAhwiAUECdEGw1gBqIgIoAgAgA0YEQCACIAA2AgAgAA0BQYTUACAIQX4gAXdxIgg2AgAMAgsgB0EQQRQgBygCECADRhtqIAA2AgAgAEUNAQsgACAHNgIYIAMoAhAiAQRAIAAgATYCECABIAA2AhgLIANBFGooAgAiAUUNACAAQRRqIAE2AgAgASAANgIYCwJAIAVBD00EQCADIAQgBWoiAEEDcjYCBCAAIANqIgAgACgCBEEBcjYCBAwBCyADIARqIgIgBUEBcjYCBCADIARBA3I2AgQgAiAFaiAFNgIAIAVB/wFNBEAgBUF4cUGo1ABqIQACf0GA1AAoAgAiAUEBIAVBA3Z0IgVxRQRAQYDUACABIAVyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRBsNYAaiEAQQEgAXQiBCAIcUUEQCAAIAI2AgBBhNQAIAQgCHI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEEAkADQCAEIgAoAgRBeHEgBUYNASABQR12IQQgAUEBdCEBIAAgBEEEcWpBEGoiBigCACIEDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLIANBCGohAQwBCwJAIAlFDQACQCAAKAIcIgFBAnRBsNYAaiICKAIAIABGBEAgAiADNgIAIAMNAUGE1AAgC0F+IAF3cTYCAAwCCyAJQRBBFCAJKAIQIABGG2ogAzYCACADRQ0BCyADIAk2AhggACgCECIBBEAgAyABNgIQIAEgAzYCGAsgAEEUaigCACIBRQ0AIANBFGogATYCACABIAM2AhgLAkAgBUEPTQRAIAAgBCAFaiIBQQNyNgIEIAAgAWoiASABKAIEQQFyNgIEDAELIAAgBGoiByAFQQFyNgIEIAAgBEEDcjYCBCAFIAdqIAU2AgAgCARAIAhBeHFBqNQAaiEBQZTUACgCACEDAn9BASAIQQN2dCICIAZxRQRAQYDUACACIAZyNgIAIAEMAQsgASgCCAsiAiADNgIMIAEgAzYCCCADIAE2AgwgAyACNgIIC0GU1AAgBzYCAEGI1AAgBTYCAAsgAEEIaiEBCyAKQRBqJAAgAQtDACAARQRAPwBBEHQPCwJAIABB//8DcQ0AIABBAEgNACAAQRB2QAAiAEF/RgRAQfDXAEEwNgIAQX8PCyAAQRB0DwsACwvbQCIAQYAICwkBAAAAAgAAAAMAQZQICwUEAAAABQBBpAgLCQYAAAAHAAAACABB3AgLgjFJbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBFeHBlY3RlZCBMRiBhZnRlciBoZWFkZXJzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABUcmFuc2Zlci1FbmNvZGluZyBjYW4ndCBiZSBwcmVzZW50IHdpdGggQ29udGVudC1MZW5ndGgARHVwbGljYXRlIENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhciBpbiB1cmwgcGF0aABDb250ZW50LUxlbmd0aCBjYW4ndCBiZSBwcmVzZW50IHdpdGggVHJhbnNmZXItRW5jb2RpbmcATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBzaXplAEV4cGVjdGVkIExGIGFmdGVyIGNodW5rIHNpemUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgc2l6ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl92YWx1ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBleHRlbnNpb24gdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIHF1b3RlZC1wYWlyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciByZXNwb25zZSBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIG5hbWUASW52YWxpZCBzdGF0dXMgY29kZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGRhdGEARXhwZWN0ZWQgTEYgYWZ0ZXIgY2h1bmsgZGF0YQBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AARGF0YSBhZnRlciBgQ29ubmVjdGlvbjogY2xvc2VgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBRVUVSWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAEV4cGVjdGVkIExGIGFmdGVyIENSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAUhUAABoVAAAPEgAA5BkAAJEVAAAJFAAALRkAAOQUAADpEQAAaRQAAKEUAAB2FQAAQxYAAF4SAACUFwAAFxYAAH0UAAB/FgAAQRcAALMTAADDFgAABBoAAL0YAADQGAAAoBMAANQZAACvFgAAaBYAAHAXAADZFgAA/BgAAP4RAABZFwAAlxYAABwXAAD2FgAAjRcAAAsSAAB/GwAALhEAALMQAABJEgAArRIAAPYYAABoEAAAYhUAABAVAABaFgAAShkAALUVAADBFQAAYBUAAFwZAABaGQAAUxkAABYVAACtEQAAQhAAALcQAABXGAAAvxUAAIkQAAAcGQAAGhkAALkVAABRGAAA3BMAAFsVAABZFQAA5hgAAGcVAAARGQAA7RgAAOcTAACuEAAAwhcAAAAUAACSEwAAhBMAAEASAAAmGQAArxUAAGIQAEHpOQsBAQBBgDoL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB6jsLBAEAAAIAQYE8C14DBAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAUAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEHqPQsEAQAAAgBBgT4LXgMAAwMDAwMAAAMDAAMDAAMDAwMDAwMDAwMABAAFAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwADAAMAQeA/Cw1sb3NlZWVwLWFsaXZlAEH5PwsBAQBBkMAAC+ABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQfnBAAsBAQBBkMIAC+cBAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAEGhxAALXgEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAQYDGAAshZWN0aW9uZW50LWxlbmd0aG9ucm94eS1jb25uZWN0aW9uAEGwxgALK3JhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KU00NCg0KVFRQL0NFL1RTUC8AQenGAAsFAQIAAQMAQYDHAAtfBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQenIAAsFAQIAAQMAQYDJAAtfBAUFBgUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQenKAAsEAQAAAQBBgcsAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEHpzAALBQECAAEDAEGAzQALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEHpzgALBQEBAAEBAEGAzwALAQEAQZrPAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQenQAAsFAQEAAQEAQYDRAAsBAQBBitEACwYCAAAAAAIAQaHRAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB4NIAC5oBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==";
var wasmBuffer;
Object.defineProperty(module3, "exports", {
get: /* @__PURE__ */ __name(() => {
return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer7.from(wasmBase64, "base64");
}, "get")
});
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Buffer: Buffer7 } = require("buffer");
var wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzQzBQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEDAAADAAAABAUBcAESEgUDAQACBggBfwFBgNgECwfFBygGbWVtb3J5AgALX2luaXRpYWxpemUACBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQACRhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUANgxsbGh0dHBfYWxsb2MACwZtYWxsb2MAOAtsbGh0dHBfZnJlZQAMBGZyZWUADA9sbGh0dHBfZ2V0X3R5cGUADRVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADhVsbGh0dHBfZ2V0X2h0dHBfbWlub3IADxFsbGh0dHBfZ2V0X21ldGhvZAAQFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAERJsbGh0dHBfZ2V0X3VwZ3JhZGUAEgxsbGh0dHBfcmVzZXQAEw5sbGh0dHBfZXhlY3V0ZQAUFGxsaHR0cF9zZXR0aW5nc19pbml0ABUNbGxodHRwX2ZpbmlzaAAWDGxsaHR0cF9wYXVzZQAXDWxsaHR0cF9yZXN1bWUAGBtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGRBsbGh0dHBfZ2V0X2Vycm5vABoXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AGxdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAcFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB0RbGxodHRwX2Vycm5vX25hbWUAHhJsbGh0dHBfbWV0aG9kX25hbWUAHxJsbGh0dHBfc3RhdHVzX25hbWUAIBpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAhIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAiHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACMkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACQabGxodHRwX3NldF9sZW5pZW50X3ZlcnNpb24AJSNsbGh0dHBfc2V0X2xlbmllbnRfZGF0YV9hZnRlcl9jbG9zZQAmJ2xsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9sZl9hZnRlcl9jcgAnLGxsaHR0cF9zZXRfbGVuaWVudF9vcHRpb25hbF9jcmxmX2FmdGVyX2NodW5rACgobGxodHRwX3NldF9sZW5pZW50X29wdGlvbmFsX2NyX2JlZm9yZV9sZgApKmxsaHR0cF9zZXRfbGVuaWVudF9zcGFjZXNfYWZ0ZXJfY2h1bmtfc2l6ZQAqGGxsaHR0cF9tZXNzYWdlX25lZWRzX2VvZgA1CRcBAEEBCxEBAgMEBQoGBzEzMi0uLCsvMArYywIzFgBB/NMAKAIABEAAC0H80wBBATYCAAsUACAAEDcgACACNgI4IAAgAToAKAsUACAAIAAvATQgAC0AMCAAEDYQAAseAQF/QcAAEDkiARA3IAFBgAg2AjggASAAOgAoIAELjwwBB38CQCAARQ0AIABBCGsiASAAQQRrKAIAIgBBeHEiBGohBQJAIABBAXENACAAQQNxRQ0BIAEgASgCACIAayIBQZDUACgCAEkNASAAIARqIQQCQAJAQZTUACgCACABRwRAIABB/wFNBEAgAEEDdiEDIAEoAggiACABKAIMIgJGBEBBgNQAQYDUACgCAEF+IAN3cTYCAAwFCyACIAA2AgggACACNgIMDAQLIAEoAhghBiABIAEoAgwiAEcEQCAAIAEoAggiAjYCCCACIAA2AgwMAwsgAUEUaiIDKAIAIgJFBEAgASgCECICRQ0CIAFBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUoAgQiAEEDcUEDRw0CIAUgAEF+cTYCBEGI1AAgBDYCACAFIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAEoAhwiAkECdEGw1gBqIgMoAgAgAUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECABRhtqIAA2AgAgAEUNAQsgACAGNgIYIAEoAhAiAgRAIAAgAjYCECACIAA2AhgLIAFBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIAVPDQAgBSgCBCIAQQFxRQ0AAkACQAJAAkAgAEECcUUEQEGY1AAoAgAgBUYEQEGY1AAgATYCAEGM1ABBjNQAKAIAIARqIgA2AgAgASAAQQFyNgIEIAFBlNQAKAIARw0GQYjUAEEANgIAQZTUAEEANgIADAYLQZTUACgCACAFRgRAQZTUACABNgIAQYjUAEGI1AAoAgAgBGoiADYCACABIABBAXI2AgQgACABaiAANgIADAYLIABBeHEgBGohBCAAQf8BTQRAIABBA3YhAyAFKAIIIgAgBSgCDCICRgRAQYDUAEGA1AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyAFKAIYIQYgBSAFKAIMIgBHBEBBkNQAKAIAGiAAIAUoAggiAjYCCCACIAA2AgwMAwsgBUEUaiIDKAIAIgJFBEAgBSgCECICRQ0CIAVBEGohAwsDQCADIQcgAiIAQRRqIgMoAgAiAg0AIABBEGohAyAAKAIQIgINAAsgB0EANgIADAILIAUgAEF+cTYCBCABIARqIAQ2AgAgASAEQQFyNgIEDAMLQQAhAAsgBkUNAAJAIAUoAhwiAkECdEGw1gBqIgMoAgAgBUYEQCADIAA2AgAgAA0BQYTUAEGE1AAoAgBBfiACd3E2AgAMAgsgBkEQQRQgBigCECAFRhtqIAA2AgAgAEUNAQsgACAGNgIYIAUoAhAiAgRAIAAgAjYCECACIAA2AhgLIAVBFGooAgAiAkUNACAAQRRqIAI2AgAgAiAANgIYCyABIARqIAQ2AgAgASAEQQFyNgIEIAFBlNQAKAIARw0AQYjUACAENgIADAELIARB/wFNBEAgBEF4cUGo1ABqIQACf0GA1AAoAgAiAkEBIARBA3Z0IgNxRQRAQYDUACACIANyNgIAIAAMAQsgACgCCAsiAiABNgIMIAAgATYCCCABIAA2AgwgASACNgIIDAELQR8hAiAEQf///wdNBEAgBEEmIARBCHZnIgBrdkEBcSAAQQF0a0E+aiECCyABIAI2AhwgAUIANwIQIAJBAnRBsNYAaiEAAkBBhNQAKAIAIgNBASACdCIHcUUEQCAAIAE2AgBBhNQAIAMgB3I2AgAgASAANgIYIAEgATYCCCABIAE2AgwMAQsgBEEZIAJBAXZrQQAgAkEfRxt0IQIgACgCACEAAkADQCAAIgMoAgRBeHEgBEYNASACQR12IQAgAkEBdCECIAMgAEEEcWpBEGoiBygCACIADQALIAcgATYCACABIAM2AhggASABNgIMIAEgATYCCAwBCyADKAIIIgAgATYCDCADIAE2AgggAUEANgIYIAEgAzYCDCABIAA2AggLQaDUAEGg1AAoAgBBAWsiAEF/IAAbNgIACwsHACAALQAoCwcAIAAtACoLBwAgAC0AKwsHACAALQApCwcAIAAvATQLBwAgAC0AMAtAAQR/IAAoAhghASAALwEuIQIgAC0AKCEDIAAoAjghBCAAEDcgACAENgI4IAAgAzoAKCAAIAI7AS4gACABNgIYC8X4AQIHfwN+IAEgAmohBAJAIAAiAygCDCIADQAgAygCBARAIAMgATYCBAsjAEEQayIJJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQFrDuwB7gEB6AECAwQFBgcICQoLDA0ODxAREucBE+YBFBXlARYX5AEYGRobHB0eHyDvAe0BIeMBIiMkJSYnKCkqK+IBLC0uLzAxMuEB4AEzNN8B3gE1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk/pAVBRUlPdAdwBVNsBVdoBVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHZAdgBxgHXAccB1gHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAQDqAQtBAAzUAQtBDgzTAQtBDQzSAQtBDwzRAQtBEAzQAQtBEQzPAQtBEgzOAQtBEwzNAQtBFAzMAQtBFQzLAQtBFgzKAQtBFwzJAQtBGAzIAQtBGQzHAQtBGgzGAQtBGwzFAQtBHAzEAQtBHQzDAQtBHgzCAQtBHwzBAQtBCAzAAQtBIAy/AQtBIgy+AQtBIQy9AQtBBwy8AQtBIwy7AQtBJAy6AQtBJQy5AQtBJgy4AQtBJwy3AQtBzgEMtgELQSgMtQELQSkMtAELQSoMswELQSsMsgELQc8BDLEBC0EtDLABC0EuDK8BC0EvDK4BC0EwDK0BC0ExDKwBC0EyDKsBC0EzDKoBC0HQAQypAQtBNAyoAQtBOAynAQtBDAymAQtBNQylAQtBNgykAQtBNwyjAQtBPQyiAQtBOQyhAQtB0QEMoAELQQsMnwELQT4MngELQToMnQELQQoMnAELQTsMmwELQTwMmgELQdIBDJkBC0HAAAyYAQtBPwyXAQtBwQAMlgELQQkMlQELQSwMlAELQcIADJMBC0HDAAySAQtBxAAMkQELQcUADJABC0HGAAyPAQtBxwAMjgELQcgADI0BC0HJAAyMAQtBygAMiwELQcsADIoBC0HMAAyJAQtBzQAMiAELQc4ADIcBC0HPAAyGAQtB0AAMhQELQdEADIQBC0HSAAyDAQtB1AAMggELQdMADIEBC0HVAAyAAQtB1gAMfwtB1wAMfgtB2AAMfQtB2QAMfAtB2gAMewtB2wAMegtB0wEMeQtB3AAMeAtB3QAMdwtBBgx2C0HeAAx1C0EFDHQLQd8ADHMLQQQMcgtB4AAMcQtB4QAMcAtB4gAMbwtB4wAMbgtBAwxtC0HkAAxsC0HlAAxrC0HmAAxqC0HoAAxpC0HnAAxoC0HpAAxnC0HqAAxmC0HrAAxlC0HsAAxkC0ECDGMLQe0ADGILQe4ADGELQe8ADGALQfAADF8LQfEADF4LQfIADF0LQfMADFwLQfQADFsLQfUADFoLQfYADFkLQfcADFgLQfgADFcLQfkADFYLQfoADFULQfsADFQLQfwADFMLQf0ADFILQf4ADFELQf8ADFALQYABDE8LQYEBDE4LQYIBDE0LQYMBDEwLQYQBDEsLQYUBDEoLQYYBDEkLQYcBDEgLQYgBDEcLQYkBDEYLQYoBDEULQYsBDEQLQYwBDEMLQY0BDEILQY4BDEELQY8BDEALQZABDD8LQZEBDD4LQZIBDD0LQZMBDDwLQZQBDDsLQZUBDDoLQZYBDDkLQZcBDDgLQZgBDDcLQZkBDDYLQZoBDDULQZsBDDQLQZwBDDMLQZ0BDDILQZ4BDDELQZ8BDDALQaABDC8LQaEBDC4LQaIBDC0LQaMBDCwLQaQBDCsLQaUBDCoLQaYBDCkLQacBDCgLQagBDCcLQakBDCYLQaoBDCULQasBDCQLQawBDCMLQa0BDCILQa4BDCELQa8BDCALQbABDB8LQbEBDB4LQbIBDB0LQbMBDBwLQbQBDBsLQbUBDBoLQbYBDBkLQbcBDBgLQbgBDBcLQQEMFgtBuQEMFQtBugEMFAtBuwEMEwtBvAEMEgtBvQEMEQtBvgEMEAtBvwEMDwtBwAEMDgtBwQEMDQtBwgEMDAtBwwEMCwtBxAEMCgtBxQEMCQtBxgEMCAtB1AEMBwtBxwEMBgtByAEMBQtByQEMBAtBygEMAwtBywEMAgtBzQEMAQtBzAELIQIDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCACDtQBAAECAwQFBgcICQoLDA0ODxARFBUWFxgZGhscHR4fICEjJCUnKCmIA4cDhQOEA/wC9QLuAusC6ALmAuMC4ALfAt0C2wLWAtUC1ALTAtICygLJAsgCxwLGAsUCxALDAr0CvAK6ArkCuAK3ArYCtQK0ArICsQKsAqoCqAKnAqYCpQKkAqMCogKhAqACnwKbApoCmQKYApcCkAKIAoQCgwKCAvkB9gH1AfQB8wHyAfEB8AHvAe0B6wHoAeMB4QHgAd8B3gHdAdwB2wHaAdkB2AHXAdYB1QHUAdIB0QHQAc8BzgHNAcwBywHKAckByAHHAcYBxQHEAcMBwgHBAcABvwG+Ab0BvAG7AboBuQG4AbcBtgG1AbQBswGyAbEBsAGvAa4BrQGsAasBqgGpAagBpwGmAaUBpAGjAaIBoQGgAZ8BngGdAZwBmwGaAZcBlgGRAZABjwGOAY0BjAGLAYoBiQGIAYUBhAGDAX59fHt6d3Z1LFFSU1RVVgsgASAERw1zQewBIQIMqQMLIAEgBEcNkAFB0QEhAgyoAwsgASAERw3pAUGEASECDKcDCyABIARHDfQBQfoAIQIMpgMLIAEgBEcNggJB9QAhAgylAwsgASAERw2JAkHzACECDKQDCyABIARHDYwCQfEAIQIMowMLIAEgBEcNHkEeIQIMogMLIAEgBEcNGUEYIQIMoQMLIAEgBEcNuAJBzQAhAgygAwsgASAERw3DAkHGACECDJ8DCyABIARHDcQCQcMAIQIMngMLIAEgBEcNygJBOCECDJ0DCyADLQAwQQFGDZUDDPICC0EAIQACQAJAAkAgAy0AKkUNACADLQArRQ0AIAMvATIiAkECcUUNAQwCCyADLwEyIgJBAXFFDQELQQEhACADLQAoQQFGDQAgAy8BNCIGQeQAa0HkAEkNACAGQcwBRg0AIAZBsAJGDQAgAkHAAHENAEEAIQAgAkGIBHFBgARGDQAgAkEocUEARyEACyADQQA7ATIgA0EAOgAxAkAgAEUEQCADQQA6ADEgAy0ALkEEcQ0BDJwDCyADQgA3AyALIANBADoAMSADQQE6ADYMSQtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAEUNSSAAQRVHDWMgA0EENgIcIAMgATYCFCADQb0aNgIQIANBFTYCDEEAIQIMmgMLIAEgBEYEQEEGIQIMmgMLIAEtAABBCkYNGQwBCyABIARGBEBBByECDJkDCwJAIAEtAABBCmsOBAIBAQABCyABQQFqIQFBECECDP4CCyADLQAuQYABcQ0YQQAhAiADQQA2AhwgAyABNgIUIANBqR82AhAgA0ECNgIMDJcDCyABQQFqIQEgA0Evai0AAEEBcQ0XQQAhAiADQQA2AhwgAyABNgIUIANBhB82AhAgA0EZNgIMDJYDCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMWg0ZQQghAgyVAwsgASAERwRAIANBCTYCCCADIAE2AgRBEiECDPsCC0EJIQIMlAMLIAMpAyBQDZwCDEQLIAEgBEYEQEELIQIMkwMLIAEtAABBCkcNFyABQQFqIQEMGAsgA0Evai0AAEEBcUUNGgwnC0EAIQACQCADKAI4IgJFDQAgAigCSCICRQ0AIAMgAhEAACEACyAADRoMQwtBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0bDCULQQAhAAJAIAMoAjgiAkUNACACKAJIIgJFDQAgAyACEQAAIQALIAANHAwzCyADQS9qLQAAQQFxRQ0dDCMLQQAhAAJAIAMoAjgiAkUNACACKAJMIgJFDQAgAyACEQAAIQALIAANHQxDC0EAIQACQCADKAI4IgJFDQAgAigCTCICRQ0AIAMgAhEAACEACyAADR4MIQsgASAERgRAQRMhAgyLAwsCQCABLQAAIgBBCmsOBCAkJAAjCyABQQFqIQEMIAtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0jDEMLIAEgBEYEQEEWIQIMiQMLIAEtAABB8D9qLQAAQQFHDSQM7QILAkADQCABLQAAQeA5ai0AACIAQQFHBEACQCAAQQJrDgIDACgLIAFBAWohAUEfIQIM8AILIAQgAUEBaiIBRw0AC0EYIQIMiAMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABQQFqIgEQMyIADSIMQgtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAA0kDCsLIAEgBEYEQEEcIQIMhgMLIANBCjYCCCADIAE2AgRBACEAAkAgAygCOCICRQ0AIAIoAkgiAkUNACADIAIRAAAhAAsgAA0mQSIhAgzrAgsgASAERwRAA0AgAS0AAEHgO2otAAAiAEEDRwRAIABBAWsOBRkbJ+wCJicLIAQgAUEBaiIBRw0AC0EbIQIMhQMLQRshAgyEAwsDQCABLQAAQeA9ai0AACIAQQNHBEAgAEEBaw4FEBIoFCcoCyAEIAFBAWoiAUcNAAtBHiECDIMDCyABIARHBEAgA0ELNgIIIAMgATYCBEEHIQIM6QILQR8hAgyCAwsgASAERgRAQSAhAgyCAwsCQCABLQAAQQ1rDhQvQEBAQEBAQEBAQEBAQEBAQEBAAEALQQAhAiADQQA2AhwgA0G3CzYCECADQQI2AgwgAyABQQFqNgIUDIEDCyADQS9qIQIDQCABIARGBEBBISECDIIDCwJAAkACQCABLQAAIgBBCWsOGAIAKioBKioqKioqKioqKioqKioqKioqAigLIAFBAWohASADQS9qLQAAQQFxRQ0LDBkLIAFBAWohAQwYCyABQQFqIQEgAi0AAEECcQ0AC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAyAAwsgAUEBaiEBC0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAADQEM0QILIANCADcDIAw8CyAAQRVGBEAgA0EkNgIcIAMgATYCFCADQYYaNgIQIANBFTYCDEEAIQIM/QILQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDPwCCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDSsgA0EHNgIcIAMgATYCFCADIAA2AgwM+wILIAMtAC5BwABxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCUCICRQ0AIAMgAhEAACEACyAARQ0rIABBFUYEQCADQQo2AhwgAyABNgIUIANB8Rg2AhAgA0EVNgIMQQAhAgz6AgtBACECIANBADYCHCADIAE2AhQgA0GLDDYCECADQRM2AgwM+QILQQAhAiADQQA2AhwgAyABNgIUIANBsRQ2AhAgA0ECNgIMDPgCC0EAIQIgA0EANgIcIAMgATYCFCADQYwUNgIQIANBGTYCDAz3AgtBACECIANBADYCHCADIAE2AhQgA0HRHDYCECADQRk2AgwM9gILIABBFUYNPUEAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAz1AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQ0oIANBDTYCHCADIAE2AhQgAyAANgIMDPQCCyAAQRVGDTpBACECIANBADYCHCADIAE2AhQgA0GiDzYCECADQSI2AgwM8wILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDIiAEUEQCABQQFqIQEMKAsgA0EONgIcIAMgADYCDCADIAFBAWo2AhQM8gILIABBFUYNN0EAIQIgA0EANgIcIAMgATYCFCADQaIPNgIQIANBIjYCDAzxAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMiIARQRAIAFBAWohAQwnCyADQQ82AhwgAyAANgIMIAMgAUEBajYCFAzwAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM7wILIABBFUYNM0EAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzuAgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMyIARQ0lIANBETYCHCADIAE2AhQgAyAANgIMDO0CCyAAQRVGDTBBACECIANBADYCHCADIAE2AhQgA0HODDYCECADQSM2AgwM7AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEMJQsgA0ESNgIcIAMgADYCDCADIAFBAWo2AhQM6wILIANBL2otAABBAXFFDQELQRUhAgzPAgtBACECIANBADYCHCADIAE2AhQgA0HoFjYCECADQRk2AgwM6AILIABBO0cNACABQQFqIQEMDAtBACECIANBADYCHCADIAE2AhQgA0GYFzYCECADQQI2AgwM5gILIABBFUYNKEEAIQIgA0EANgIcIAMgATYCFCADQc4MNgIQIANBIzYCDAzlAgsgA0EUNgIcIAMgATYCFCADIAA2AgwM5AILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDMiAEUEQCABQQFqIQEM3AILIANBFTYCHCADIAA2AgwgAyABQQFqNgIUDOMCCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNoCCyADQRc2AhwgAyAANgIMIAMgAUEBajYCFAziAgsgAEEVRg0jQQAhAiADQQA2AhwgAyABNgIUIANBzgw2AhAgA0EjNgIMDOECCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDB0LIANBGTYCHCADIAA2AgwgAyABQQFqNgIUDOACCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDNYCCyADQRo2AhwgAyAANgIMIAMgAUEBajYCFAzfAgsgAEEVRg0fQQAhAiADQQA2AhwgAyABNgIUIANBog82AhAgA0EiNgIMDN4CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUDN0CCyADKAIEIQBBACECIANBADYCBCADIAAgARAyIgBFBEAgAUEBaiEBDNICCyADQR02AhwgAyAANgIMIAMgAUEBajYCFAzcAgsgAEE7Rw0BIAFBAWohAQtBJCECDMACC0EAIQIgA0EANgIcIAMgATYCFCADQc4UNgIQIANBDDYCDAzZAgsgASAERwRAA0AgAS0AAEEgRw3xASAEIAFBAWoiAUcNAAtBLCECDNkCC0EsIQIM2AILIAEgBEYEQEE0IQIM2AILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0E0IQIM2QILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ2MAiADQTI2AhwgAyABNgIUIAMgADYCDEEAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQRAIAFBAWohAQyMAgsgA0EyNgIcIAMgADYCDCADIAFBAWo2AhRBACECDNcCCyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE5IQIMwAILIAMpAyAiC0KZs+bMmbPmzBlWDQEgAyALQgp+Igo3AyAgCiAArUL/AYMiC0J/hVYNASADIAogC3w3AyAgBCABQQFqIgFHDQALQcAAIQIM2AILIAMoAgQhACADQQA2AgQgAyAAIAFBAWoiARAwIgANFwzJAgtBwAAhAgzWAgsgASAERgRAQckAIQIM1gILAkADQAJAIAEtAABBCWsOGAACjwKPApMCjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CjwKPAo8CAI8CCyAEIAFBAWoiAUcNAAtByQAhAgzWAgsgAUEBaiEBIANBL2otAABBAXENjwIgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIM1QILIAEgBEcEQANAIAEtAAAiAEEgRwRAAkACQAJAIABByABrDgsAAc0BzQHNAc0BzQHNAc0BzQECzQELIAFBAWohAUHZACECDL8CCyABQQFqIQFB2gAhAgy+AgsgAUEBaiEBQdsAIQIMvQILIAQgAUEBaiIBRw0AC0HuACECDNUCC0HuACECDNQCCyADQQI6ACgMMAtBACECIANBADYCHCADQbcLNgIQIANBAjYCDCADIAFBAWo2AhQM0gILQQAhAgy3AgtBDSECDLYCC0ERIQIMtQILQRMhAgy0AgtBFCECDLMCC0EWIQIMsgILQRchAgyxAgtBGCECDLACC0EZIQIMrwILQRohAgyuAgtBGyECDK0CC0EcIQIMrAILQR0hAgyrAgtBHiECDKoCC0EgIQIMqQILQSEhAgyoAgtBIyECDKcCC0EnIQIMpgILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgy/AgsgA0EbNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMvgILIANBIDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDL0CCyADQRM2AhwgAyABNgIUIANBnhk2AhAgA0EVNgIMQQAhAgy8AgsgA0ELNgIcIAMgATYCFCADQZ4ZNgIQIANBFTYCDEEAIQIMuwILIANBEDYCHCADIAE2AhQgA0GeGTYCECADQRU2AgxBACECDLoCCyADQSA2AhwgAyABNgIUIANBjxs2AhAgA0EVNgIMQQAhAgy5AgsgA0ELNgIcIAMgATYCFCADQY8bNgIQIANBFTYCDEEAIQIMuAILIANBDDYCHCADIAE2AhQgA0GPGzYCECADQRU2AgxBACECDLcCC0EAIQIgA0EANgIcIAMgATYCFCADQa8ONgIQIANBEjYCDAy2AgsCQANAAkAgAS0AAEEKaw4EAAICAAILIAQgAUEBaiIBRw0AC0HsASECDLYCCwJAAkAgAy0ANkEBRw0AQQAhAAJAIAMoAjgiAkUNACACKAJYIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB6wE2AhwgAyABNgIUIANB4hg2AhAgA0EVNgIMQQAhAgy3AgtBzAEhAgycAgsgA0EANgIcIAMgATYCFCADQfELNgIQIANBHzYCDEEAIQIMtQILAkACQCADLQAoQQFrDgIEAQALQcsBIQIMmwILQcQBIQIMmgILIANBAjoAMUEAIQACQCADKAI4IgJFDQAgAigCACICRQ0AIAMgAhEAACEACyAARQRAQc0BIQIMmgILIABBFUcEQCADQQA2AhwgAyABNgIUIANBrAw2AhAgA0EQNgIMQQAhAgy0AgsgA0HqATYCHCADIAE2AhQgA0GHGTYCECADQRU2AgxBACECDLMCCyABIARGBEBB6QEhAgyzAgsgAS0AAEHIAEYNASADQQE6ACgLQbYBIQIMlwILQcoBIQIMlgILIAEgBEcEQCADQQw2AgggAyABNgIEQckBIQIMlgILQegBIQIMrwILIAEgBEYEQEHnASECDK8CCyABLQAAQcgARw0EIAFBAWohAUHIASECDJQCCyABIARGBEBB5gEhAgyuAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQcYBIQIMlAILIAFBAWohAUHHASECDJMCC0HlASECIAEgBEYNrAIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB99MAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMrQILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgBFBEBB1AEhAgyTAgsgA0HkATYCHCADIAE2AhQgAyAANgIMQQAhAgysAgtB4wEhAiABIARGDasCIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQfXTAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADKwCCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAtIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB0B42AhAgA0EINgIMDKkCC0HFASECDI4CCyADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDKcCC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ1lIABBFUcEQCADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgynAgsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDKYCC0HhASECIAQgASIARg2lAiAEIAFrIAMoAgAiAWohBSAAIAFrQQRqIQYCQANAIAAtAAAgAUHw0wBqLQAARw0BIAFBBEYNAyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBTYCAAymAgsgA0EANgIcIAMgADYCFCADQYQ3NgIQIANBCDYCDCADQQA2AgBBACECDKUCCyABIARHBEAgA0ENNgIIIAMgATYCBEHCASECDIsCC0HgASECDKQCCyADQQA2AgAgBkEBaiEBC0HDASECDIgCCyABIARGBEBB3wEhAgyiAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBwQEhAgyIAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYgCIANB3gE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAEgBEYEQEHdASECDKECCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYkCIANB3AE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILQcABIQIMhgILIAEgBEYEQEHbASECDKACC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDQIgA0HYATYCHCADIAE2AhQgAyAANgIMQQAhAgyiAgsgAygCBCEAIANBADYCBCADIAAgARAuIgBFDYsCIANB2QE2AhwgAyABNgIUIAMgADYCDEEAIQIMoQILIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ2JAiADQdoBNgIcIAMgATYCFCADIAA2AgwMoAILQb8BIQIMhQILQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBnA02AhAgA0EhNgIMQQAhAgygAgtBvgEhAgyFAgsgA0HXATYCHCADIAE2AhQgA0HWGTYCECADQRU2AgxBACECDJ4CCyABIARGBEBB1wEhAgyeAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANB6xA2AhAgA0EJNgIMQQAhAgyeAgtBvQEhAgyDAgsgASAERgRAQdYBIQIMnQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDAyeAgsgA0EANgIcIAMgATYCFCADQYAdNgIQIANBDTYCDEEAIQIMnQILQbwBIQIMggILIAEgBEYEQEHVASECDJwCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgwMnQILIANBADYCHCADIAE2AhQgA0GAHTYCECADQQ02AgxBACECDJwCC0G7ASECDIECCyABIARGBEBB1AEhAgybAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMDJwCCyADQQA2AhwgAyABNgIUIANBgB02AhAgA0ENNgIMQQAhAgybAgtBugEhAgyAAgsgASAERgRAQdMBIQIMmgILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUG5ASECDIECCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GFCzYCECADQQ02AgxBACECDJoCCyADQQA2AhwgAyABNgIUIANBhQs2AhAgA0ENNgIMQQAhAgyZAgsgASAERwRAIANBDjYCCCADIAE2AgRBASECDP8BC0HSASECDJgCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB0QEhAgyZAgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFBEAgAUEBaiEBDAQLIANB0AE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMmAILIAMoAgQhACADQQA2AgQgAyAAIAEQLCIADQEgAUEBagshAUG3ASECDPwBCyADQc8BNgIcIAMgADYCDCADIAFBAWo2AhRBACECDJUCC0G4ASECDPoBCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQc8bNgIQIANBGTYCDEEAIQIMkwILIAEgBEYEQEHPASECDJMCCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsgAEUNlgEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBvRk2AhAgA0EVNgIMQQAhAgySAgsgA0EANgIcIAMgATYCFCADQfgMNgIQIANBGzYCDEEAIQIMkQILIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDJACCyABIARHBEAgA0EMNgIIIAMgATYCBEG1ASECDPYBC0HOASECDI8CCyABIARGBEBBzQEhAgyPAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQQFqIQFB8QAhAgyEAgsgAUEBaiEBQfIAIQIMgwILIAFBAWohAUH3ACECDIICCyABQQFqIQFB+wAhAgyBAgsgAUEBaiEBQfwAIQIMgAILIAFBAWohAUH/ACECDP8BCyABQQFqIQFBgAEhAgz+AQsgAUEBaiEBQYMBIQIM/QELIAFBAWohAUGMASECDPwBCyABQQFqIQFBjQEhAgz7AQsgAUEBaiEBQY4BIQIM+gELIAFBAWohAUGbASECDPkBCyABQQFqIQFBnAEhAgz4AQsgAUEBaiEBQaIBIQIM9wELIAFBAWohAUGqASECDPYBCyABQQFqIQFBrQEhAgz1AQsgAUEBaiEBQbQBIQIM9AELIAEgBEYEQEHMASECDI4CCyABLQAAQc4ARw1IIAFBAWohAUGzASECDPMBCyABIARGBEBBywEhAgyNAgsCQAJAAkAgAS0AAEHCAGsOEgBKSkpKSkpKSkoBSkpKSkpKAkoLIAFBAWohAUGuASECDPQBCyABQQFqIQFBsQEhAgzzAQsgAUEBaiEBQbIBIQIM8gELQcoBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQdqIQYCQANAIAEtAAAgAEHo0wBqLQAARw1FIABBB0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEbDEULIAEgBEYEQEHJASECDIsCCwJAAkAgAS0AAEHJAGsOBwBHR0dHRwFHCyABQQFqIQFBrwEhAgzxAQsgAUEBaiEBQbABIQIM8AELQcgBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm0wBqLQAARw1DIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEPDEMLQccBIQIgASAERg2IAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk0wBqLQAARw1CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyJAgsgA0EANgIAIAZBAWohAUEgDEILQcYBIQIgASAERg2HAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw1BIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyIAgsgA0EANgIAIAZBAWohAUESDEELIAEgBEYEQEHFASECDIcCCwJAAkAgAS0AAEHFAGsODgBDQ0NDQ0NDQ0NDQ0MBQwsgAUEBaiEBQasBIQIM7QELIAFBAWohAUGsASECDOwBC0HEASECIAEgBEYNhQIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB3tMAai0AAEcNPyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhgILIANBADYCACAGQQFqIQFBBww/C0HDASECIAEgBEYNhAIgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABB2NMAai0AAEcNPiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMhQILIANBADYCACAGQQFqIQFBKAw+CyABIARGBEBBwgEhAgyEAgsCQAJAAkAgAS0AAEHFAGsOEQBBQUFBQUFBQUEBQUFBQUECQQsgAUEBaiEBQacBIQIM6wELIAFBAWohAUGoASECDOoBCyABQQFqIQFBqQEhAgzpAQtBwQEhAiABIARGDYICIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQdHTAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIMCCyADQQA2AgAgBkEBaiEBQRoMPAtBwAEhAiABIARGDYECIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQc3TAGotAABHDTsgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADIICCyADQQA2AgAgBkEBaiEBQSEMOwsgASAERgRAQb8BIQIMgQILAkACQCABLQAAQcEAaw4UAD09PT09PT09PT09PT09PT09PQE9CyABQQFqIQFBowEhAgznAQsgAUEBaiEBQaYBIQIM5gELIAEgBEYEQEG+ASECDIACCwJAAkAgAS0AAEHVAGsOCwA8PDw8PDw8PDwBPAsgAUEBaiEBQaQBIQIM5gELIAFBAWohAUGlASECDOUBC0G9ASECIAEgBEYN/gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNOCAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/wELIANBADYCACAGQQFqIQFBKgw4CyABIARGBEBBvAEhAgz+AQsgAS0AAEHQAEcNOCABQQFqIQFBJQw3C0G7ASECIAEgBEYN/AEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBwdMAai0AAEcNNiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM/QELIANBADYCACAGQQFqIQFBDgw2CyABIARGBEBBugEhAgz8AQsgAS0AAEHFAEcNNiABQQFqIQFBoQEhAgzhAQsgASAERgRAQbkBIQIM+wELAkACQAJAAkAgAS0AAEHCAGsODwABAjk5OTk5OTk5OTk5AzkLIAFBAWohAUGdASECDOMBCyABQQFqIQFBngEhAgziAQsgAUEBaiEBQZ8BIQIM4QELIAFBAWohAUGgASECDOABC0G4ASECIAEgBEYN+QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtMAai0AAEcNMyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+gELIANBADYCACAGQQFqIQFBFAwzC0G3ASECIAEgBEYN+AEgAygCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBudMAai0AAEcNMiAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+QELIANBADYCACAGQQFqIQFBKwwyC0G2ASECIAEgBEYN9wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBttMAai0AAEcNMSAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM+AELIANBADYCACAGQQFqIQFBLAwxC0G1ASECIAEgBEYN9gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB4dMAai0AAEcNMCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9wELIANBADYCACAGQQFqIQFBEQwwC0G0ASECIAEgBEYN9QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBstMAai0AAEcNLyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM9gELIANBADYCACAGQQFqIQFBLgwvCyABIARGBEBBswEhAgz1AQsCQAJAAkACQAJAIAEtAABBwQBrDhUANDQ0NDQ0NDQ0NAE0NAI0NAM0NAQ0CyABQQFqIQFBkQEhAgzeAQsgAUEBaiEBQZIBIQIM3QELIAFBAWohAUGTASECDNwBCyABQQFqIQFBmAEhAgzbAQsgAUEBaiEBQZoBIQIM2gELIAEgBEYEQEGyASECDPQBCwJAAkAgAS0AAEHSAGsOAwAwATALIAFBAWohAUGZASECDNoBCyABQQFqIQFBBAwtC0GxASECIAEgBEYN8gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBsNMAai0AAEcNLCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM8wELIANBADYCACAGQQFqIQFBHQwsCyABIARGBEBBsAEhAgzyAQsCQAJAIAEtAABByQBrDgcBLi4uLi4ALgsgAUEBaiEBQZcBIQIM2AELIAFBAWohAUEiDCsLIAEgBEYEQEGvASECDPEBCyABLQAAQdAARw0rIAFBAWohAUGWASECDNYBCyABIARGBEBBrgEhAgzwAQsCQAJAIAEtAABBxgBrDgsALCwsLCwsLCwsASwLIAFBAWohAUGUASECDNYBCyABQQFqIQFBlQEhAgzVAQtBrQEhAiABIARGDe4BIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQazTAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO8BCyADQQA2AgAgBkEBaiEBQQ0MKAtBrAEhAiABIARGDe0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQeHTAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO4BCyADQQA2AgAgBkEBaiEBQQwMJwtBqwEhAiABIARGDewBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQarTAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADO0BCyADQQA2AgAgBkEBaiEBQQMMJgtBqgEhAiABIARGDesBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQajTAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOwBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQakBIQIM6wELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBjwEhAgzRAQsgAUEBaiEBQZABIQIM0AELQagBIQIgASAERg3pASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm0wBqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzqAQsgA0EANgIAIAZBAWohAUEnDCMLQacBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk0wBqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEcDCILQaYBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGe0wBqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEGDCELQaUBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGZ0wBqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGkASECDOYBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQYQBIQIMzgELIAFBAWohAUGFASECDM0BCyABQQFqIQFBigEhAgzMAQsgAUEBaiEBQYsBIQIMywELQaMBIQIgASAERg3kASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGX0wBqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzlAQsgA0EANgIAIAZBAWohAUELDB4LIAEgBEYEQEGiASECDOQBCwJAAkAgAS0AAEHBAGsOAwAgASALIAFBAWohAUGGASECDMoBCyABQQFqIQFBiQEhAgzJAQsgASAERgRAQaEBIQIM4wELAkACQCABLQAAQcEAaw4PAB8fHx8fHx8fHx8fHx8BHwsgAUEBaiEBQYcBIQIMyQELIAFBAWohAUGIASECDMgBCyABIARGBEBBoAEhAgziAQsgAS0AAEHMAEcNHCABQQFqIQFBCgwbC0GfASECIAEgBEYN4AEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBkdMAai0AAEcNGiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4QELIANBADYCACAGQQFqIQFBHgwaC0GeASECIAEgBEYN3wEgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBitMAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4AELIANBADYCACAGQQFqIQFBFQwZC0GdASECIAEgBEYN3gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBh9MAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3wELIANBADYCACAGQQFqIQFBFwwYC0GcASECIAEgBEYN3QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBgdMAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3gELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBmwEhAgzdAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYEBIQIMwwELIAFBAWohAUGCASECDMIBC0GaASECIAEgBEYN2wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5tMAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM3AELIANBADYCACAGQQFqIQFBCQwVC0GZASECIAEgBEYN2gEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB5NMAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2wELIANBADYCACAGQQFqIQFBHwwUC0GYASECIAEgBEYN2QEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB/tIAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM2gELIANBADYCACAGQQFqIQFBAgwTC0GXASECIAEgBEYN2AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQfzSAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyABIARGBEBBlgEhAgzYAQtBASABLQAAQd8ARw0RGiABQQFqIQFB/QAhAgy9AQsgA0EANgIAIAZBAWohAUH+ACECDLwBC0GVASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBxNMAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBKQwPC0GUASECIAEgBEYN1AEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB+NIAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1QELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBkwEhAgzUAQsgAS0AAEHFAEcNDiABQQFqIQFB+gAhAgy5AQsgASAERgRAQZIBIQIM0wELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFB+AAhAgy5AQsgAUEBaiEBQfkAIQIMuAELQZEBIQIgASAERg3RASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHz0gBqLQAARw0LIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzSAQsgA0EANgIAIAZBAWohAUEjDAsLQZABIQIgASAERg3QASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHw0gBqLQAARw0KIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzRAQsgA0EANgIAIAZBAWohAUEADAoLIAEgBEYEQEGPASECDNABCwJAAkAgAS0AAEHIAGsOCAAMDAwMDAwBDAsgAUEBaiEBQfMAIQIMtgELIAFBAWohAUH2ACECDLUBCyABIARGBEBBjgEhAgzPAQsCQAJAIAEtAABBzgBrDgMACwELCyABQQFqIQFB9AAhAgy1AQsgAUEBaiEBQfUAIQIMtAELIAEgBEYEQEGNASECDM4BCyABLQAAQdkARw0IIAFBAWohAUEIDAcLQYwBIQIgASAERg3MASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHs0gBqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzNAQsgA0EANgIAIAZBAWohAUEFDAYLQYsBIQIgASAERg3LASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHm0gBqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzMAQsgA0EANgIAIAZBAWohAUEWDAULQYoBIQIgASAERg3KASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHh0wBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzLAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGJASECDMoBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUHvACECDLABCyABQQFqIQFB8AAhAgyvAQtBiAEhAiABIARGDcgBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQeDSAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMkBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGHASECDMcBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC0iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB6R42AhAgA0EGNgIMDMQBC0HuACECDKkBCyADQYYBNgIcIAMgATYCFCADIAA2AgxBACECDMIBC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANB1A42AhAgA0EgNgIMQQAhAgzBAQtB7QAhAgymAQsgA0GFATYCHCADIAE2AhQgA0HXGjYCECADQRU2AgxBACECDL8BCyABIARGBEBBhQEhAgy/AQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GGHjYCECADQQY2AgxBACECDL8BC0ECIQIMpAELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GEASECDL0BCyABIARGBEBBgwEhAgy9AQsCQCABLQAAQQlrDgRAAABAAAtB6wAhAgyiAQsgAy0AKUEFRgRAQewAIQIMogELQeoAIQIMoQELIAEgBEYEQEGCASECDLsBCyADQQ82AgggAyABNgIEDAoLIAEgBEYEQEGBASECDLoBCwJAIAEtAABBCWsOBD0AAD0AC0HpACECDJ8BCyABIARHBEAgA0EPNgIIIAMgATYCBEHnACECDJ8BC0GAASECDLgBCwJAIAEgBEcEQANAIAEtAABB4M4Aai0AACIAQQNHBEACQCAAQQFrDgI/AAQLQeYAIQIMoQELIAQgAUEBaiIBRw0AC0H+ACECDLkBC0H+ACECDLgBCyADQQA2AhwgAyABNgIUIANBxh82AhAgA0EHNgIMQQAhAgy3AQsgASAERgRAQf8AIQIMtwELAkACQAJAIAEtAABB4NAAai0AAEEBaw4DPAIAAQtB6AAhAgyeAQsgA0EANgIcIAMgATYCFCADQYYSNgIQIANBBzYCDEEAIQIMtwELQeAAIQIMnAELIAEgBEcEQCABQQFqIQFB5QAhAgycAQtB/QAhAgy1AQsgBCABIgBGBEBB/AAhAgy1AQsgAC0AACIBQS9GBEAgAEEBaiEBQeQAIQIMmwELIAFBCWsiAkEXSw0BIAAhAUEBIAJ0QZuAgARxDTcMAQsgBCABIgBGBEBB+wAhAgy0AQsgAC0AAEEvRw0AIABBAWohAQwDC0EAIQIgA0EANgIcIAMgADYCFCADQcYfNgIQIANBBzYCDAyyAQsCQAJAAkACQAJAA0AgAS0AAEHgzABqLQAAIgBBBUcEQAJAAkAgAEEBaw4IPQUGBwgABAEIC0HhACECDJ8BCyABQQFqIQFB4wAhAgyeAQsgBCABQQFqIgFHDQALQfoAIQIMtgELIAFBAWoMFAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgy0AQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyzAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDR4gA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyyAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMsQELIAEgBEYEQEH5ACECDLEBCwJAIAEtAABB4MwAai0AAEEBaw4INAQFBgAIAgMHCyABQQFqIQELQQMhAgyVAQsgAUEBagwNC0EAIQIgA0EANgIcIANBoxI2AhAgA0EHNgIMIAMgAUEBajYCFAytAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgysAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDRYgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgA0EANgIcIAMgATYCFCADQcsPNgIQIANBBzYCDEEAIQIMqQELQeIAIQIMjgELIAEgBEYEQEH4ACECDKgBCyABQQFqDAILIAEgBEYEQEH3ACECDKcBCyABQQFqDAELIAEgBEYNASABQQFqCyEBQQQhAgyKAQtB9gAhAgyjAQsDQCABLQAAQeDKAGotAAAiAEECRwRAIABBAUcEQEHfACECDIsBCwwnCyAEIAFBAWoiAUcNAAtB9QAhAgyiAQsgASAERgRAQfQAIQIMogELAkAgAS0AAEEJaw43JQMGJQQGBgYGBgYGBgYGBgYGBgYGBgYFBgYCBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAYLIAFBAWoLIQFBBSECDIYBCyABQQFqDAYLIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMngELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMnQELIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ0IIANB8AA2AhwgAyABNgIUIAMgADYCDEEAIQIMnAELIANBADYCHCADIAE2AhQgA0G8EzYCECADQQc2AgxBACECDJsBCwJAAkACQAJAA0AgAS0AAEHgyABqLQAAIgBBBUcEQAJAIABBAWsOBiQDBAUGAAYLQd4AIQIMhgELIAQgAUEBaiIBRw0AC0HzACECDJ4BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDJ0BCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDJwBCyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNByADQfAANgIcIAMgATYCFCADIAA2AgxBACECDJsBCyADQQA2AhwgAyABNgIUIANB3Ag2AhAgA0EHNgIMQQAhAgyaAQsgASAERg0BIAFBAWoLIQFBBiECDH4LQfIAIQIMlwELAkACQAJAAkADQCABLQAAQeDGAGotAAAiAEEFRwRAIABBAWsOBB8CAwQFCyAEIAFBAWoiAUcNAAtB8QAhAgyaAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyZAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyYAQsgAygCBCEAIANBADYCBCADIAAgARArIgBFDQMgA0HwADYCHCADIAE2AhQgAyAANgIMQQAhAgyXAQsgA0EANgIcIAMgATYCFCADQbQKNgIQIANBBzYCDEEAIQIMlgELQc4AIQIMewtB0AAhAgx6C0HdACECDHkLIAEgBEYEQEHwACECDJMBCwJAIAEtAABBCWsOBBYAABYACyABQQFqIQFB3AAhAgx4CyABIARGBEBB7wAhAgySAQsCQCABLQAAQQlrDgQVAAAVAAtBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUEQEHTASECDHgLIABBFUcEQCADQQA2AhwgAyABNgIUIANBwQ02AhAgA0EaNgIMQQAhAgySAQsgA0HuADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDJEBC0HtACECIAEgBEYNkAEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABB18YAai0AAEcNBCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkQELIANBADYCACAGQQFqIQEgAy0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACECIANBADYCHCADIAE2AhQgA0HlCTYCECADQQg2AgwMkAELQewAIQIgASAERg2PASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHUxgBqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyQAQsgA0EANgIAIAZBAWohASADLQApQSFGDQMgA0EANgIcIAMgATYCFCADQYkKNgIQIANBCDYCDEEAIQIMjwELQesAIQIgASAERg2OASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEHQxgBqLQAARw0CIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyPAQsgA0EANgIAIAZBAWohASADLQApIgBBI0kNAiAAQS5GDQIgA0EANgIcIAMgATYCFCADQcEJNgIQIANBCDYCDEEAIQIMjgELIANBADYCAAtBACECIANBADYCHCADIAE2AhQgA0GENzYCECADQQg2AgwMjAELQdgAIQIMcQsgASAERwRAIANBDTYCCCADIAE2AgRB1wAhAgxxC0HqACECDIoBCyABIARGBEBB6QAhAgyKAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1gAhAgxwCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdCADQegANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyABIARGBEBB5wAhAgyJAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLiIARQ11IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMiQELQdUAIQIMbgsgASAERgRAQeUAIQIMiAELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDIoBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdyADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIkBCyADKAIEIQAgA0EANgIEIAMgACABEC4iAEUNdSADQeQANgIcIAMgATYCFCADIAA2AgwMiAELQdMAIQIMbQsgAy0AKUEiRg2AAUHSACECDGwLQQAhAAJAIAMoAjgiAkUNACACKAI8IgJFDQAgAyACEQAAIQALIABFBEBB1AAhAgxsCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQZwNNgIQIANBITYCDEEAIQIMhgELIANB4QA2AhwgAyABNgIUIANB1hk2AhAgA0EVNgIMQQAhAgyFAQsgASAERgRAQeAAIQIMhQELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HRACECDGwLIANBADYCHCADIAE2AhQgA0GIETYCECADQQk2AgxBACECDIUBCyADQQA2AhwgAyABNgIUIANBiBE2AhAgA0EJNgIMQQAhAgyEAQsgASAERgRAQd8AIQIMhAELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBiBE2AhAgA0ECNgIMQQAhAgyDAQsgASAERgRAQd0AIQIMgwELIAEtAAAiAkENRgRAIAFBAWohAUHPACECDGkLIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyCAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0G1LDYCECADQQc2AgwMgAELIAEgBEYEQEHbACECDIABCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc0AIQIMZAsgASAERgRAQdoAIQIMfgsgAS0AAEEJaw4EAAEBAAELQQAhAiADQQA2AhwgA0HsETYCECADQQc2AgwgAyABQQFqNgIUDHwLIANBgBI7ASpBACEAAkAgAygCOCICRQ0AIAIoAjAiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HZADYCHCADIAE2AhQgA0HwGTYCECADQRU2AgxBACECDHsLQcwAIQIMYAsgA0EANgIcIAMgATYCFCADQcENNgIQIANBGjYCDEEAIQIMeQsgASAERgRAQdkAIQIMeQsgAS0AAEEgRw06IAFBAWohASADLQAuQQFxDTogA0EANgIcIAMgATYCFCADQa0bNgIQIANBHjYCDEEAIQIMeAsgASAERgRAQdgAIQIMeAsCQAJAAkACQAJAIAEtAAAiAEEKaw4EAgMDAAELIAFBAWohAUErIQIMYQsgAEE6Rw0BIANBADYCHCADIAE2AhQgA0G5ETYCECADQQo2AgxBACECDHoLIAFBAWohASADQS9qLQAAQQFxRQ1tIAMtADJBgAFxRQRAIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsCQAJAIAAOFkpJSAEBAQEBAQEBAQEBAQEBAQEBAQABCyADQSk2AhwgAyABNgIUIANBshg2AhAgA0EVNgIMQQAhAgx7CyADQQA2AhwgAyABNgIUIANB3Qs2AhAgA0ERNgIMQQAhAgx6C0EAIQACQCADKAI4IgJFDQAgAigCVCICRQ0AIAMgAhEAACEACyAARQ1VIABBFUcNASADQQU2AhwgAyABNgIUIANBhho2AhAgA0EVNgIMQQAhAgx5C0HKACECDF4LQQAhAiADQQA2AhwgAyABNgIUIANB4g02AhAgA0EUNgIMDHcLIAMgAy8BMkGAAXI7ATIMOAsgASAERwRAIANBEDYCCCADIAE2AgRByQAhAgxcC0HXACECDHULIAEgBEYEQEHWACECDHULAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAPT09PT09PT09PT09AT09PQIDPQsgAUEBaiEBQcUAIQIMXQsgAUEBaiEBQcYAIQIMXAsgAUEBaiEBQccAIQIMWwsgAUEBaiEBQcgAIQIMWgtB1QAhAiAEIAEiAEYNcyAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcDQCABQcDGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQhBBCABQQVGDQoaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADHMLQdQAIQIgBCABIgBGDXIgBCABayADKAIAIgFqIQYgACABa0EPaiEHA0AgAUGwxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0HQQMgAUEPRg0JGiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxyC0HTACECIAQgASIARg1xIAQgAWsgAygCACIBaiEGIAAgAWtBDmohBwNAIAFBksYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNBiABQQ5GDQcgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMcQtB0gAhAiAEIAEiAEYNcCAEIAFrIAMoAgAiAWohBSAAIAFrQQFqIQYDQCABQZDGAGotAAAgAC0AACIHQSByIAcgB0HBAGtB/wFxQRpJG0H/AXFHDQUgAUEBRg0CIAFBAWohASAEIABBAWoiAEcNAAsgAyAFNgIADHALIAEgBEYEQEHRACECDHALAkACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcUHuAGsOBwA2NjY2NgE2CyABQQFqIQFBwgAhAgxWCyABQQFqIQFBwwAhAgxVCyADQQA2AgAgBkEBaiEBQcQAIQIMVAtB0AAhAiAEIAEiAEYNbSAEIAFrIAMoAgAiAWohBiAAIAFrQQlqIQcDQCABQYbGAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQJBAiABQQlGDQQaIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADG0LQc8AIQIgBCABIgBGDWwgBCABayADKAIAIgFqIQYgACABa0EFaiEHA0AgAUGAxgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYNAiABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxsCyAAIQEgA0EANgIADDALQQELOgAsIANBADYCACAHQQFqIQELQSwhAgxOCwJAA0AgAS0AAEGAxABqLQAAQQFHDQEgBCABQQFqIgFHDQALQc0AIQIMaAtBwQAhAgxNCyABIARGBEBBzAAhAgxnCyABLQAAQTpGBEAgAygCBCEAIANBADYCBCADIAAgARAvIgBFDTAgA0HLADYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxnCyADQQA2AhwgAyABNgIUIANBuRE2AhAgA0EKNgIMQQAhAgxmCwJAAkAgAy0ALEECaw4CAAEkCyADQTNqLQAAQQJxRQ0jIAMtAC5BAnENIyADQQA2AhwgAyABNgIUIANB1RM2AhAgA0ELNgIMQQAhAgxmCyADLQAyQSBxRQ0iIAMtAC5BAnENIiADQQA2AhwgAyABNgIUIANB7BI2AhAgA0EPNgIMQQAhAgxlC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQRAQcAAIQIMSwsgAEEVRwRAIANBADYCHCADIAE2AhQgA0H4DjYCECADQRw2AgxBACECDGULIANBygA2AhwgAyABNgIUIANB8Bo2AhAgA0EVNgIMQQAhAgxkCyABIARHBEADQCABLQAAQfA/ai0AAEEBRw0XIAQgAUEBaiIBRw0AC0HEACECDGQLQcQAIQIMYwsgASAERwRAA0ACQCABLQAAIgBBIHIgACAAQcEAa0H/AXFBGkkbQf8BcSIAQQlGDQAgAEEgRg0AAkACQAJAAkAgAEHjAGsOEwADAwMDAwMDAQMDAwMDAwMDAwIDCyABQQFqIQFBNSECDE4LIAFBAWohAUE2IQIMTQsgAUEBaiEBQTchAgxMCwwVCyAEIAFBAWoiAUcNAAtBPCECDGMLQTwhAgxiCyABIARGBEBByAAhAgxiCyADQRE2AgggAyABNgIEAkACQAJAAkACQCADLQAsQQFrDgQUAAECCQsgAy0AMkEgcQ0DQdEBIQIMSwsCQCADLwEyIgBBCHFFDQAgAy0AKEEBRw0AIAMtAC5BCHFFDQILIAMgAEH3+wNxQYAEcjsBMgwLCyADIAMvATJBEHI7ATIMBAsgA0EANgIEIAMgASABEDAiAARAIANBwQA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMYwsgAUEBaiEBDFILIANBADYCHCADIAE2AhQgA0GjEzYCECADQQQ2AgxBACECDGELQccAIQIgASAERg1gIAMoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEHwwwBqLQAAIAEtAABBIHJHDQEgAEEGRg1GIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADGELIANBADYCAAwFCwJAIAEgBEcEQANAIAEtAABB8MEAai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBxQAhAgxhC0HFACECDGALCyADQQA6ACwMAQtBCyECDEMLQT4hAgxCCwJAAkADQCABLQAAIgBBIEcEQAJAIABBCmsOBAMFBQMACyAAQSxGDQMMBAsgBCABQQFqIgFHDQALQcYAIQIMXQsgA0EIOgAsDA4LIAMtAChBAUcNAiADLQAuQQhxDQIgAygCBCEAIANBADYCBCADIAAgARAwIgAEQCADQcIANgIcIAMgADYCDCADIAFBAWo2AhRBACECDFwLIAFBAWohAQxKC0E6IQIMQAsCQANAIAEtAAAiAEEgRyAAQQlHcQ0BIAQgAUEBaiIBRw0AC0HDACECDFoLC0E7IQIMPgsCQAJAIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBAMEBAMECyAEIAFBAWoiAUcNAAtBPyECDFoLQT8hAgxZCyADIAMvATJBIHI7ATIMCgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFDUggA0E+NgIcIAMgATYCFCADIAA2AgxBACECDFcLAkAgASAERwRAA0AgAS0AAEHwwQBqLQAAIgBBAUcEQCAAQQJGDQMMDAsgBCABQQFqIgFHDQALQTchAgxYC0E3IQIMVwsgAUEBaiEBDAQLQTshAiAEIAEiAEYNVSAEIAFrIAMoAgAiAWohBiAAIAFrQQVqIQcCQANAIAFBwMYAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQVGBEBBByEBDDsLIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFYLIANBADYCACAAIQEMBQtBOiECIAQgASIARg1UIAQgAWsgAygCACIBaiEGIAAgAWtBCGohBwJAA0AgAUHkP2otAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAUEIRgRAQQUhAQw6CyABQQFqIQEgBCAAQQFqIgBHDQALIAMgBjYCAAxVCyADQQA2AgAgACEBDAQLQTkhAiAEIAEiAEYNUyAEIAFrIAMoAgAiAWohBiAAIAFrQQNqIQcCQANAIAFB4D9qLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBA0YEQEEGIQEMOQsgAUEBaiEBIAQgAEEBaiIARw0ACyADIAY2AgAMVAsgA0EANgIAIAAhAQwDCwJAA0AgAS0AACIAQSBHBEAgAEEKaw4EBwQEBwILIAQgAUEBaiIBRw0AC0E4IQIMUwsgAEEsRw0BIAFBAWohAEEBIQECQAJAAkACQAJAIAMtACxBBWsOBAMBAgQACyAAIQEMBAtBAiEBDAELQQQhAQsgA0EBOgAsIAMgAy8BMiABcjsBMiAAIQEMAQsgAyADLwEyQQhyOwEyIAAhAQtBPSECDDcLIANBADoALAtBOCECDDULIAEgBEYEQEE2IQIMTwsCQAJAAkACQAJAIAEtAABBCmsOBAACAgECCyADKAIEIQAgA0EANgIEIAMgACABEDAiAEUNAiADQTM2AhwgAyABNgIUIAMgADYCDEEAIQIMUgsgAygCBCEAIANBADYCBCADIAAgARAwIgBFBEAgAUEBaiEBDAYLIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgxRCyADLQAuQQFxBEBB0AEhAgw3CyADKAIEIQAgA0EANgIEIAMgACABEDAiAA0BDEMLQTMhAgw1CyADQTU2AhwgAyABNgIUIAMgADYCDEEAIQIMTgtBNCECDDMLIANBL2otAABBAXENACADQQA2AhwgAyABNgIUIANB8RU2AhAgA0EZNgIMQQAhAgxMC0EyIQIMMQsgASAERgRAQTIhAgxLCwJAIAEtAABBCkYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZgWNgIQIANBAzYCDEEAIQIMSwtBMSECDDALIAEgBEYEQEExIQIMSgsgAS0AACIAQQlHIABBIEdxDQEgAy0ALEEIRw0AIANBADoALAtBPCECDC4LQQEhAgJAAkACQAJAIAMtACxBBWsOBAMBAgAKCyADIAMvATJBCHI7ATIMCQtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgwGCyABIARGBEBBMCECDEcLIAEtAABBCkYEQCABQQFqIQEMAQsgAy0ALkEBcQ0AIANBADYCHCADIAE2AhQgA0HHJzYCECADQQI2AgxBACECDEYLQS8hAgwrCyABQQFqIQFBMCECDCoLIAEgBEYEQEEvIQIMRAsgAS0AACIAQQlHIABBIEdxRQRAIAFBAWohASADLQAuQQFxDQEgA0EANgIcIAMgATYCFCADQekPNgIQIANBCjYCDEEAIQIMRAtBASECAkACQAJAAkACQAJAIAMtACxBAmsOBwUEBAMBAgAECyADIAMvATJBCHI7ATIMAwtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgtBLiECDCoLIANBADYCHCADIAE2AhQgA0GzEjYCECADQQs2AgxBACECDEMLQdIBIQIMKAsgASAERgRAQS4hAgxCCyADQQA2AgQgA0ERNgIIIAMgASABEDAiAA0BC0EtIQIMJgsgA0EtNgIcIAMgATYCFCADIAA2AgxBACECDD8LQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2AA2AhwgAyABNgIUIANBnho2AhAgA0EVNgIMQQAhAgw+C0HLACECDCMLIANBADYCHCADIAE2AhQgA0GFDjYCECADQR02AgxBACECDDwLIAEgBEYEQEHOACECDDwLIAEtAAAiAEEgRg0CIABBOkYNAQsgA0EAOgAsQQkhAgwgCyADKAIEIQAgA0EANgIEIAMgACABEC8iAA0BDAILIAMtAC5BAXEEQEHPASECDB8LIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ0CIANBKjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgw4CyADQcsANgIcIAMgADYCDCADIAFBAWo2AhRBACECDDcLIAFBAWohAUE/IQIMHAsgAUEBaiEBDCkLIAEgBEYEQEErIQIMNQsCQCABLQAAQQpGBEAgAUEBaiEBDAELIAMtAC5BwABxRQ0GCyADLQAyQYABcQRAQQAhAAJAIAMoAjgiAkUNACACKAJUIgJFDQAgAyACEQAAIQALIABFDREgAEEVRgRAIANBBTYCHCADIAE2AhQgA0GGGjYCECADQRU2AgxBACECDDYLIANBADYCHCADIAE2AhQgA0HiDTYCECADQRQ2AgxBACECDDULIANBMmohAiADEDRBACEAAkAgAygCOCIGRQ0AIAYoAiQiBkUNACADIAYRAAAhAAsgAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIANBAToAMAsgAiACLwEAQcAAcjsBAAtBKiECDBcLIANBKTYCHCADIAE2AhQgA0GyGDYCECADQRU2AgxBACECDDALIANBADYCHCADIAE2AhQgA0HdCzYCECADQRE2AgxBACECDC8LIANBADYCHCADIAE2AhQgA0GdCzYCECADQQI2AgxBACECDC4LQQEhByADLwEyIgVBCHFFBEAgAykDIEIAUiEHCwJAIAMtADAEQEEBIQAgAy0AKUEFRg0BIAVBwABxRSAHcUUNAQsCQCADLQAoIgJBAkYEQEEBIQAgAy8BNCIGQeUARg0CQQAhACAFQcAAcQ0CIAZB5ABGDQIgBkHmAGtBAkkNAiAGQcwBRg0CIAZBsAJGDQIMAQtBACEAIAVBwABxDQELQQIhACAFQQhxDQAgBUGABHEEQAJAIAJBAUcNACADLQAuQQpxDQBBBSEADAILQQQhAAwBCyAFQSBxRQRAIAMQNUEAR0ECdCEADAELQQBBAyADKQMgUBshAAsCQCAAQQFrDgUAAQYHAgMLQQAhAgJAIAMoAjgiAEUNACAAKAIsIgBFDQAgAyAAEQAAIQILIAJFDSYgAkEVRgRAIANBAzYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDC4LQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDC0LQc4BIQIMEgtBACECIANBADYCHCADIAE2AhQgA0HkHzYCECADQQ82AgwMKwtBACEAAkAgAygCOCICRQ0AIAIoAiwiAkUNACADIAIRAAAhAAsgAA0BC0EOIQIMDwsgAEEVRgRAIANBAjYCHCADIAE2AhQgA0G9GjYCECADQRU2AgxBACECDCkLQQAhAiADQQA2AhwgAyABNgIUIANBrw42AhAgA0ESNgIMDCgLQSkhAgwNCyADQQE6ADEMJAsgASAERwRAIANBCTYCCCADIAE2AgRBKCECDAwLQSYhAgwlCyADIAMpAyAiDCAEIAFrrSIKfSILQgAgCyAMWBs3AyAgCiAMVARAQSUhAgwlCyADKAIEIQBBACECIANBADYCBCADIAAgASAMp2oiARAxIgBFDQAgA0EFNgIcIAMgATYCFCADIAA2AgwMJAtBDyECDAkLIAEgBEYEQEEjIQIMIwtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsONxcWAAECAwQFBgcUFBQUFBQUCAkKCwwNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQODxAREhMUC0ICIQoMFgtCAyEKDBULQgQhCgwUC0IFIQoMEwtCBiEKDBILQgchCgwRC0IIIQoMEAtCCSEKDA8LQgohCgwOC0ILIQoMDQtCDCEKDAwLQg0hCgwLC0IOIQoMCgtCDyEKDAkLQgohCgwIC0ILIQoMBwtCDCEKDAYLQg0hCgwFC0IOIQoMBAtCDyEKDAMLQQAhAiADQQA2AhwgAyABNgIUIANBzhQ2AhAgA0EMNgIMDCILIAEgBEYEQEEiIQIMIgtCACEKAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQTBrDjcVFAABAgMEBQYHFhYWFhYWFggJCgsMDRYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWDg8QERITFgtCAiEKDBQLQgMhCgwTC0IEIQoMEgtCBSEKDBELQgYhCgwQC0IHIQoMDwtCCCEKDA4LQgkhCgwNC0IKIQoMDAtCCyEKDAsLQgwhCgwKC0INIQoMCQtCDiEKDAgLQg8hCgwHC0IKIQoMBgtCCyEKDAULQgwhCgwEC0INIQoMAwtCDiEKDAILQg8hCgwBC0IBIQoLIAFBAWohASADKQMgIgtC//////////8PWARAIAMgC0IEhiAKhDcDIAwCC0EAIQIgA0EANgIcIAMgATYCFCADQa0JNgIQIANBDDYCDAwfC0ElIQIMBAtBJiECDAMLIAMgAToALCADQQA2AgAgB0EBaiEBQQwhAgwCCyADQQA2AgAgBkEBaiEBQQohAgwBCyABQQFqIQFBCCECDAALAAtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMGAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMFwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMFgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMFQtBACECIANBADYCHCADIAE2AhQgA0HVEDYCECADQQk2AgwMFAtBACECIANBADYCHCADIAE2AhQgA0HXCjYCECADQQk2AgwMEwtBACECIANBADYCHCADIAE2AhQgA0G/EDYCECADQQk2AgwMEgtBACECIANBADYCHCADIAE2AhQgA0GkETYCECADQQk2AgwMEQtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMEAtBACECIANBADYCHCADIAE2AhQgA0G/FjYCECADQQ82AgwMDwtBACECIANBADYCHCADIAE2AhQgA0HIEjYCECADQQs2AgwMDgtBACECIANBADYCHCADIAE2AhQgA0GVCTYCECADQQs2AgwMDQtBACECIANBADYCHCADIAE2AhQgA0HpDzYCECADQQo2AgwMDAtBACECIANBADYCHCADIAE2AhQgA0GDEDYCECADQQo2AgwMCwtBACECIANBADYCHCADIAE2AhQgA0GmHDYCECADQQI2AgwMCgtBACECIANBADYCHCADIAE2AhQgA0HFFTYCECADQQI2AgwMCQtBACECIANBADYCHCADIAE2AhQgA0H/FzYCECADQQI2AgwMCAtBACECIANBADYCHCADIAE2AhQgA0HKFzYCECADQQI2AgwMBwsgA0ECNgIcIAMgATYCFCADQZQdNgIQIANBFjYCDEEAIQIMBgtB3gAhAiABIARGDQUgCUEIaiEHIAMoAgAhBQJAAkAgASAERwRAIAVBxsYAaiEIIAQgBWogAWshBiAFQX9zQQpqIgUgAWohAANAIAEtAAAgCC0AAEcEQEECIQgMAwsgBUUEQEEAIQggACEBDAMLIAVBAWshBSAIQQFqIQggBCABQQFqIgFHDQALIAYhBSAEIQELIAdBATYCACADIAU2AgAMAQsgA0EANgIAIAcgCDYCAAsgByABNgIEIAkoAgwhACAJKAIIDgMBBQIACwALIANBADYCHCADQa0dNgIQIANBFzYCDCADIABBAWo2AhRBACECDAMLIANBADYCHCADIAA2AhQgA0HCHTYCECADQQk2AgxBACECDAILIAEgBEYEQEEoIQIMAgsgA0EJNgIIIAMgATYCBEEnIQIMAQsgASAERgRAQQEhAgwBCwNAAkACQAJAIAEtAABBCmsOBAABAQABCyABQQFqIQEMAQsgAUEBaiEBIAMtAC5BIHENAEEAIQIgA0EANgIcIAMgATYCFCADQYwgNgIQIANBBTYCDAwCC0EBIQIgASAERw0ACwsgCUEQaiQAIAJFBEAgAygCDCEADAELIAMgAjYCHEEAIQAgAygCBCIBRQ0AIAMgASAEIAMoAggRAQAiAUUNACADIAQ2AhQgAyABNgIMIAEhAAsgAAu+AgECfyAAQQA6AAAgAEHcAGoiAUEBa0EAOgAAIABBADoAAiAAQQA6AAEgAUEDa0EAOgAAIAFBAmtBADoAACAAQQA6AAMgAUEEa0EAOgAAQQAgAGtBA3EiASAAaiIAQQA2AgBB3AAgAWtBfHEiAiAAaiIBQQRrQQA2AgACQCACQQlJDQAgAEEANgIIIABBADYCBCABQQhrQQA2AgAgAUEMa0EANgIAIAJBGUkNACAAQQA2AhggAEEANgIUIABBADYCECAAQQA2AgwgAUEQa0EANgIAIAFBFGtBADYCACABQRhrQQA2AgAgAUEca0EANgIAIAIgAEEEcUEYciICayIBQSBJDQAgACACaiEAA0AgAEIANwMYIABCADcDECAAQgA3AwggAEIANwMAIABBIGohACABQSBrIgFBH0sNAAsLC1YBAX8CQCAAKAIMDQACQAJAAkACQCAALQAxDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgAREAACIBDQMLQQAPCwALIABB0Bg2AhBBDiEBCyABCxoAIAAoAgxFBEAgAEHJHjYCECAAQRU2AgwLCxQAIAAoAgxBFUYEQCAAQQA2AgwLCxQAIAAoAgxBFkYEQCAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsXACAAQSRPBEAACyAAQQJ0QZQ3aigCAAsXACAAQS9PBEAACyAAQQJ0QaQ4aigCAAu/CQEBf0HfLCEBAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHkAGsO9ANjYgABYWFhYWFhAgMEBWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEGBwgJCgsMDQ4PYWFhYWEQYWFhYWFhYWFhYWERYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhEhMUFRYXGBkaG2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEcHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTZhNzg5OmFhYWFhYWFhO2FhYTxhYWFhPT4/YWFhYWFhYWFAYWFBYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhQkNERUZHSElKS0xNTk9QUVJTYWFhYWFhYWFUVVZXWFlaW2FcXWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYV5hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFfYGELQdUrDwtBgyUPC0G/MA8LQfI1DwtBtCgPC0GfKA8LQYEsDwtB1ioPC0H0Mw8LQa0zDwtByygPC0HOIw8LQcAjDwtB2SMPC0HRJA8LQZwzDwtBojYPC0H8Mw8LQeArDwtB4SUPC0HtIA8LQcQyDwtBqScPC0G5Ng8LQbggDwtBqyAPC0GjJA8LQbYkDwtBgSMPC0HhMg8LQZ80DwtByCkPC0HAMg8LQe4yDwtB8C8PC0HGNA8LQdAhDwtBmiQPC0HrLw8LQYQ1DwtByzUPC0GWMQ8LQcgrDwtB1C8PC0GTMA8LQd81DwtBtCMPC0G+NQ8LQdIpDwtBsyIPC0HNIA8LQZs2DwtBkCEPC0H/IA8LQa01DwtBsDQPC0HxJA8LQacqDwtB3TAPC0GLIg8LQcgvDwtB6yoPC0H0KQ8LQY8lDwtB3SIPC0HsJg8LQf0wDwtB1iYPC0GUNQ8LQY0jDwtBuikPC0HHIg8LQfIlDwtBtjMPC0GiIQ8LQf8vDwtBwCEPC0GBMw8LQcklDwtBqDEPC0HGMw8LQdM2DwtBxjYPC0HkNA8LQYgmDwtB7ScPC0H4IQ8LQakwDwtBjzQPC0GGNg8LQaovDwtBoSYPC0HsNg8LQZIpDwtBryYPC0GZIg8LQeAhDwsAC0G1JSEBCyABCxcAIAAgAC8BLkH+/wNxIAFBAEdyOwEuCxoAIAAgAC8BLkH9/wNxIAFBAEdBAXRyOwEuCxoAIAAgAC8BLkH7/wNxIAFBAEdBAnRyOwEuCxoAIAAgAC8BLkH3/wNxIAFBAEdBA3RyOwEuCxoAIAAgAC8BLkHv/wNxIAFBAEdBBHRyOwEuCxoAIAAgAC8BLkHf/wNxIAFBAEdBBXRyOwEuCxoAIAAgAC8BLkG//wNxIAFBAEdBBnRyOwEuCxoAIAAgAC8BLkH//gNxIAFBAEdBB3RyOwEuCxoAIAAgAC8BLkH//QNxIAFBAEdBCHRyOwEuCxoAIAAgAC8BLkH/+wNxIAFBAEdBCXRyOwEuCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBzhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5Ao2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB5R02AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBnRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBoh42AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7hQ2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9xs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRU2AhBBGCEECyAECzgAIAACfyAALwEyQRRxQRRGBEBBASAALQAoQQFGDQEaIAAvATRB5QBGDAELIAAtAClBBUYLOgAwC1kBAn8CQCAALQAoQQFGDQAgAC8BNCIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMiIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEyIgFBAnFFDQEMAgsgAC8BMiIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATQiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtzACAAQRBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAA/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQTBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQSBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQewBNgIcCwYAIAAQOQuaLQELfyMAQRBrIgokAEGY1AAoAgAiCUUEQEHY1wAoAgAiBUUEQEHk1wBCfzcCAEHc1wBCgICEgICAwAA3AgBB2NcAIApBCGpBcHFB2KrVqgVzIgU2AgBB7NcAQQA2AgBBvNcAQQA2AgALQcDXAEGA2AQ2AgBBkNQAQYDYBDYCAEGk1AAgBTYCAEGg1ABBfzYCAEHE1wBBgKgDNgIAA0AgAUG81ABqIAFBsNQAaiICNgIAIAIgAUGo1ABqIgM2AgAgAUG01ABqIAM2AgAgAUHE1ABqIAFBuNQAaiIDNgIAIAMgAjYCACABQczUAGogAUHA1ABqIgI2AgAgAiADNgIAIAFByNQAaiACNgIAIAFBIGoiAUGAAkcNAAtBjNgEQcGnAzYCAEGc1ABB6NcAKAIANgIAQYzUAEHApwM2AgBBmNQAQYjYBDYCAEHM/wdBODYCAEGI2AQhCQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQewBTQRAQYDUACgCACIGQRAgAEETakFwcSAAQQtJGyIEQQN2IgB2IgFBA3EEQAJAIAFBAXEgAHJBAXMiAkEDdCIAQajUAGoiASAAQbDUAGooAgAiACgCCCIDRgRAQYDUACAGQX4gAndxNgIADAELIAEgAzYCCCADIAE2AgwLIABBCGohASAAIAJBA3QiAkEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwRC0GI1AAoAgAiCCAETw0BIAEEQAJAQQIgAHQiAkEAIAJrciABIAB0cWgiAEEDdCICQajUAGoiASACQbDUAGooAgAiAigCCCIDRgRAQYDUACAGQX4gAHdxIgY2AgAMAQsgASADNgIIIAMgATYCDAsgAiAEQQNyNgIEIABBA3QiACAEayEFIAAgAmogBTYCACACIARqIgQgBUEBcjYCBCAIBEAgCEF4cUGo1ABqIQBBlNQAKAIAIQMCf0EBIAhBA3Z0IgEgBnFFBEBBgNQAIAEgBnI2AgAgAAwBCyAAKAIICyIBIAM2AgwgACADNgIIIAMgADYCDCADIAE2AggLIAJBCGohAUGU1AAgBDYCAEGI1AAgBTYCAAwRC0GE1AAoAgAiC0UNASALaEECdEGw1gBqKAIAIgAoAgRBeHEgBGshBSAAIQIDQAJAIAIoAhAiAUUEQCACQRRqKAIAIgFFDQELIAEoAgRBeHEgBGsiAyAFSSECIAMgBSACGyEFIAEgACACGyEAIAEhAgwBCwsgACgCGCEJIAAoAgwiAyAARwRAQZDUACgCABogAyAAKAIIIgE2AgggASADNgIMDBALIABBFGoiAigCACIBRQRAIAAoAhAiAUUNAyAAQRBqIQILA0AgAiEHIAEiA0EUaiICKAIAIgENACADQRBqIQIgAygCECIBDQALIAdBADYCAAwPC0F/IQQgAEG/f0sNACAAQRNqIgFBcHEhBEGE1AAoAgAiCEUNAEEAIARrIQUCQAJAAkACf0EAIARBgAJJDQAaQR8gBEH///8HSw0AGiAEQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qCyIGQQJ0QbDWAGooAgAiAkUEQEEAIQFBACEDDAELQQAhASAEQRkgBkEBdmtBACAGQR9HG3QhAEEAIQMDQAJAIAIoAgRBeHEgBGsiByAFTw0AIAIhAyAHIgUNAEEAIQUgAiEBDAMLIAEgAkEUaigCACIHIAcgAiAAQR12QQRxakEQaigCACICRhsgASAHGyEBIABBAXQhACACDQALCyABIANyRQRAQQAhA0ECIAZ0IgBBACAAa3IgCHEiAEUNAyAAaEECdEGw1gBqKAIAIQELIAFFDQELA0AgASgCBEF4cSAEayICIAVJIQAgAiAFIAAbIQUgASADIAAbIQMgASgCECIABH8gAAUgAUEUaigCAAsiAQ0ACwsgA0UNACAFQYjUACgCACAEa08NACADKAIYIQcgAyADKAIMIgBHBEBBkNQAKAIAGiAAIAMoAggiATYCCCABIAA2AgwMDgsgA0EUaiICKAIAIgFFBEAgAygCECIBRQ0DIANBEGohAgsDQCACIQYgASIAQRRqIgIoAgAiAQ0AIABBEGohAiAAKAIQIgENAAsgBkEANgIADA0LQYjUACgCACIDIARPBEBBlNQAKAIAIQECQCADIARrIgJBEE8EQCABIARqIgAgAkEBcjYCBCABIANqIAI2AgAgASAEQQNyNgIEDAELIAEgA0EDcjYCBCABIANqIgAgACgCBEEBcjYCBEEAIQBBACECC0GI1AAgAjYCAEGU1AAgADYCACABQQhqIQEMDwtBjNQAKAIAIgMgBEsEQCAEIAlqIgAgAyAEayIBQQFyNgIEQZjUACAANgIAQYzUACABNgIAIAkgBEEDcjYCBCAJQQhqIQEMDwtBACEBIAQCf0HY1wAoAgAEQEHg1wAoAgAMAQtB5NcAQn83AgBB3NcAQoCAhICAgMAANwIAQdjXACAKQQxqQXBxQdiq1aoFczYCAEHs1wBBADYCAEG81wBBADYCAEGAgAQLIgAgBEHHAGoiBWoiBkEAIABrIgdxIgJPBEBB8NcAQTA2AgAMDwsCQEG41wAoAgAiAUUNAEGw1wAoAgAiCCACaiEAIAAgAU0gACAIS3ENAEEAIQFB8NcAQTA2AgAMDwtBvNcALQAAQQRxDQQCQAJAIAkEQEHA1wAhAQNAIAEoAgAiACAJTQRAIAAgASgCBGogCUsNAwsgASgCCCIBDQALC0EAEDoiAEF/Rg0FIAIhBkHc1wAoAgAiAUEBayIDIABxBEAgAiAAayAAIANqQQAgAWtxaiEGCyAEIAZPDQUgBkH+////B0sNBUG41wAoAgAiAwRAQbDXACgCACIHIAZqIQEgASAHTQ0GIAEgA0sNBgsgBhA6IgEgAEcNAQwHCyAGIANrIAdxIgZB/v///wdLDQQgBhA6IQAgACABKAIAIAEoAgRqRg0DIAAhAQsCQCAGIARByABqTw0AIAFBf0YNAEHg1wAoAgAiACAFIAZrakEAIABrcSIAQf7///8HSwRAIAEhAAwHCyAAEDpBf0cEQCAAIAZqIQYgASEADAcLQQAgBmsQOhoMBAsgASIAQX9HDQUMAwtBACEDDAwLQQAhAAwKCyAAQX9HDQILQbzXAEG81wAoAgBBBHI2AgALIAJB/v///wdLDQEgAhA6IQBBABA6IQEgAEF/Rg0BIAFBf0YNASAAIAFPDQEgASAAayIGIARBOGpNDQELQbDXAEGw1wAoAgAgBmoiATYCAEG01wAoAgAgAUkEQEG01wAgATYCAAsCQAJAAkBBmNQAKAIAIgIEQEHA1wAhAQNAIAAgASgCACIDIAEoAgQiBWpGDQIgASgCCCIBDQALDAILQZDUACgCACIBQQBHIAAgAU9xRQRAQZDUACAANgIAC0EAIQFBxNcAIAY2AgBBwNcAIAA2AgBBoNQAQX82AgBBpNQAQdjXACgCADYCAEHM1wBBADYCAANAIAFBvNQAaiABQbDUAGoiAjYCACACIAFBqNQAaiIDNgIAIAFBtNQAaiADNgIAIAFBxNQAaiABQbjUAGoiAzYCACADIAI2AgAgAUHM1ABqIAFBwNQAaiICNgIAIAIgAzYCACABQcjUAGogAjYCACABQSBqIgFBgAJHDQALQXggAGtBD3EiASAAaiICIAZBOGsiAyABayIBQQFyNgIEQZzUAEHo1wAoAgA2AgBBjNQAIAE2AgBBmNQAIAI2AgAgACADakE4NgIEDAILIAAgAk0NACACIANJDQAgASgCDEEIcQ0AQXggAmtBD3EiACACaiIDQYzUACgCACAGaiIHIABrIgBBAXI2AgQgASAFIAZqNgIEQZzUAEHo1wAoAgA2AgBBjNQAIAA2AgBBmNQAIAM2AgAgAiAHakE4NgIEDAELIABBkNQAKAIASQRAQZDUACAANgIACyAAIAZqIQNBwNcAIQECQAJAAkADQCADIAEoAgBHBEAgASgCCCIBDQEMAgsLIAEtAAxBCHFFDQELQcDXACEBA0AgASgCACIDIAJNBEAgAyABKAIEaiIFIAJLDQMLIAEoAgghAQwACwALIAEgADYCACABIAEoAgQgBmo2AgQgAEF4IABrQQ9xaiIJIARBA3I2AgQgA0F4IANrQQ9xaiIGIAQgCWoiBGshASACIAZGBEBBmNQAIAQ2AgBBjNQAQYzUACgCACABaiIANgIAIAQgAEEBcjYCBAwIC0GU1AAoAgAgBkYEQEGU1AAgBDYCAEGI1ABBiNQAKAIAIAFqIgA2AgAgBCAAQQFyNgIEIAAgBGogADYCAAwICyAGKAIEIgVBA3FBAUcNBiAFQXhxIQggBUH/AU0EQCAFQQN2IQMgBigCCCIAIAYoAgwiAkYEQEGA1ABBgNQAKAIAQX4gA3dxNgIADAcLIAIgADYCCCAAIAI2AgwMBgsgBigCGCEHIAYgBigCDCIARwRAIAAgBigCCCICNgIIIAIgADYCDAwFCyAGQRRqIgIoAgAiBUUEQCAGKAIQIgVFDQQgBkEQaiECCwNAIAIhAyAFIgBBFGoiAigCACIFDQAgAEEQaiECIAAoAhAiBQ0ACyADQQA2AgAMBAtBeCAAa0EPcSIBIABqIgcgBkE4ayIDIAFrIgFBAXI2AgQgACADakE4NgIEIAIgBUE3IAVrQQ9xakE/ayIDIAMgAkEQakkbIgNBIzYCBEGc1ABB6NcAKAIANgIAQYzUACABNgIAQZjUACAHNgIAIANBEGpByNcAKQIANwIAIANBwNcAKQIANwIIQcjXACADQQhqNgIAQcTXACAGNgIAQcDXACAANgIAQczXAEEANgIAIANBJGohAQNAIAFBBzYCACAFIAFBBGoiAUsNAAsgAiADRg0AIAMgAygCBEF+cTYCBCADIAMgAmsiBTYCACACIAVBAXI2AgQgBUH/AU0EQCAFQXhxQajUAGohAAJ/QYDUACgCACIBQQEgBUEDdnQiA3FFBEBBgNQAIAEgA3I2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEGw1gBqIQBBhNQAKAIAIgNBASABdCIGcUUEQCAAIAI2AgBBhNQAIAMgBnI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEDAkADQCADIgAoAgRBeHEgBUYNASABQR12IQMgAUEBdCEBIAAgA0EEcWpBEGoiBigCACIDDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLQYzUACgCACIBIARNDQBBmNQAKAIAIgAgBGoiAiABIARrIgFBAXI2AgRBjNQAIAE2AgBBmNQAIAI2AgAgACAEQQNyNgIEIABBCGohAQwIC0EAIQFB8NcAQTA2AgAMBwtBACEACyAHRQ0AAkAgBigCHCICQQJ0QbDWAGoiAygCACAGRgRAIAMgADYCACAADQFBhNQAQYTUACgCAEF+IAJ3cTYCAAwCCyAHQRBBFCAHKAIQIAZGG2ogADYCACAARQ0BCyAAIAc2AhggBigCECICBEAgACACNgIQIAIgADYCGAsgBkEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgCGohASAGIAhqIgYoAgQhBQsgBiAFQX5xNgIEIAEgBGogATYCACAEIAFBAXI2AgQgAUH/AU0EQCABQXhxQajUAGohAAJ/QYDUACgCACICQQEgAUEDdnQiAXFFBEBBgNQAIAEgAnI2AgAgAAwBCyAAKAIICyIBIAQ2AgwgACAENgIIIAQgADYCDCAEIAE2AggMAQtBHyEFIAFB////B00EQCABQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qIQULIAQgBTYCHCAEQgA3AhAgBUECdEGw1gBqIQBBhNQAKAIAIgJBASAFdCIDcUUEQCAAIAQ2AgBBhNQAIAIgA3I2AgAgBCAANgIYIAQgBDYCCCAEIAQ2AgwMAQsgAUEZIAVBAXZrQQAgBUEfRxt0IQUgACgCACEAAkADQCAAIgIoAgRBeHEgAUYNASAFQR12IQAgBUEBdCEFIAIgAEEEcWpBEGoiAygCACIADQALIAMgBDYCACAEIAI2AhggBCAENgIMIAQgBDYCCAwBCyACKAIIIgAgBDYCDCACIAQ2AgggBEEANgIYIAQgAjYCDCAEIAA2AggLIAlBCGohAQwCCwJAIAdFDQACQCADKAIcIgFBAnRBsNYAaiICKAIAIANGBEAgAiAANgIAIAANAUGE1AAgCEF+IAF3cSIINgIADAILIAdBEEEUIAcoAhAgA0YbaiAANgIAIABFDQELIAAgBzYCGCADKAIQIgEEQCAAIAE2AhAgASAANgIYCyADQRRqKAIAIgFFDQAgAEEUaiABNgIAIAEgADYCGAsCQCAFQQ9NBEAgAyAEIAVqIgBBA3I2AgQgACADaiIAIAAoAgRBAXI2AgQMAQsgAyAEaiICIAVBAXI2AgQgAyAEQQNyNgIEIAIgBWogBTYCACAFQf8BTQRAIAVBeHFBqNQAaiEAAn9BgNQAKAIAIgFBASAFQQN2dCIFcUUEQEGA1AAgASAFcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbDWAGohAEEBIAF0IgQgCHFFBEAgACACNgIAQYTUACAEIAhyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhBAJAA0AgBCIAKAIEQXhxIAVGDQEgAUEddiEEIAFBAXQhASAAIARBBHFqQRBqIgYoAgAiBA0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIICyADQQhqIQEMAQsCQCAJRQ0AAkAgACgCHCIBQQJ0QbDWAGoiAigCACAARgRAIAIgAzYCACADDQFBhNQAIAtBfiABd3E2AgAMAgsgCUEQQRQgCSgCECAARhtqIAM2AgAgA0UNAQsgAyAJNgIYIAAoAhAiAQRAIAMgATYCECABIAM2AhgLIABBFGooAgAiAUUNACADQRRqIAE2AgAgASADNgIYCwJAIAVBD00EQCAAIAQgBWoiAUEDcjYCBCAAIAFqIgEgASgCBEEBcjYCBAwBCyAAIARqIgcgBUEBcjYCBCAAIARBA3I2AgQgBSAHaiAFNgIAIAgEQCAIQXhxQajUAGohAUGU1AAoAgAhAwJ/QQEgCEEDdnQiAiAGcUUEQEGA1AAgAiAGcjYCACABDAELIAEoAggLIgIgAzYCDCABIAM2AgggAyABNgIMIAMgAjYCCAtBlNQAIAc2AgBBiNQAIAU2AgALIABBCGohAQsgCkEQaiQAIAELQwAgAEUEQD8AQRB0DwsCQCAAQf//A3ENACAAQQBIDQAgAEEQdkAAIgBBf0YEQEHw1wBBMDYCAEF/DwsgAEEQdA8LAAsL20AiAEGACAsJAQAAAAIAAAADAEGUCAsFBAAAAAUAQaQICwkGAAAABwAAAAgAQdwIC4IxSW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMARXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVycwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zAFVzZXIgY2FsbGJhY2sgZXJyb3IAYG9uX3Jlc2V0YCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfaGVhZGVyYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9iZWdpbmAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3N0YXR1c19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3ZlcnNpb25fY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl91cmxfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXRob2RfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfZmllbGRfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fbmFtZWAgY2FsbGJhY2sgZXJyb3IAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzZXJ2ZXIASW52YWxpZCBoZWFkZXIgdmFsdWUgY2hhcgBJbnZhbGlkIGhlYWRlciBmaWVsZCBjaGFyAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdmVyc2lvbgBJbnZhbGlkIG1pbm9yIHZlcnNpb24ASW52YWxpZCBtYWpvciB2ZXJzaW9uAEV4cGVjdGVkIHNwYWNlIGFmdGVyIHZlcnNpb24ARXhwZWN0ZWQgQ1JMRiBhZnRlciB2ZXJzaW9uAEludmFsaWQgSFRUUCB2ZXJzaW9uAEludmFsaWQgaGVhZGVyIHRva2VuAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdXJsAEludmFsaWQgY2hhcmFjdGVycyBpbiB1cmwAVW5leHBlY3RlZCBzdGFydCBjaGFyIGluIHVybABEb3VibGUgQCBpbiB1cmwARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgAVHJhbnNmZXItRW5jb2RpbmcgY2FuJ3QgYmUgcHJlc2VudCB3aXRoIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgc2l6ZQBFeHBlY3RlZCBMRiBhZnRlciBjaHVuayBzaXplAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGhlYWRlciB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBxdW90ZWQtcGFpciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBQYXVzZWQgYnkgb25faGVhZGVyc19jb21wbGV0ZQBJbnZhbGlkIEVPRiBzdGF0ZQBvbl9yZXNldCBwYXVzZQBvbl9jaHVua19oZWFkZXIgcGF1c2UAb25fbWVzc2FnZV9iZWdpbiBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fdmFsdWUgcGF1c2UAb25fc3RhdHVzX2NvbXBsZXRlIHBhdXNlAG9uX3ZlcnNpb25fY29tcGxldGUgcGF1c2UAb25fdXJsX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXNzYWdlX2NvbXBsZXRlIHBhdXNlAG9uX21ldGhvZF9jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfZmllbGRfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUgcGF1c2UAVW5leHBlY3RlZCBzcGFjZSBhZnRlciBzdGFydCBsaW5lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgcmVzcG9uc2UgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGV4dGVuc2lvbiBuYW1lAEludmFsaWQgc3RhdHVzIGNvZGUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBkYXRhAEV4cGVjdGVkIExGIGFmdGVyIGNodW5rIGRhdGEAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAERhdGEgYWZ0ZXIgYENvbm5lY3Rpb246IGNsb3NlYABTV0lUQ0hfUFJPWFkAVVNFX1BST1hZAE1LQUNUSVZJVFkAVU5QUk9DRVNTQUJMRV9FTlRJVFkAUVVFUlkAQ09QWQBNT1ZFRF9QRVJNQU5FTlRMWQBUT09fRUFSTFkATk9USUZZAEZBSUxFRF9ERVBFTkRFTkNZAEJBRF9HQVRFV0FZAFBMQVkAUFVUAENIRUNLT1VUAEdBVEVXQVlfVElNRU9VVABSRVFVRVNUX1RJTUVPVVQATkVUV09SS19DT05ORUNUX1RJTUVPVVQAQ09OTkVDVElPTl9USU1FT1VUAExPR0lOX1RJTUVPVVQATkVUV09SS19SRUFEX1RJTUVPVVQAUE9TVABNSVNESVJFQ1RFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX0xPQURfQkFMQU5DRURfUkVRVUVTVABCQURfUkVRVUVTVABIVFRQX1JFUVVFU1RfU0VOVF9UT19IVFRQU19QT1JUAFJFUE9SVABJTV9BX1RFQVBPVABSRVNFVF9DT05URU5UAE5PX0NPTlRFTlQAUEFSVElBTF9DT05URU5UAEhQRV9JTlZBTElEX0NPTlNUQU5UAEhQRV9DQl9SRVNFVABHRVQASFBFX1NUUklDVABDT05GTElDVABURU1QT1JBUllfUkVESVJFQ1QAUEVSTUFORU5UX1JFRElSRUNUAENPTk5FQ1QATVVMVElfU1RBVFVTAEhQRV9JTlZBTElEX1NUQVRVUwBUT09fTUFOWV9SRVFVRVNUUwBFQVJMWV9ISU5UUwBVTkFWQUlMQUJMRV9GT1JfTEVHQUxfUkVBU09OUwBPUFRJT05TAFNXSVRDSElOR19QUk9UT0NPTFMAVkFSSUFOVF9BTFNPX05FR09USUFURVMATVVMVElQTEVfQ0hPSUNFUwBJTlRFUk5BTF9TRVJWRVJfRVJST1IAV0VCX1NFUlZFUl9VTktOT1dOX0VSUk9SAFJBSUxHVU5fRVJST1IASURFTlRJVFlfUFJPVklERVJfQVVUSEVOVElDQVRJT05fRVJST1IAU1NMX0NFUlRJRklDQVRFX0VSUk9SAElOVkFMSURfWF9GT1JXQVJERURfRk9SAFNFVF9QQVJBTUVURVIAR0VUX1BBUkFNRVRFUgBIUEVfVVNFUgBTRUVfT1RIRVIASFBFX0NCX0NIVU5LX0hFQURFUgBFeHBlY3RlZCBMRiBhZnRlciBDUgBNS0NBTEVOREFSAFNFVFVQAFdFQl9TRVJWRVJfSVNfRE9XTgBURUFSRE9XTgBIUEVfQ0xPU0VEX0NPTk5FQ1RJT04ASEVVUklTVElDX0VYUElSQVRJT04ARElTQ09OTkVDVEVEX09QRVJBVElPTgBOT05fQVVUSE9SSVRBVElWRV9JTkZPUk1BVElPTgBIUEVfSU5WQUxJRF9WRVJTSU9OAEhQRV9DQl9NRVNTQUdFX0JFR0lOAFNJVEVfSVNfRlJPWkVOAEhQRV9JTlZBTElEX0hFQURFUl9UT0tFTgBJTlZBTElEX1RPS0VOAEZPUkJJRERFTgBFTkhBTkNFX1lPVVJfQ0FMTQBIUEVfSU5WQUxJRF9VUkwAQkxPQ0tFRF9CWV9QQVJFTlRBTF9DT05UUk9MAE1LQ09MAEFDTABIUEVfSU5URVJOQUwAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRV9VTk9GRklDSUFMAEhQRV9PSwBVTkxJTksAVU5MT0NLAFBSSQBSRVRSWV9XSVRIAEhQRV9JTlZBTElEX0NPTlRFTlRfTEVOR1RIAEhQRV9VTkVYUEVDVEVEX0NPTlRFTlRfTEVOR1RIAEZMVVNIAFBST1BQQVRDSABNLVNFQVJDSABVUklfVE9PX0xPTkcAUFJPQ0VTU0lORwBNSVNDRUxMQU5FT1VTX1BFUlNJU1RFTlRfV0FSTklORwBNSVNDRUxMQU5FT1VTX1dBUk5JTkcASFBFX0lOVkFMSURfVFJBTlNGRVJfRU5DT0RJTkcARXhwZWN0ZWQgQ1JMRgBIUEVfSU5WQUxJRF9DSFVOS19TSVpFAE1PVkUAQ09OVElOVUUASFBFX0NCX1NUQVRVU19DT01QTEVURQBIUEVfQ0JfSEVBREVSU19DT01QTEVURQBIUEVfQ0JfVkVSU0lPTl9DT01QTEVURQBIUEVfQ0JfVVJMX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8AAFIVAAAaFQAADxIAAOQZAACRFQAACRQAAC0ZAADkFAAA6REAAGkUAAChFAAAdhUAAEMWAABeEgAAlBcAABcWAAB9FAAAfxYAAEEXAACzEwAAwxYAAAQaAAC9GAAA0BgAAKATAADUGQAArxYAAGgWAABwFwAA2RYAAPwYAAD+EQAAWRcAAJcWAAAcFwAA9hYAAI0XAAALEgAAfxsAAC4RAACzEAAASRIAAK0SAAD2GAAAaBAAAGIVAAAQFQAAWhYAAEoZAAC1FQAAwRUAAGAVAABcGQAAWhkAAFMZAAAWFQAArREAAEIQAAC3EAAAVxgAAL8VAACJEAAAHBkAABoZAAC5FQAAURgAANwTAABbFQAAWRUAAOYYAABnFQAAERkAAO0YAADnEwAArhAAAMIXAAAAFAAAkhMAAIQTAABAEgAAJhkAAK8VAABiEABB6TkLAQEAQYA6C+ABAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAwEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQeo7CwQBAAACAEGBPAteAwQDAwMDAwAAAwMAAwMAAwMDAwMDAwMDAwAFAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAMAAwBB6j0LBAEAAAIAQYE+C14DAAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAQABQAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEHgPwsNbG9zZWVlcC1hbGl2ZQBB+T8LAQEAQZDAAAvgAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH5wQALAQEAQZDCAAvnAQEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZABBocQAC14BAAEBAQEBAAABAQABAQABAQEBAQEBAQEBAAAAAAAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAEGAxgALIWVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgBBsMYACytyYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNClNNDQoNClRUUC9DRS9UU1AvAEHpxgALBQECAAEDAEGAxwALXwQFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFAEHpyAALBQECAAEDAEGAyQALXwQFBQYFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFAEHpygALBAEAAAEAQYHLAAteAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgBB6cwACwUBAgABAwBBgM0AC18EBQAABQUFBQUFBQUFBQUGBQUFBQUFBQUFBQUFAAUABwgFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUABQAFAAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFAAAABQBB6c4ACwUBAQABAQBBgM8ACwEBAEGazwALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEHp0AALBQEBAAEBAEGA0QALAQEAQYrRAAsGAgAAAAACAEGh0QALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQeDSAAuaAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VVRVJZT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=";
var wasmBuffer;
Object.defineProperty(module3, "exports", {
get: /* @__PURE__ */ __name(() => {
return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer7.from(wasmBase64, "base64");
}, "get")
});
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/constants.js
var require_constants3 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/constants.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var corsSafeListedMethods = (
/** @type {const} */
["GET", "HEAD", "POST"]
);
var corsSafeListedMethodsSet = new Set(corsSafeListedMethods);
var nullBodyStatus = (
/** @type {const} */
[101, 204, 205, 304]
);
var redirectStatus = (
/** @type {const} */
[301, 302, 303, 307, 308]
);
var redirectStatusSet = new Set(redirectStatus);
var badPorts = (
/** @type {const} */
[
"1",
"7",
"9",
"11",
"13",
"15",
"17",
"19",
"20",
"21",
"22",
"23",
"25",
"37",
"42",
"43",
"53",
"69",
"77",
"79",
"87",
"95",
"101",
"102",
"103",
"104",
"109",
"110",
"111",
"113",
"115",
"117",
"119",
"123",
"135",
"137",
"139",
"143",
"161",
"179",
"389",
"427",
"465",
"512",
"513",
"514",
"515",
"526",
"530",
"531",
"532",
"540",
"548",
"554",
"556",
"563",
"587",
"601",
"636",
"989",
"990",
"993",
"995",
"1719",
"1720",
"1723",
"2049",
"3659",
"4045",
"4190",
"5060",
"5061",
"6000",
"6566",
"6665",
"6666",
"6667",
"6668",
"6669",
"6679",
"6697",
"10080"
]
);
var badPortsSet = new Set(badPorts);
var referrerPolicyTokens = (
/** @type {const} */
[
"no-referrer",
"no-referrer-when-downgrade",
"same-origin",
"origin",
"strict-origin",
"origin-when-cross-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
]
);
var referrerPolicy = (
/** @type {const} */
[
"",
...referrerPolicyTokens
]
);
var referrerPolicyTokensSet = new Set(referrerPolicyTokens);
var requestRedirect = (
/** @type {const} */
["follow", "manual", "error"]
);
var safeMethods = (
/** @type {const} */
["GET", "HEAD", "OPTIONS", "TRACE"]
);
var safeMethodsSet = new Set(safeMethods);
var requestMode = (
/** @type {const} */
["navigate", "same-origin", "no-cors", "cors"]
);
var requestCredentials = (
/** @type {const} */
["omit", "same-origin", "include"]
);
var requestCache = (
/** @type {const} */
[
"default",
"no-store",
"reload",
"no-cache",
"force-cache",
"only-if-cached"
]
);
var requestBodyHeader = (
/** @type {const} */
[
"content-encoding",
"content-language",
"content-location",
"content-type",
// See https://github.com/nodejs/undici/issues/2021
// 'Content-Length' is a forbidden header name, which is typically
// removed in the Headers implementation. However, undici doesn't
// filter out headers, so we add it here.
"content-length"
]
);
var requestDuplex = (
/** @type {const} */
[
"half"
]
);
var forbiddenMethods = (
/** @type {const} */
["CONNECT", "TRACE", "TRACK"]
);
var forbiddenMethodsSet = new Set(forbiddenMethods);
var subresource = (
/** @type {const} */
[
"audio",
"audioworklet",
"font",
"image",
"manifest",
"paintworklet",
"script",
"style",
"track",
"video",
"xslt",
""
]
);
var subresourceSet = new Set(subresource);
module3.exports = {
subresource,
forbiddenMethods,
requestBodyHeader,
referrerPolicy,
requestRedirect,
requestMode,
requestCredentials,
requestCache,
redirectStatus,
corsSafeListedMethods,
nullBodyStatus,
safeMethods,
badPorts,
requestDuplex,
subresourceSet,
badPortsSet,
redirectStatusSet,
corsSafeListedMethodsSet,
safeMethodsSet,
forbiddenMethodsSet,
referrerPolicyTokens: referrerPolicyTokensSet
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/global.js
var require_global = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/global.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var globalOrigin = Symbol.for("undici.globalOrigin.1");
function getGlobalOrigin() {
return globalThis[globalOrigin];
}
__name(getGlobalOrigin, "getGlobalOrigin");
function setGlobalOrigin(newOrigin) {
if (newOrigin === void 0) {
Object.defineProperty(globalThis, globalOrigin, {
value: void 0,
writable: true,
enumerable: false,
configurable: false
});
return;
}
const parsedURL = new URL(newOrigin);
if (parsedURL.protocol !== "http:" && parsedURL.protocol !== "https:") {
throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`);
}
Object.defineProperty(globalThis, globalOrigin, {
value: parsedURL,
writable: true,
enumerable: false,
configurable: false
});
}
__name(setGlobalOrigin, "setGlobalOrigin");
module3.exports = {
getGlobalOrigin,
setGlobalOrigin
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/data-url.js
var require_data_url = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/data-url.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var encoder = new TextEncoder();
var HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/;
var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/;
var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g;
var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;
function dataURLProcessor(dataURL) {
assert44(dataURL.protocol === "data:");
let input = URLSerializer(dataURL, true);
input = input.slice(5);
const position = { position: 0 };
let mimeType = collectASequenceOfCodePointsFast(
",",
input,
position
);
const mimeTypeLength = mimeType.length;
mimeType = removeASCIIWhitespace(mimeType, true, true);
if (position.position >= input.length) {
return "failure";
}
position.position++;
const encodedBody = input.slice(mimeTypeLength + 1);
let body = stringPercentDecode(encodedBody);
if (/;(\u0020){0,}base64$/i.test(mimeType)) {
const stringBody = isomorphicDecode(body);
body = forgivingBase64(stringBody);
if (body === "failure") {
return "failure";
}
mimeType = mimeType.slice(0, -6);
mimeType = mimeType.replace(/(\u0020)+$/, "");
mimeType = mimeType.slice(0, -1);
}
if (mimeType.startsWith(";")) {
mimeType = "text/plain" + mimeType;
}
let mimeTypeRecord = parseMIMEType(mimeType);
if (mimeTypeRecord === "failure") {
mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII");
}
return { mimeType: mimeTypeRecord, body };
}
__name(dataURLProcessor, "dataURLProcessor");
function URLSerializer(url4, excludeFragment = false) {
if (!excludeFragment) {
return url4.href;
}
const href = url4.href;
const hashLength = url4.hash.length;
const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength);
if (!hashLength && href.endsWith("#")) {
return serialized.slice(0, -1);
}
return serialized;
}
__name(URLSerializer, "URLSerializer");
function collectASequenceOfCodePoints(condition, input, position) {
let result = "";
while (position.position < input.length && condition(input[position.position])) {
result += input[position.position];
position.position++;
}
return result;
}
__name(collectASequenceOfCodePoints, "collectASequenceOfCodePoints");
function collectASequenceOfCodePointsFast(char, input, position) {
const idx = input.indexOf(char, position.position);
const start = position.position;
if (idx === -1) {
position.position = input.length;
return input.slice(start);
}
position.position = idx;
return input.slice(start, position.position);
}
__name(collectASequenceOfCodePointsFast, "collectASequenceOfCodePointsFast");
function stringPercentDecode(input) {
const bytes = encoder.encode(input);
return percentDecode(bytes);
}
__name(stringPercentDecode, "stringPercentDecode");
function isHexCharByte(byte) {
return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
}
__name(isHexCharByte, "isHexCharByte");
function hexByteToNumber(byte) {
return (
// 0-9
byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55
);
}
__name(hexByteToNumber, "hexByteToNumber");
function percentDecode(input) {
const length = input.length;
const output = new Uint8Array(length);
let j6 = 0;
for (let i5 = 0; i5 < length; ++i5) {
const byte = input[i5];
if (byte !== 37) {
output[j6++] = byte;
} else if (byte === 37 && !(isHexCharByte(input[i5 + 1]) && isHexCharByte(input[i5 + 2]))) {
output[j6++] = 37;
} else {
output[j6++] = hexByteToNumber(input[i5 + 1]) << 4 | hexByteToNumber(input[i5 + 2]);
i5 += 2;
}
}
return length === j6 ? output : output.subarray(0, j6);
}
__name(percentDecode, "percentDecode");
function parseMIMEType(input) {
input = removeHTTPWhitespace(input, true, true);
const position = { position: 0 };
const type = collectASequenceOfCodePointsFast(
"/",
input,
position
);
if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
return "failure";
}
if (position.position >= input.length) {
return "failure";
}
position.position++;
let subtype = collectASequenceOfCodePointsFast(
";",
input,
position
);
subtype = removeHTTPWhitespace(subtype, false, true);
if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
return "failure";
}
const typeLowercase = type.toLowerCase();
const subtypeLowercase = subtype.toLowerCase();
const mimeType = {
type: typeLowercase,
subtype: subtypeLowercase,
/** @type {Map<string, string>} */
parameters: /* @__PURE__ */ new Map(),
// https://mimesniff.spec.whatwg.org/#mime-type-essence
essence: `${typeLowercase}/${subtypeLowercase}`
};
while (position.position < input.length) {
position.position++;
collectASequenceOfCodePoints(
// https://fetch.spec.whatwg.org/#http-whitespace
(char) => HTTP_WHITESPACE_REGEX.test(char),
input,
position
);
let parameterName = collectASequenceOfCodePoints(
(char) => char !== ";" && char !== "=",
input,
position
);
parameterName = parameterName.toLowerCase();
if (position.position < input.length) {
if (input[position.position] === ";") {
continue;
}
position.position++;
}
if (position.position >= input.length) {
break;
}
let parameterValue = null;
if (input[position.position] === '"') {
parameterValue = collectAnHTTPQuotedString(input, position, true);
collectASequenceOfCodePointsFast(
";",
input,
position
);
} else {
parameterValue = collectASequenceOfCodePointsFast(
";",
input,
position
);
parameterValue = removeHTTPWhitespace(parameterValue, false, true);
if (parameterValue.length === 0) {
continue;
}
}
if (parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName)) {
mimeType.parameters.set(parameterName, parameterValue);
}
}
return mimeType;
}
__name(parseMIMEType, "parseMIMEType");
function forgivingBase64(data) {
data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, "");
let dataLength = data.length;
if (dataLength % 4 === 0) {
if (data.charCodeAt(dataLength - 1) === 61) {
--dataLength;
if (data.charCodeAt(dataLength - 1) === 61) {
--dataLength;
}
}
}
if (dataLength % 4 === 1) {
return "failure";
}
if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
return "failure";
}
const buffer = Buffer.from(data, "base64");
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
__name(forgivingBase64, "forgivingBase64");
function collectAnHTTPQuotedString(input, position, extractValue = false) {
const positionStart = position.position;
let value = "";
assert44(input[position.position] === '"');
position.position++;
while (true) {
value += collectASequenceOfCodePoints(
(char) => char !== '"' && char !== "\\",
input,
position
);
if (position.position >= input.length) {
break;
}
const quoteOrBackslash = input[position.position];
position.position++;
if (quoteOrBackslash === "\\") {
if (position.position >= input.length) {
value += "\\";
break;
}
value += input[position.position];
position.position++;
} else {
assert44(quoteOrBackslash === '"');
break;
}
}
if (extractValue) {
return value;
}
return input.slice(positionStart, position.position);
}
__name(collectAnHTTPQuotedString, "collectAnHTTPQuotedString");
function serializeAMimeType(mimeType) {
assert44(mimeType !== "failure");
const { parameters, essence } = mimeType;
let serialization = essence;
for (let [name2, value] of parameters.entries()) {
serialization += ";";
serialization += name2;
serialization += "=";
if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
value = value.replace(/(\\|")/g, "\\$1");
value = '"' + value;
value += '"';
}
serialization += value;
}
return serialization;
}
__name(serializeAMimeType, "serializeAMimeType");
function isHTTPWhiteSpace(char) {
return char === 13 || char === 10 || char === 9 || char === 32;
}
__name(isHTTPWhiteSpace, "isHTTPWhiteSpace");
function removeHTTPWhitespace(str, leading = true, trailing = true) {
return removeChars(str, leading, trailing, isHTTPWhiteSpace);
}
__name(removeHTTPWhitespace, "removeHTTPWhitespace");
function isASCIIWhitespace(char) {
return char === 13 || char === 10 || char === 9 || char === 12 || char === 32;
}
__name(isASCIIWhitespace, "isASCIIWhitespace");
function removeASCIIWhitespace(str, leading = true, trailing = true) {
return removeChars(str, leading, trailing, isASCIIWhitespace);
}
__name(removeASCIIWhitespace, "removeASCIIWhitespace");
function removeChars(str, leading, trailing, predicate) {
let lead = 0;
let trail = str.length - 1;
if (leading) {
while (lead < str.length && predicate(str.charCodeAt(lead))) lead++;
}
if (trailing) {
while (trail > 0 && predicate(str.charCodeAt(trail))) trail--;
}
return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1);
}
__name(removeChars, "removeChars");
function isomorphicDecode(input) {
const length = input.length;
if ((2 << 15) - 1 > length) {
return String.fromCharCode.apply(null, input);
}
let result = "";
let i5 = 0;
let addition = (2 << 15) - 1;
while (i5 < length) {
if (i5 + addition > length) {
addition = length - i5;
}
result += String.fromCharCode.apply(null, input.subarray(i5, i5 += addition));
}
return result;
}
__name(isomorphicDecode, "isomorphicDecode");
function minimizeSupportedMimeType(mimeType) {
switch (mimeType.essence) {
case "application/ecmascript":
case "application/javascript":
case "application/x-ecmascript":
case "application/x-javascript":
case "text/ecmascript":
case "text/javascript":
case "text/javascript1.0":
case "text/javascript1.1":
case "text/javascript1.2":
case "text/javascript1.3":
case "text/javascript1.4":
case "text/javascript1.5":
case "text/jscript":
case "text/livescript":
case "text/x-ecmascript":
case "text/x-javascript":
return "text/javascript";
case "application/json":
case "text/json":
return "application/json";
case "image/svg+xml":
return "image/svg+xml";
case "text/xml":
case "application/xml":
return "application/xml";
}
if (mimeType.subtype.endsWith("+json")) {
return "application/json";
}
if (mimeType.subtype.endsWith("+xml")) {
return "application/xml";
}
return "";
}
__name(minimizeSupportedMimeType, "minimizeSupportedMimeType");
module3.exports = {
dataURLProcessor,
URLSerializer,
collectASequenceOfCodePoints,
collectASequenceOfCodePointsFast,
stringPercentDecode,
parseMIMEType,
collectAnHTTPQuotedString,
serializeAMimeType,
removeChars,
removeHTTPWhitespace,
minimizeSupportedMimeType,
HTTP_TOKEN_CODEPOINTS,
isomorphicDecode
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/webidl/index.js
var require_webidl = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/webidl/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { types: types3, inspect: inspect2 } = require("util");
var { markAsUncloneable } = require("worker_threads");
var UNDEFINED = 1;
var BOOLEAN = 2;
var STRING = 3;
var SYMBOL = 4;
var NUMBER = 5;
var BIGINT = 6;
var NULL = 7;
var OBJECT = 8;
var FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]);
var webidl = {
converters: {},
util: {},
errors: {},
is: {}
};
webidl.errors.exception = function(message) {
return new TypeError(`${message.header}: ${message.message}`);
};
webidl.errors.conversionFailed = function(opts) {
const plural2 = opts.types.length === 1 ? "" : " one of";
const message = `${opts.argument} could not be converted to${plural2}: ${opts.types.join(", ")}.`;
return webidl.errors.exception({
header: opts.prefix,
message
});
};
webidl.errors.invalidArgument = function(context2) {
return webidl.errors.exception({
header: context2.prefix,
message: `"${context2.value}" is an invalid ${context2.type}.`
});
};
webidl.brandCheck = function(V3, I4) {
if (!FunctionPrototypeSymbolHasInstance(I4, V3)) {
const err = new TypeError("Illegal invocation");
err.code = "ERR_INVALID_THIS";
throw err;
}
};
webidl.brandCheckMultiple = function(List2) {
const prototypes = List2.map((c6) => webidl.util.MakeTypeAssertion(c6));
return (V3) => {
if (prototypes.every((typeCheck) => !typeCheck(V3))) {
const err = new TypeError("Illegal invocation");
err.code = "ERR_INVALID_THIS";
throw err;
}
};
};
webidl.argumentLengthCheck = function({ length }, min, ctx) {
if (length < min) {
throw webidl.errors.exception({
message: `${min} argument${min !== 1 ? "s" : ""} required, but${length ? " only" : ""} ${length} found.`,
header: ctx
});
}
};
webidl.illegalConstructor = function() {
throw webidl.errors.exception({
header: "TypeError",
message: "Illegal constructor"
});
};
webidl.util.MakeTypeAssertion = function(I4) {
return (O3) => FunctionPrototypeSymbolHasInstance(I4, O3);
};
webidl.util.Type = function(V3) {
switch (typeof V3) {
case "undefined":
return UNDEFINED;
case "boolean":
return BOOLEAN;
case "string":
return STRING;
case "symbol":
return SYMBOL;
case "number":
return NUMBER;
case "bigint":
return BIGINT;
case "function":
case "object": {
if (V3 === null) {
return NULL;
}
return OBJECT;
}
}
};
webidl.util.Types = {
UNDEFINED,
BOOLEAN,
STRING,
SYMBOL,
NUMBER,
BIGINT,
NULL,
OBJECT
};
webidl.util.TypeValueToString = function(o5) {
switch (webidl.util.Type(o5)) {
case UNDEFINED:
return "Undefined";
case BOOLEAN:
return "Boolean";
case STRING:
return "String";
case SYMBOL:
return "Symbol";
case NUMBER:
return "Number";
case BIGINT:
return "BigInt";
case NULL:
return "Null";
case OBJECT:
return "Object";
}
};
webidl.util.markAsUncloneable = markAsUncloneable || (() => {
});
webidl.util.ConvertToInt = function(V3, bitLength, signedness, opts) {
let upperBound;
let lowerBound2;
if (bitLength === 64) {
upperBound = Math.pow(2, 53) - 1;
if (signedness === "unsigned") {
lowerBound2 = 0;
} else {
lowerBound2 = Math.pow(-2, 53) + 1;
}
} else if (signedness === "unsigned") {
lowerBound2 = 0;
upperBound = Math.pow(2, bitLength) - 1;
} else {
lowerBound2 = Math.pow(-2, bitLength) - 1;
upperBound = Math.pow(2, bitLength - 1) - 1;
}
let x6 = Number(V3);
if (x6 === 0) {
x6 = 0;
}
if (opts?.enforceRange === true) {
if (Number.isNaN(x6) || x6 === Number.POSITIVE_INFINITY || x6 === Number.NEGATIVE_INFINITY) {
throw webidl.errors.exception({
header: "Integer conversion",
message: `Could not convert ${webidl.util.Stringify(V3)} to an integer.`
});
}
x6 = webidl.util.IntegerPart(x6);
if (x6 < lowerBound2 || x6 > upperBound) {
throw webidl.errors.exception({
header: "Integer conversion",
message: `Value must be between ${lowerBound2}-${upperBound}, got ${x6}.`
});
}
return x6;
}
if (!Number.isNaN(x6) && opts?.clamp === true) {
x6 = Math.min(Math.max(x6, lowerBound2), upperBound);
if (Math.floor(x6) % 2 === 0) {
x6 = Math.floor(x6);
} else {
x6 = Math.ceil(x6);
}
return x6;
}
if (Number.isNaN(x6) || x6 === 0 && Object.is(0, x6) || x6 === Number.POSITIVE_INFINITY || x6 === Number.NEGATIVE_INFINITY) {
return 0;
}
x6 = webidl.util.IntegerPart(x6);
x6 = x6 % Math.pow(2, bitLength);
if (signedness === "signed" && x6 >= Math.pow(2, bitLength) - 1) {
return x6 - Math.pow(2, bitLength);
}
return x6;
};
webidl.util.IntegerPart = function(n6) {
const r7 = Math.floor(Math.abs(n6));
if (n6 < 0) {
return -1 * r7;
}
return r7;
};
webidl.util.Stringify = function(V3) {
const type = webidl.util.Type(V3);
switch (type) {
case SYMBOL:
return `Symbol(${V3.description})`;
case OBJECT:
return inspect2(V3);
case STRING:
return `"${V3}"`;
case BIGINT:
return `${V3}n`;
default:
return `${V3}`;
}
};
webidl.sequenceConverter = function(converter) {
return (V3, prefix, argument, Iterable) => {
if (webidl.util.Type(V3) !== OBJECT) {
throw webidl.errors.exception({
header: prefix,
message: `${argument} (${webidl.util.Stringify(V3)}) is not iterable.`
});
}
const method = typeof Iterable === "function" ? Iterable() : V3?.[Symbol.iterator]?.();
const seq = [];
let index = 0;
if (method === void 0 || typeof method.next !== "function") {
throw webidl.errors.exception({
header: prefix,
message: `${argument} is not iterable.`
});
}
while (true) {
const { done, value } = method.next();
if (done) {
break;
}
seq.push(converter(value, prefix, `${argument}[${index++}]`));
}
return seq;
};
};
webidl.recordConverter = function(keyConverter, valueConverter) {
return (O3, prefix, argument) => {
if (webidl.util.Type(O3) !== OBJECT) {
throw webidl.errors.exception({
header: prefix,
message: `${argument} ("${webidl.util.TypeValueToString(O3)}") is not an Object.`
});
}
const result = {};
if (!types3.isProxy(O3)) {
const keys2 = [...Object.getOwnPropertyNames(O3), ...Object.getOwnPropertySymbols(O3)];
for (const key of keys2) {
const keyName = webidl.util.Stringify(key);
const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`);
const typedValue = valueConverter(O3[key], prefix, `${argument}[${keyName}]`);
result[typedKey] = typedValue;
}
return result;
}
const keys = Reflect.ownKeys(O3);
for (const key of keys) {
const desc = Reflect.getOwnPropertyDescriptor(O3, key);
if (desc?.enumerable) {
const typedKey = keyConverter(key, prefix, argument);
const typedValue = valueConverter(O3[key], prefix, argument);
result[typedKey] = typedValue;
}
}
return result;
};
};
webidl.interfaceConverter = function(TypeCheck, name2) {
return (V3, prefix, argument) => {
if (!TypeCheck(V3)) {
throw webidl.errors.exception({
header: prefix,
message: `Expected ${argument} ("${webidl.util.Stringify(V3)}") to be an instance of ${name2}.`
});
}
return V3;
};
};
webidl.dictionaryConverter = function(converters) {
return (dictionary, prefix, argument) => {
const dict = {};
if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
throw webidl.errors.exception({
header: prefix,
message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
});
}
for (const options of converters) {
const { key, defaultValue, required, converter } = options;
if (required === true) {
if (dictionary == null || !Object.hasOwn(dictionary, key)) {
throw webidl.errors.exception({
header: prefix,
message: `Missing required key "${key}".`
});
}
}
let value = dictionary?.[key];
const hasDefault = defaultValue !== void 0;
if (hasDefault && value === void 0) {
value = defaultValue();
}
if (required || hasDefault || value !== void 0) {
value = converter(value, prefix, `${argument}.${key}`);
if (options.allowedValues && !options.allowedValues.includes(value)) {
throw webidl.errors.exception({
header: prefix,
message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(", ")}.`
});
}
dict[key] = value;
}
}
return dict;
};
};
webidl.nullableConverter = function(converter) {
return (V3, prefix, argument) => {
if (V3 === null) {
return V3;
}
return converter(V3, prefix, argument);
};
};
webidl.is.USVString = function(value) {
return typeof value === "string" && value.isWellFormed();
};
webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream);
webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob);
webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams);
webidl.is.File = webidl.util.MakeTypeAssertion(globalThis.File ?? require("buffer").File);
webidl.is.URL = webidl.util.MakeTypeAssertion(URL);
webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal);
webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort);
webidl.converters.DOMString = function(V3, prefix, argument, opts) {
if (V3 === null && opts?.legacyNullToEmptyString) {
return "";
}
if (typeof V3 === "symbol") {
throw webidl.errors.exception({
header: prefix,
message: `${argument} is a symbol, which cannot be converted to a DOMString.`
});
}
return String(V3);
};
webidl.converters.ByteString = function(V3, prefix, argument) {
if (typeof V3 === "symbol") {
throw webidl.errors.exception({
header: prefix,
message: `${argument} is a symbol, which cannot be converted to a ByteString.`
});
}
const x6 = String(V3);
for (let index = 0; index < x6.length; index++) {
if (x6.charCodeAt(index) > 255) {
throw new TypeError(
`Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x6.charCodeAt(index)} which is greater than 255.`
);
}
}
return x6;
};
webidl.converters.USVString = function(value) {
if (typeof value === "string") {
return value.toWellFormed();
}
return `${value}`.toWellFormed();
};
webidl.converters.boolean = function(V3) {
const x6 = Boolean(V3);
return x6;
};
webidl.converters.any = function(V3) {
return V3;
};
webidl.converters["long long"] = function(V3, prefix, argument) {
const x6 = webidl.util.ConvertToInt(V3, 64, "signed", void 0, prefix, argument);
return x6;
};
webidl.converters["unsigned long long"] = function(V3, prefix, argument) {
const x6 = webidl.util.ConvertToInt(V3, 64, "unsigned", void 0, prefix, argument);
return x6;
};
webidl.converters["unsigned long"] = function(V3, prefix, argument) {
const x6 = webidl.util.ConvertToInt(V3, 32, "unsigned", void 0, prefix, argument);
return x6;
};
webidl.converters["unsigned short"] = function(V3, prefix, argument, opts) {
const x6 = webidl.util.ConvertToInt(V3, 16, "unsigned", opts, prefix, argument);
return x6;
};
webidl.converters.ArrayBuffer = function(V3, prefix, argument, opts) {
if (webidl.util.Type(V3) !== OBJECT || !types3.isAnyArrayBuffer(V3)) {
throw webidl.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl.util.Stringify(V3)}")`,
types: ["ArrayBuffer"]
});
}
if (opts?.allowShared === false && types3.isSharedArrayBuffer(V3)) {
throw webidl.errors.exception({
header: "ArrayBuffer",
message: "SharedArrayBuffer is not allowed."
});
}
if (V3.resizable || V3.growable) {
throw webidl.errors.exception({
header: "ArrayBuffer",
message: "Received a resizable ArrayBuffer."
});
}
return V3;
};
webidl.converters.TypedArray = function(V3, T3, prefix, name2, opts) {
if (webidl.util.Type(V3) !== OBJECT || !types3.isTypedArray(V3) || V3.constructor.name !== T3.name) {
throw webidl.errors.conversionFailed({
prefix,
argument: `${name2} ("${webidl.util.Stringify(V3)}")`,
types: [T3.name]
});
}
if (opts?.allowShared === false && types3.isSharedArrayBuffer(V3.buffer)) {
throw webidl.errors.exception({
header: "ArrayBuffer",
message: "SharedArrayBuffer is not allowed."
});
}
if (V3.buffer.resizable || V3.buffer.growable) {
throw webidl.errors.exception({
header: "ArrayBuffer",
message: "Received a resizable ArrayBuffer."
});
}
return V3;
};
webidl.converters.DataView = function(V3, prefix, name2, opts) {
if (webidl.util.Type(V3) !== OBJECT || !types3.isDataView(V3)) {
throw webidl.errors.exception({
header: prefix,
message: `${name2} is not a DataView.`
});
}
if (opts?.allowShared === false && types3.isSharedArrayBuffer(V3.buffer)) {
throw webidl.errors.exception({
header: "ArrayBuffer",
message: "SharedArrayBuffer is not allowed."
});
}
if (V3.buffer.resizable || V3.buffer.growable) {
throw webidl.errors.exception({
header: "ArrayBuffer",
message: "Received a resizable ArrayBuffer."
});
}
return V3;
};
webidl.converters["sequence<ByteString>"] = webidl.sequenceConverter(
webidl.converters.ByteString
);
webidl.converters["sequence<sequence<ByteString>>"] = webidl.sequenceConverter(
webidl.converters["sequence<ByteString>"]
);
webidl.converters["record<ByteString, ByteString>"] = webidl.recordConverter(
webidl.converters.ByteString,
webidl.converters.ByteString
);
webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, "Blob");
webidl.converters.AbortSignal = webidl.interfaceConverter(
webidl.is.AbortSignal,
"AbortSignal"
);
module3.exports = {
webidl
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/util.js
var require_util2 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Transform: Transform2 } = require("stream");
var zlib2 = require("zlib");
var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants3();
var { getGlobalOrigin } = require_global();
var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url();
var { performance: performance2 } = require("perf_hooks");
var { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
var assert44 = require("assert");
var { isUint8Array } = require("util/types");
var { webidl } = require_webidl();
var supportedHashes = [];
var crypto8;
try {
crypto8 = require("crypto");
const possibleRelevantHashes = ["sha256", "sha384", "sha512"];
supportedHashes = crypto8.getHashes().filter((hash) => possibleRelevantHashes.includes(hash));
} catch {
}
function responseURL(response) {
const urlList = response.urlList;
const length = urlList.length;
return length === 0 ? null : urlList[length - 1].toString();
}
__name(responseURL, "responseURL");
function responseLocationURL(response, requestFragment) {
if (!redirectStatusSet.has(response.status)) {
return null;
}
let location = response.headersList.get("location", true);
if (location !== null && isValidHeaderValue(location)) {
if (!isValidEncodedURL(location)) {
location = normalizeBinaryStringToUtf8(location);
}
location = new URL(location, responseURL(response));
}
if (location && !location.hash) {
location.hash = requestFragment;
}
return location;
}
__name(responseLocationURL, "responseLocationURL");
function isValidEncodedURL(url4) {
for (let i5 = 0; i5 < url4.length; ++i5) {
const code = url4.charCodeAt(i5);
if (code > 126 || // Non-US-ASCII + DEL
code < 32) {
return false;
}
}
return true;
}
__name(isValidEncodedURL, "isValidEncodedURL");
function normalizeBinaryStringToUtf8(value) {
return Buffer.from(value, "binary").toString("utf8");
}
__name(normalizeBinaryStringToUtf8, "normalizeBinaryStringToUtf8");
function requestCurrentURL(request4) {
return request4.urlList[request4.urlList.length - 1];
}
__name(requestCurrentURL, "requestCurrentURL");
function requestBadPort(request4) {
const url4 = requestCurrentURL(request4);
if (urlIsHttpHttpsScheme(url4) && badPortsSet.has(url4.port)) {
return "blocked";
}
return "allowed";
}
__name(requestBadPort, "requestBadPort");
function isErrorLike(object) {
return object instanceof Error || (object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException");
}
__name(isErrorLike, "isErrorLike");
function isValidReasonPhrase(statusText) {
for (let i5 = 0; i5 < statusText.length; ++i5) {
const c6 = statusText.charCodeAt(i5);
if (!(c6 === 9 || // HTAB
c6 >= 32 && c6 <= 126 || // SP / VCHAR
c6 >= 128 && c6 <= 255)) {
return false;
}
}
return true;
}
__name(isValidReasonPhrase, "isValidReasonPhrase");
var isValidHeaderName = isValidHTTPToken;
function isValidHeaderValue(potentialValue) {
return (potentialValue[0] === " " || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false;
}
__name(isValidHeaderValue, "isValidHeaderValue");
function parseReferrerPolicy(actualResponse) {
const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(",");
let policy = "";
if (policyHeader.length) {
for (let i5 = policyHeader.length; i5 !== 0; i5--) {
const token = policyHeader[i5 - 1].trim();
if (referrerPolicyTokens.has(token)) {
policy = token;
break;
}
}
}
return policy;
}
__name(parseReferrerPolicy, "parseReferrerPolicy");
function setRequestReferrerPolicyOnRedirect(request4, actualResponse) {
const policy = parseReferrerPolicy(actualResponse);
if (policy !== "") {
request4.referrerPolicy = policy;
}
}
__name(setRequestReferrerPolicyOnRedirect, "setRequestReferrerPolicyOnRedirect");
function crossOriginResourcePolicyCheck() {
return "allowed";
}
__name(crossOriginResourcePolicyCheck, "crossOriginResourcePolicyCheck");
function corsCheck() {
return "success";
}
__name(corsCheck, "corsCheck");
function TAOCheck() {
return "success";
}
__name(TAOCheck, "TAOCheck");
function appendFetchMetadata(httpRequest2) {
let header = null;
header = httpRequest2.mode;
httpRequest2.headersList.set("sec-fetch-mode", header, true);
}
__name(appendFetchMetadata, "appendFetchMetadata");
function appendRequestOriginHeader(request4) {
let serializedOrigin = request4.origin;
if (serializedOrigin === "client" || serializedOrigin === void 0) {
return;
}
if (request4.responseTainting === "cors" || request4.mode === "websocket") {
request4.headersList.append("origin", serializedOrigin, true);
} else if (request4.method !== "GET" && request4.method !== "HEAD") {
switch (request4.referrerPolicy) {
case "no-referrer":
serializedOrigin = null;
break;
case "no-referrer-when-downgrade":
case "strict-origin":
case "strict-origin-when-cross-origin":
if (request4.origin && urlHasHttpsScheme(request4.origin) && !urlHasHttpsScheme(requestCurrentURL(request4))) {
serializedOrigin = null;
}
break;
case "same-origin":
if (!sameOrigin(request4, requestCurrentURL(request4))) {
serializedOrigin = null;
}
break;
default:
}
request4.headersList.append("origin", serializedOrigin, true);
}
}
__name(appendRequestOriginHeader, "appendRequestOriginHeader");
function coarsenTime(timestamp, crossOriginIsolatedCapability) {
return timestamp;
}
__name(coarsenTime, "coarsenTime");
function clampAndCoarsenConnectionTimingInfo(connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
return {
domainLookupStartTime: defaultStartTime,
domainLookupEndTime: defaultStartTime,
connectionStartTime: defaultStartTime,
connectionEndTime: defaultStartTime,
secureConnectionStartTime: defaultStartTime,
ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
};
}
return {
domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
};
}
__name(clampAndCoarsenConnectionTimingInfo, "clampAndCoarsenConnectionTimingInfo");
function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
return coarsenTime(performance2.now(), crossOriginIsolatedCapability);
}
__name(coarsenedSharedCurrentTime, "coarsenedSharedCurrentTime");
function createOpaqueTimingInfo(timingInfo) {
return {
startTime: timingInfo.startTime ?? 0,
redirectStartTime: 0,
redirectEndTime: 0,
postRedirectStartTime: timingInfo.startTime ?? 0,
finalServiceWorkerStartTime: 0,
finalNetworkResponseStartTime: 0,
finalNetworkRequestStartTime: 0,
endTime: 0,
encodedBodySize: 0,
decodedBodySize: 0,
finalConnectionTimingInfo: null
};
}
__name(createOpaqueTimingInfo, "createOpaqueTimingInfo");
function makePolicyContainer() {
return {
referrerPolicy: "strict-origin-when-cross-origin"
};
}
__name(makePolicyContainer, "makePolicyContainer");
function clonePolicyContainer(policyContainer) {
return {
referrerPolicy: policyContainer.referrerPolicy
};
}
__name(clonePolicyContainer, "clonePolicyContainer");
function determineRequestsReferrer(request4) {
const policy = request4.referrerPolicy;
assert44(policy);
let referrerSource = null;
if (request4.referrer === "client") {
const globalOrigin = getGlobalOrigin();
if (!globalOrigin || globalOrigin.origin === "null") {
return "no-referrer";
}
referrerSource = new URL(globalOrigin);
} else if (webidl.is.URL(request4.referrer)) {
referrerSource = request4.referrer;
}
let referrerURL = stripURLForReferrer(referrerSource);
const referrerOrigin = stripURLForReferrer(referrerSource, true);
if (referrerURL.toString().length > 4096) {
referrerURL = referrerOrigin;
}
switch (policy) {
case "no-referrer":
return "no-referrer";
case "origin":
if (referrerOrigin != null) {
return referrerOrigin;
}
return stripURLForReferrer(referrerSource, true);
case "unsafe-url":
return referrerURL;
case "strict-origin": {
const currentURL = requestCurrentURL(request4);
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
return "no-referrer";
}
return referrerOrigin;
}
case "strict-origin-when-cross-origin": {
const currentURL = requestCurrentURL(request4);
if (sameOrigin(referrerURL, currentURL)) {
return referrerURL;
}
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
return "no-referrer";
}
return referrerOrigin;
}
case "same-origin":
if (sameOrigin(request4, referrerURL)) {
return referrerURL;
}
return "no-referrer";
case "origin-when-cross-origin":
if (sameOrigin(request4, referrerURL)) {
return referrerURL;
}
return referrerOrigin;
case "no-referrer-when-downgrade": {
const currentURL = requestCurrentURL(request4);
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
return "no-referrer";
}
return referrerOrigin;
}
}
}
__name(determineRequestsReferrer, "determineRequestsReferrer");
function stripURLForReferrer(url4, originOnly = false) {
assert44(webidl.is.URL(url4));
url4 = new URL(url4);
if (urlIsLocal(url4)) {
return "no-referrer";
}
url4.username = "";
url4.password = "";
url4.hash = "";
if (originOnly === true) {
url4.pathname = "";
url4.search = "";
}
return url4;
}
__name(stripURLForReferrer, "stripURLForReferrer");
var potentialleTrustworthyIPv4RegExp = new RegExp("^(?:(?:127\\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9]))$");
var potentialleTrustworthyIPv6RegExp = new RegExp("^(?:(?:(?:0{1,4}):){7}(?:(?:0{0,3}1))|(?:(?:0{1,4}):){1,6}(?::(?:0{0,3}1))|(?:::(?:0{0,3}1))|)$");
function isOriginIPPotentiallyTrustworthy(origin) {
if (origin.includes(":")) {
if (origin[0] === "[" && origin[origin.length - 1] === "]") {
origin = origin.slice(1, -1);
}
return potentialleTrustworthyIPv6RegExp.test(origin);
}
return potentialleTrustworthyIPv4RegExp.test(origin);
}
__name(isOriginIPPotentiallyTrustworthy, "isOriginIPPotentiallyTrustworthy");
function isOriginPotentiallyTrustworthy(origin) {
if (origin == null || origin === "null") {
return false;
}
origin = new URL(origin);
if (origin.protocol === "https:" || origin.protocol === "wss:") {
return true;
}
if (isOriginIPPotentiallyTrustworthy(origin.hostname)) {
return true;
}
if (origin.hostname === "localhost" || origin.hostname === "localhost.") {
return true;
}
if (origin.hostname.endsWith(".localhost") || origin.hostname.endsWith(".localhost.")) {
return true;
}
if (origin.protocol === "file:") {
return true;
}
return false;
}
__name(isOriginPotentiallyTrustworthy, "isOriginPotentiallyTrustworthy");
function isURLPotentiallyTrustworthy(url4) {
if (!webidl.is.URL(url4)) {
return false;
}
if (url4.href === "about:blank" || url4.href === "about:srcdoc") {
return true;
}
if (url4.protocol === "data:") return true;
if (url4.protocol === "blob:") return true;
return isOriginPotentiallyTrustworthy(url4.origin);
}
__name(isURLPotentiallyTrustworthy, "isURLPotentiallyTrustworthy");
function bytesMatch(bytes, metadataList) {
if (crypto8 === void 0) {
return true;
}
const parsedMetadata = parseMetadata(metadataList);
if (parsedMetadata === "no metadata") {
return true;
}
if (parsedMetadata.length === 0) {
return true;
}
const strongest = getStrongestMetadata(parsedMetadata);
const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest);
for (const item of metadata) {
const algorithm = item.algo;
const expectedValue = item.hash;
let actualValue = crypto8.createHash(algorithm).update(bytes).digest("base64");
if (actualValue[actualValue.length - 1] === "=") {
if (actualValue[actualValue.length - 2] === "=") {
actualValue = actualValue.slice(0, -2);
} else {
actualValue = actualValue.slice(0, -1);
}
}
if (compareBase64Mixed(actualValue, expectedValue)) {
return true;
}
}
return false;
}
__name(bytesMatch, "bytesMatch");
var parseHashWithOptions = /(?<algo>sha256|sha384|sha512)-((?<hash>[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i;
function parseMetadata(metadata) {
const result = [];
let empty2 = true;
for (const token of metadata.split(" ")) {
empty2 = false;
const parsedToken = parseHashWithOptions.exec(token);
if (parsedToken === null || parsedToken.groups === void 0 || parsedToken.groups.algo === void 0) {
continue;
}
const algorithm = parsedToken.groups.algo.toLowerCase();
if (supportedHashes.includes(algorithm)) {
result.push(parsedToken.groups);
}
}
if (empty2 === true) {
return "no metadata";
}
return result;
}
__name(parseMetadata, "parseMetadata");
function getStrongestMetadata(metadataList) {
let algorithm = metadataList[0].algo;
if (algorithm[3] === "5") {
return algorithm;
}
for (let i5 = 1; i5 < metadataList.length; ++i5) {
const metadata = metadataList[i5];
if (metadata.algo[3] === "5") {
algorithm = "sha512";
break;
} else if (algorithm[3] === "3") {
continue;
} else if (metadata.algo[3] === "3") {
algorithm = "sha384";
}
}
return algorithm;
}
__name(getStrongestMetadata, "getStrongestMetadata");
function filterMetadataListByAlgorithm(metadataList, algorithm) {
if (metadataList.length === 1) {
return metadataList;
}
let pos = 0;
for (let i5 = 0; i5 < metadataList.length; ++i5) {
if (metadataList[i5].algo === algorithm) {
metadataList[pos++] = metadataList[i5];
}
}
metadataList.length = pos;
return metadataList;
}
__name(filterMetadataListByAlgorithm, "filterMetadataListByAlgorithm");
function compareBase64Mixed(actualValue, expectedValue) {
if (actualValue.length !== expectedValue.length) {
return false;
}
for (let i5 = 0; i5 < actualValue.length; ++i5) {
if (actualValue[i5] !== expectedValue[i5]) {
if (actualValue[i5] === "+" && expectedValue[i5] === "-" || actualValue[i5] === "/" && expectedValue[i5] === "_") {
continue;
}
return false;
}
}
return true;
}
__name(compareBase64Mixed, "compareBase64Mixed");
function tryUpgradeRequestToAPotentiallyTrustworthyURL(request4) {
}
__name(tryUpgradeRequestToAPotentiallyTrustworthyURL, "tryUpgradeRequestToAPotentiallyTrustworthyURL");
function sameOrigin(A3, B3) {
if (A3.origin === B3.origin && A3.origin === "null") {
return true;
}
if (A3.protocol === B3.protocol && A3.hostname === B3.hostname && A3.port === B3.port) {
return true;
}
return false;
}
__name(sameOrigin, "sameOrigin");
function createDeferredPromise() {
let res;
let rej;
const promise = new Promise((resolve25, reject) => {
res = resolve25;
rej = reject;
});
return { promise, resolve: res, reject: rej };
}
__name(createDeferredPromise, "createDeferredPromise");
function isAborted2(fetchParams) {
return fetchParams.controller.state === "aborted";
}
__name(isAborted2, "isAborted");
function isCancelled(fetchParams) {
return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
}
__name(isCancelled, "isCancelled");
function normalizeMethod(method) {
return normalizedMethodRecordsBase[method.toLowerCase()] ?? method;
}
__name(normalizeMethod, "normalizeMethod");
function serializeJavascriptValueToJSONString(value) {
const result = JSON.stringify(value);
if (result === void 0) {
throw new TypeError("Value is not JSON serializable");
}
assert44(typeof result === "string");
return result;
}
__name(serializeJavascriptValueToJSONString, "serializeJavascriptValueToJSONString");
var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
function createIterator(name2, kInternalIterator, keyIndex = 0, valueIndex = 1) {
class FastIterableIterator {
static {
__name(this, "FastIterableIterator");
}
/** @type {any} */
#target;
/** @type {'key' | 'value' | 'key+value'} */
#kind;
/** @type {number} */
#index;
/**
* @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
* @param {unknown} target
* @param {'key' | 'value' | 'key+value'} kind
*/
constructor(target, kind) {
this.#target = target;
this.#kind = kind;
this.#index = 0;
}
next() {
if (typeof this !== "object" || this === null || !(#target in this)) {
throw new TypeError(
`'next' called on an object that does not implement interface ${name2} Iterator.`
);
}
const index = this.#index;
const values = kInternalIterator(this.#target);
const len = values.length;
if (index >= len) {
return {
value: void 0,
done: true
};
}
const { [keyIndex]: key, [valueIndex]: value } = values[index];
this.#index = index + 1;
let result;
switch (this.#kind) {
case "key":
result = key;
break;
case "value":
result = value;
break;
case "key+value":
result = [key, value];
break;
}
return {
value: result,
done: false
};
}
}
delete FastIterableIterator.prototype.constructor;
Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype);
Object.defineProperties(FastIterableIterator.prototype, {
[Symbol.toStringTag]: {
writable: false,
enumerable: false,
configurable: true,
value: `${name2} Iterator`
},
next: { writable: true, enumerable: true, configurable: true }
});
return function(target, kind) {
return new FastIterableIterator(target, kind);
};
}
__name(createIterator, "createIterator");
function iteratorMixin(name2, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
const makeIterator = createIterator(name2, kInternalIterator, keyIndex, valueIndex);
const properties = {
keys: {
writable: true,
enumerable: true,
configurable: true,
value: /* @__PURE__ */ __name(function keys() {
webidl.brandCheck(this, object);
return makeIterator(this, "key");
}, "keys")
},
values: {
writable: true,
enumerable: true,
configurable: true,
value: /* @__PURE__ */ __name(function values() {
webidl.brandCheck(this, object);
return makeIterator(this, "value");
}, "values")
},
entries: {
writable: true,
enumerable: true,
configurable: true,
value: /* @__PURE__ */ __name(function entries() {
webidl.brandCheck(this, object);
return makeIterator(this, "key+value");
}, "entries")
},
forEach: {
writable: true,
enumerable: true,
configurable: true,
value: /* @__PURE__ */ __name(function forEach(callbackfn, thisArg = globalThis) {
webidl.brandCheck(this, object);
webidl.argumentLengthCheck(arguments, 1, `${name2}.forEach`);
if (typeof callbackfn !== "function") {
throw new TypeError(
`Failed to execute 'forEach' on '${name2}': parameter 1 is not of type 'Function'.`
);
}
for (const { 0: key, 1: value } of makeIterator(this, "key+value")) {
callbackfn.call(thisArg, value, key, this);
}
}, "forEach")
}
};
return Object.defineProperties(object.prototype, {
...properties,
[Symbol.iterator]: {
writable: true,
enumerable: false,
configurable: true,
value: properties.entries.value
}
});
}
__name(iteratorMixin, "iteratorMixin");
function fullyReadBody(body, processBody, processBodyError) {
const successSteps = processBody;
const errorSteps = processBodyError;
let reader;
try {
reader = body.stream.getReader();
} catch (e7) {
errorSteps(e7);
return;
}
readAllBytes(reader, successSteps, errorSteps);
}
__name(fullyReadBody, "fullyReadBody");
function readableStreamClose(controller) {
try {
controller.close();
controller.byobRequest?.respond(0);
} catch (err) {
if (!err.message.includes("Controller is already closed") && !err.message.includes("ReadableStream is already closed")) {
throw err;
}
}
}
__name(readableStreamClose, "readableStreamClose");
var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/;
function isomorphicEncode(input) {
assert44(!invalidIsomorphicEncodeValueRegex.test(input));
return input;
}
__name(isomorphicEncode, "isomorphicEncode");
async function readAllBytes(reader, successSteps, failureSteps) {
const bytes = [];
let byteLength = 0;
try {
do {
const { done, value: chunk } = await reader.read();
if (done) {
successSteps(Buffer.concat(bytes, byteLength));
return;
}
if (!isUint8Array(chunk)) {
failureSteps(new TypeError("Received non-Uint8Array chunk"));
return;
}
bytes.push(chunk);
byteLength += chunk.length;
} while (true);
} catch (e7) {
failureSteps(e7);
}
}
__name(readAllBytes, "readAllBytes");
function urlIsLocal(url4) {
assert44("protocol" in url4);
const protocol = url4.protocol;
return protocol === "about:" || protocol === "blob:" || protocol === "data:";
}
__name(urlIsLocal, "urlIsLocal");
function urlHasHttpsScheme(url4) {
return typeof url4 === "string" && url4[5] === ":" && url4[0] === "h" && url4[1] === "t" && url4[2] === "t" && url4[3] === "p" && url4[4] === "s" || url4.protocol === "https:";
}
__name(urlHasHttpsScheme, "urlHasHttpsScheme");
function urlIsHttpHttpsScheme(url4) {
assert44("protocol" in url4);
const protocol = url4.protocol;
return protocol === "http:" || protocol === "https:";
}
__name(urlIsHttpHttpsScheme, "urlIsHttpHttpsScheme");
function simpleRangeHeaderValue(value, allowWhitespace) {
const data = value;
if (!data.startsWith("bytes")) {
return "failure";
}
const position = { position: 5 };
if (allowWhitespace) {
collectASequenceOfCodePoints(
(char) => char === " " || char === " ",
data,
position
);
}
if (data.charCodeAt(position.position) !== 61) {
return "failure";
}
position.position++;
if (allowWhitespace) {
collectASequenceOfCodePoints(
(char) => char === " " || char === " ",
data,
position
);
}
const rangeStart = collectASequenceOfCodePoints(
(char) => {
const code = char.charCodeAt(0);
return code >= 48 && code <= 57;
},
data,
position
);
const rangeStartValue = rangeStart.length ? Number(rangeStart) : null;
if (allowWhitespace) {
collectASequenceOfCodePoints(
(char) => char === " " || char === " ",
data,
position
);
}
if (data.charCodeAt(position.position) !== 45) {
return "failure";
}
position.position++;
if (allowWhitespace) {
collectASequenceOfCodePoints(
(char) => char === " " || char === " ",
data,
position
);
}
const rangeEnd = collectASequenceOfCodePoints(
(char) => {
const code = char.charCodeAt(0);
return code >= 48 && code <= 57;
},
data,
position
);
const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null;
if (position.position < data.length) {
return "failure";
}
if (rangeEndValue === null && rangeStartValue === null) {
return "failure";
}
if (rangeStartValue > rangeEndValue) {
return "failure";
}
return { rangeStartValue, rangeEndValue };
}
__name(simpleRangeHeaderValue, "simpleRangeHeaderValue");
function buildContentRange(rangeStart, rangeEnd, fullLength) {
let contentRange = "bytes ";
contentRange += isomorphicEncode(`${rangeStart}`);
contentRange += "-";
contentRange += isomorphicEncode(`${rangeEnd}`);
contentRange += "/";
contentRange += isomorphicEncode(`${fullLength}`);
return contentRange;
}
__name(buildContentRange, "buildContentRange");
var InflateStream = class extends Transform2 {
static {
__name(this, "InflateStream");
}
#zlibOptions;
/** @param {zlib.ZlibOptions} [zlibOptions] */
constructor(zlibOptions) {
super();
this.#zlibOptions = zlibOptions;
}
_transform(chunk, encoding, callback) {
if (!this._inflateStream) {
if (chunk.length === 0) {
callback();
return;
}
this._inflateStream = (chunk[0] & 15) === 8 ? zlib2.createInflate(this.#zlibOptions) : zlib2.createInflateRaw(this.#zlibOptions);
this._inflateStream.on("data", this.push.bind(this));
this._inflateStream.on("end", () => this.push(null));
this._inflateStream.on("error", (err) => this.destroy(err));
}
this._inflateStream.write(chunk, encoding, callback);
}
_final(callback) {
if (this._inflateStream) {
this._inflateStream.end();
this._inflateStream = null;
}
callback();
}
};
function createInflate(zlibOptions) {
return new InflateStream(zlibOptions);
}
__name(createInflate, "createInflate");
function extractMimeType(headers) {
let charset = null;
let essence = null;
let mimeType = null;
const values = getDecodeSplit("content-type", headers);
if (values === null) {
return "failure";
}
for (const value of values) {
const temporaryMimeType = parseMIMEType(value);
if (temporaryMimeType === "failure" || temporaryMimeType.essence === "*/*") {
continue;
}
mimeType = temporaryMimeType;
if (mimeType.essence !== essence) {
charset = null;
if (mimeType.parameters.has("charset")) {
charset = mimeType.parameters.get("charset");
}
essence = mimeType.essence;
} else if (!mimeType.parameters.has("charset") && charset !== null) {
mimeType.parameters.set("charset", charset);
}
}
if (mimeType == null) {
return "failure";
}
return mimeType;
}
__name(extractMimeType, "extractMimeType");
function gettingDecodingSplitting(value) {
const input = value;
const position = { position: 0 };
const values = [];
let temporaryValue = "";
while (position.position < input.length) {
temporaryValue += collectASequenceOfCodePoints(
(char) => char !== '"' && char !== ",",
input,
position
);
if (position.position < input.length) {
if (input.charCodeAt(position.position) === 34) {
temporaryValue += collectAnHTTPQuotedString(
input,
position
);
if (position.position < input.length) {
continue;
}
} else {
assert44(input.charCodeAt(position.position) === 44);
position.position++;
}
}
temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 9 || char === 32);
values.push(temporaryValue);
temporaryValue = "";
}
return values;
}
__name(gettingDecodingSplitting, "gettingDecodingSplitting");
function getDecodeSplit(name2, list) {
const value = list.get(name2, true);
if (value === null) {
return null;
}
return gettingDecodingSplitting(value);
}
__name(getDecodeSplit, "getDecodeSplit");
var textDecoder = new TextDecoder();
function utf8DecodeBytes(buffer) {
if (buffer.length === 0) {
return "";
}
if (buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) {
buffer = buffer.subarray(3);
}
const output = textDecoder.decode(buffer);
return output;
}
__name(utf8DecodeBytes, "utf8DecodeBytes");
var EnvironmentSettingsObjectBase = class {
static {
__name(this, "EnvironmentSettingsObjectBase");
}
get baseUrl() {
return getGlobalOrigin();
}
get origin() {
return this.baseUrl?.origin;
}
policyContainer = makePolicyContainer();
};
var EnvironmentSettingsObject = class {
static {
__name(this, "EnvironmentSettingsObject");
}
settingsObject = new EnvironmentSettingsObjectBase();
};
var environmentSettingsObject = new EnvironmentSettingsObject();
module3.exports = {
isAborted: isAborted2,
isCancelled,
isValidEncodedURL,
createDeferredPromise,
ReadableStreamFrom,
tryUpgradeRequestToAPotentiallyTrustworthyURL,
clampAndCoarsenConnectionTimingInfo,
coarsenedSharedCurrentTime,
determineRequestsReferrer,
makePolicyContainer,
clonePolicyContainer,
appendFetchMetadata,
appendRequestOriginHeader,
TAOCheck,
corsCheck,
crossOriginResourcePolicyCheck,
createOpaqueTimingInfo,
setRequestReferrerPolicyOnRedirect,
isValidHTTPToken,
requestBadPort,
requestCurrentURL,
responseURL,
responseLocationURL,
isURLPotentiallyTrustworthy,
isValidReasonPhrase,
sameOrigin,
normalizeMethod,
serializeJavascriptValueToJSONString,
iteratorMixin,
createIterator,
isValidHeaderName,
isValidHeaderValue,
isErrorLike,
fullyReadBody,
bytesMatch,
readableStreamClose,
isomorphicEncode,
urlIsLocal,
urlHasHttpsScheme,
urlIsHttpHttpsScheme,
readAllBytes,
simpleRangeHeaderValue,
buildContentRange,
parseMetadata,
createInflate,
extractMimeType,
getDecodeSplit,
utf8DecodeBytes,
environmentSettingsObject,
isOriginIPPotentiallyTrustworthy
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/formdata.js
var require_formdata = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/formdata.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { iteratorMixin } = require_util2();
var { kEnumerableProperty } = require_util();
var { webidl } = require_webidl();
var { File: NativeFile } = require("buffer");
var nodeUtil = require("util");
var File2 = globalThis.File ?? NativeFile;
var FormData11 = class _FormData {
static {
__name(this, "FormData");
}
#state = [];
constructor(form) {
webidl.util.markAsUncloneable(this);
if (form !== void 0) {
throw webidl.errors.conversionFailed({
prefix: "FormData constructor",
argument: "Argument 1",
types: ["undefined"]
});
}
}
append(name2, value, filename = void 0) {
webidl.brandCheck(this, _FormData);
const prefix = "FormData.append";
webidl.argumentLengthCheck(arguments, 2, prefix);
name2 = webidl.converters.USVString(name2);
if (arguments.length === 3 || webidl.is.Blob(value)) {
value = webidl.converters.Blob(value, prefix, "value");
if (filename !== void 0) {
filename = webidl.converters.USVString(filename);
}
} else {
value = webidl.converters.USVString(value);
}
const entry = makeEntry(name2, value, filename);
this.#state.push(entry);
}
delete(name2) {
webidl.brandCheck(this, _FormData);
const prefix = "FormData.delete";
webidl.argumentLengthCheck(arguments, 1, prefix);
name2 = webidl.converters.USVString(name2);
this.#state = this.#state.filter((entry) => entry.name !== name2);
}
get(name2) {
webidl.brandCheck(this, _FormData);
const prefix = "FormData.get";
webidl.argumentLengthCheck(arguments, 1, prefix);
name2 = webidl.converters.USVString(name2);
const idx = this.#state.findIndex((entry) => entry.name === name2);
if (idx === -1) {
return null;
}
return this.#state[idx].value;
}
getAll(name2) {
webidl.brandCheck(this, _FormData);
const prefix = "FormData.getAll";
webidl.argumentLengthCheck(arguments, 1, prefix);
name2 = webidl.converters.USVString(name2);
return this.#state.filter((entry) => entry.name === name2).map((entry) => entry.value);
}
has(name2) {
webidl.brandCheck(this, _FormData);
const prefix = "FormData.has";
webidl.argumentLengthCheck(arguments, 1, prefix);
name2 = webidl.converters.USVString(name2);
return this.#state.findIndex((entry) => entry.name === name2) !== -1;
}
set(name2, value, filename = void 0) {
webidl.brandCheck(this, _FormData);
const prefix = "FormData.set";
webidl.argumentLengthCheck(arguments, 2, prefix);
name2 = webidl.converters.USVString(name2);
if (arguments.length === 3 || webidl.is.Blob(value)) {
value = webidl.converters.Blob(value, prefix, "value");
if (filename !== void 0) {
filename = webidl.converters.USVString(filename);
}
} else {
value = webidl.converters.USVString(value);
}
const entry = makeEntry(name2, value, filename);
const idx = this.#state.findIndex((entry2) => entry2.name === name2);
if (idx !== -1) {
this.#state = [
...this.#state.slice(0, idx),
entry,
...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name2)
];
} else {
this.#state.push(entry);
}
}
[nodeUtil.inspect.custom](depth, options) {
const state2 = this.#state.reduce((a5, b6) => {
if (a5[b6.name]) {
if (Array.isArray(a5[b6.name])) {
a5[b6.name].push(b6.value);
} else {
a5[b6.name] = [a5[b6.name], b6.value];
}
} else {
a5[b6.name] = b6.value;
}
return a5;
}, { __proto__: null });
options.depth ??= depth;
options.colors ??= true;
const output = nodeUtil.formatWithOptions(options, state2);
return `FormData ${output.slice(output.indexOf("]") + 2)}`;
}
/**
* @param {FormData} formData
*/
static getFormDataState(formData) {
return formData.#state;
}
/**
* @param {FormData} formData
* @param {any[]} newState
*/
static setFormDataState(formData, newState) {
formData.#state = newState;
}
};
var { getFormDataState, setFormDataState } = FormData11;
Reflect.deleteProperty(FormData11, "getFormDataState");
Reflect.deleteProperty(FormData11, "setFormDataState");
iteratorMixin("FormData", FormData11, getFormDataState, "name", "value");
Object.defineProperties(FormData11.prototype, {
append: kEnumerableProperty,
delete: kEnumerableProperty,
get: kEnumerableProperty,
getAll: kEnumerableProperty,
has: kEnumerableProperty,
set: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "FormData",
configurable: true
}
});
function makeEntry(name2, value, filename) {
if (typeof value === "string") {
} else {
if (!webidl.is.File(value)) {
value = new File2([value], "blob", { type: value.type });
}
if (filename !== void 0) {
const options = {
type: value.type,
lastModified: value.lastModified
};
value = new File2([value], filename, options);
}
}
return { name: name2, value };
}
__name(makeEntry, "makeEntry");
webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData11);
module3.exports = { FormData: FormData11, makeEntry, setFormDataState };
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/formdata-parser.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { bufferToLowerCasedHeaderName } = require_util();
var { utf8DecodeBytes } = require_util2();
var { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require_data_url();
var { makeEntry } = require_formdata();
var { webidl } = require_webidl();
var assert44 = require("assert");
var { File: NodeFile } = require("buffer");
var File2 = globalThis.File ?? NodeFile;
var formDataNameBuffer = Buffer.from('form-data; name="');
var filenameBuffer = Buffer.from("filename");
var dd = Buffer.from("--");
var ddcrlf = Buffer.from("--\r\n");
function isAsciiString(chars) {
for (let i5 = 0; i5 < chars.length; ++i5) {
if ((chars.charCodeAt(i5) & ~127) !== 0) {
return false;
}
}
return true;
}
__name(isAsciiString, "isAsciiString");
function validateBoundary(boundary) {
const length = boundary.length;
if (length < 27 || length > 70) {
return false;
}
for (let i5 = 0; i5 < length; ++i5) {
const cp3 = boundary.charCodeAt(i5);
if (!(cp3 >= 48 && cp3 <= 57 || cp3 >= 65 && cp3 <= 90 || cp3 >= 97 && cp3 <= 122 || cp3 === 39 || cp3 === 45 || cp3 === 95)) {
return false;
}
}
return true;
}
__name(validateBoundary, "validateBoundary");
function multipartFormDataParser(input, mimeType) {
assert44(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
const boundaryString = mimeType.parameters.get("boundary");
if (boundaryString === void 0) {
throw parsingError("missing boundary in content-type header");
}
const boundary = Buffer.from(`--${boundaryString}`, "utf8");
const entryList = [];
const position = { position: 0 };
while (input[position.position] === 13 && input[position.position + 1] === 10) {
position.position += 2;
}
let trailing = input.length;
while (input[trailing - 1] === 10 && input[trailing - 2] === 13) {
trailing -= 2;
}
if (trailing !== input.length) {
input = input.subarray(0, trailing);
}
while (true) {
if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
position.position += boundary.length;
} else {
throw parsingError("expected a value starting with -- and the boundary");
}
if (position.position === input.length - 2 && bufferStartsWith(input, dd, position) || position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) {
return entryList;
}
if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
throw parsingError("expected CRLF");
}
position.position += 2;
const result = parseMultipartFormDataHeaders(input, position);
let { name: name2, filename, contentType, encoding } = result;
position.position += 2;
let body;
{
const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
if (boundaryIndex === -1) {
throw parsingError("expected boundary after body");
}
body = input.subarray(position.position, boundaryIndex - 4);
position.position += body.length;
if (encoding === "base64") {
body = Buffer.from(body.toString(), "base64");
}
}
if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
throw parsingError("expected CRLF");
} else {
position.position += 2;
}
let value;
if (filename !== null) {
contentType ??= "text/plain";
if (!isAsciiString(contentType)) {
contentType = "";
}
value = new File2([body], filename, { type: contentType });
} else {
value = utf8DecodeBytes(Buffer.from(body));
}
assert44(webidl.is.USVString(name2));
assert44(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
entryList.push(makeEntry(name2, value, filename));
}
}
__name(multipartFormDataParser, "multipartFormDataParser");
function parseMultipartFormDataHeaders(input, position) {
let name2 = null;
let filename = null;
let contentType = null;
let encoding = null;
while (true) {
if (input[position.position] === 13 && input[position.position + 1] === 10) {
if (name2 === null) {
throw parsingError("header name is null");
}
return { name: name2, filename, contentType, encoding };
}
let headerName = collectASequenceOfBytes(
(char) => char !== 10 && char !== 13 && char !== 58,
input,
position
);
headerName = removeChars(headerName, true, true, (char) => char === 9 || char === 32);
if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
throw parsingError("header name does not match the field-name token production");
}
if (input[position.position] !== 58) {
throw parsingError("expected :");
}
position.position++;
collectASequenceOfBytes(
(char) => char === 32 || char === 9,
input,
position
);
switch (bufferToLowerCasedHeaderName(headerName)) {
case "content-disposition": {
name2 = filename = null;
if (!bufferStartsWith(input, formDataNameBuffer, position)) {
throw parsingError('expected form-data; name=" for content-disposition header');
}
position.position += 17;
name2 = parseMultipartFormDataName(input, position);
if (input[position.position] === 59 && input[position.position + 1] === 32) {
const at2 = { position: position.position + 2 };
if (bufferStartsWith(input, filenameBuffer, at2)) {
if (input[at2.position + 8] === 42) {
at2.position += 10;
collectASequenceOfBytes(
(char) => char === 32 || char === 9,
input,
at2
);
const headerValue = collectASequenceOfBytes(
(char) => char !== 32 && char !== 13 && char !== 10,
// ' ' or CRLF
input,
at2
);
if (headerValue[0] !== 117 && headerValue[0] !== 85 || // u or U
headerValue[1] !== 116 && headerValue[1] !== 84 || // t or T
headerValue[2] !== 102 && headerValue[2] !== 70 || // f or F
headerValue[3] !== 45 || // -
headerValue[4] !== 56) {
throw parsingError("unknown encoding, expected utf-8''");
}
filename = decodeURIComponent(new TextDecoder().decode(headerValue.subarray(7)));
position.position = at2.position;
} else {
position.position += 11;
collectASequenceOfBytes(
(char) => char === 32 || char === 9,
input,
position
);
position.position++;
filename = parseMultipartFormDataName(input, position);
}
}
}
break;
}
case "content-type": {
let headerValue = collectASequenceOfBytes(
(char) => char !== 10 && char !== 13,
input,
position
);
headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
contentType = isomorphicDecode(headerValue);
break;
}
case "content-transfer-encoding": {
let headerValue = collectASequenceOfBytes(
(char) => char !== 10 && char !== 13,
input,
position
);
headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
encoding = isomorphicDecode(headerValue);
break;
}
default: {
collectASequenceOfBytes(
(char) => char !== 10 && char !== 13,
input,
position
);
}
}
if (input[position.position] !== 13 && input[position.position + 1] !== 10) {
throw parsingError("expected CRLF");
} else {
position.position += 2;
}
}
}
__name(parseMultipartFormDataHeaders, "parseMultipartFormDataHeaders");
function parseMultipartFormDataName(input, position) {
assert44(input[position.position - 1] === 34);
let name2 = collectASequenceOfBytes(
(char) => char !== 10 && char !== 13 && char !== 34,
input,
position
);
if (input[position.position] !== 34) {
throw parsingError('expected "');
} else {
position.position++;
}
name2 = new TextDecoder().decode(name2).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
return name2;
}
__name(parseMultipartFormDataName, "parseMultipartFormDataName");
function collectASequenceOfBytes(condition, input, position) {
let start = position.position;
while (start < input.length && condition(input[start])) {
++start;
}
return input.subarray(position.position, position.position = start);
}
__name(collectASequenceOfBytes, "collectASequenceOfBytes");
function removeChars(buf, leading, trailing, predicate) {
let lead = 0;
let trail = buf.length - 1;
if (leading) {
while (lead < buf.length && predicate(buf[lead])) lead++;
}
if (trailing) {
while (trail > 0 && predicate(buf[trail])) trail--;
}
return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1);
}
__name(removeChars, "removeChars");
function bufferStartsWith(buffer, start, position) {
if (buffer.length < start.length) {
return false;
}
for (let i5 = 0; i5 < start.length; i5++) {
if (start[i5] !== buffer[position.position + i5]) {
return false;
}
}
return true;
}
__name(bufferStartsWith, "bufferStartsWith");
function parsingError(cause) {
return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) });
}
__name(parsingError, "parsingError");
module3.exports = {
multipartFormDataParser,
validateBoundary
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/body.js
var require_body = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/body.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var util3 = require_util();
var {
ReadableStreamFrom,
readableStreamClose,
createDeferredPromise,
fullyReadBody,
extractMimeType,
utf8DecodeBytes
} = require_util2();
var { FormData: FormData11, setFormDataState } = require_formdata();
var { webidl } = require_webidl();
var { Blob: Blob6 } = require("buffer");
var assert44 = require("assert");
var { isErrored, isDisturbed } = require("stream");
var { isArrayBuffer: isArrayBuffer3 } = require("util/types");
var { serializeAMimeType } = require_data_url();
var { multipartFormDataParser } = require_formdata_parser();
var random;
try {
const crypto8 = require("crypto");
random = /* @__PURE__ */ __name((max) => crypto8.randomInt(0, max), "random");
} catch {
random = /* @__PURE__ */ __name((max) => Math.floor(Math.random() * max), "random");
}
var textEncoder = new TextEncoder();
function noop() {
}
__name(noop, "noop");
var hasFinalizationRegistry = globalThis.FinalizationRegistry;
var streamRegistry;
if (hasFinalizationRegistry) {
streamRegistry = new FinalizationRegistry((weakRef) => {
const stream2 = weakRef.deref();
if (stream2 && !stream2.locked && !isDisturbed(stream2) && !isErrored(stream2)) {
stream2.cancel("Response object has been garbage collected").catch(noop);
}
});
}
function extractBody(object, keepalive = false) {
let stream2 = null;
if (webidl.is.ReadableStream(object)) {
stream2 = object;
} else if (webidl.is.Blob(object)) {
stream2 = object.stream();
} else {
stream2 = new ReadableStream({
async pull(controller) {
const buffer = typeof source === "string" ? textEncoder.encode(source) : source;
if (buffer.byteLength) {
controller.enqueue(buffer);
}
queueMicrotask(() => readableStreamClose(controller));
},
start() {
},
type: "bytes"
});
}
assert44(webidl.is.ReadableStream(stream2));
let action = null;
let source = null;
let length = null;
let type = null;
if (typeof object === "string") {
source = object;
type = "text/plain;charset=UTF-8";
} else if (webidl.is.URLSearchParams(object)) {
source = object.toString();
type = "application/x-www-form-urlencoded;charset=UTF-8";
} else if (isArrayBuffer3(object)) {
source = new Uint8Array(object.slice());
} else if (ArrayBuffer.isView(object)) {
source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength));
} else if (webidl.is.FormData(object)) {
const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
const prefix = `--${boundary}\r
Content-Disposition: form-data`;
const escape2 = /* @__PURE__ */ __name((str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), "escape");
const normalizeLinefeeds = /* @__PURE__ */ __name((value) => value.replace(/\r?\n|\r/g, "\r\n"), "normalizeLinefeeds");
const blobParts = [];
const rn = new Uint8Array([13, 10]);
length = 0;
let hasUnknownSizeValue = false;
for (const [name2, value] of object) {
if (typeof value === "string") {
const chunk2 = textEncoder.encode(prefix + `; name="${escape2(normalizeLinefeeds(name2))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
blobParts.push(chunk2);
length += chunk2.byteLength;
} else {
const chunk2 = textEncoder.encode(`${prefix}; name="${escape2(normalizeLinefeeds(name2))}"` + (value.name ? `; filename="${escape2(value.name)}"` : "") + `\r
Content-Type: ${value.type || "application/octet-stream"}\r
\r
`);
blobParts.push(chunk2, value, rn);
if (typeof value.size === "number") {
length += chunk2.byteLength + value.size + rn.byteLength;
} else {
hasUnknownSizeValue = true;
}
}
}
const chunk = textEncoder.encode(`--${boundary}--\r
`);
blobParts.push(chunk);
length += chunk.byteLength;
if (hasUnknownSizeValue) {
length = null;
}
source = object;
action = /* @__PURE__ */ __name(async function* () {
for (const part of blobParts) {
if (part.stream) {
yield* part.stream();
} else {
yield part;
}
}
}, "action");
type = `multipart/form-data; boundary=${boundary}`;
} else if (webidl.is.Blob(object)) {
source = object;
length = object.size;
if (object.type) {
type = object.type;
}
} else if (typeof object[Symbol.asyncIterator] === "function") {
if (keepalive) {
throw new TypeError("keepalive");
}
if (util3.isDisturbed(object) || object.locked) {
throw new TypeError(
"Response body object should not be disturbed or locked"
);
}
stream2 = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object);
}
if (typeof source === "string" || util3.isBuffer(source)) {
length = Buffer.byteLength(source);
}
if (action != null) {
let iterator;
stream2 = new ReadableStream({
async start() {
iterator = action(object)[Symbol.asyncIterator]();
},
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
queueMicrotask(() => {
controller.close();
controller.byobRequest?.respond(0);
});
} else {
if (!isErrored(stream2)) {
const buffer = new Uint8Array(value);
if (buffer.byteLength) {
controller.enqueue(buffer);
}
}
}
return controller.desiredSize > 0;
},
async cancel(reason) {
await iterator.return();
},
type: "bytes"
});
}
const body = { stream: stream2, source, length };
return [body, type];
}
__name(extractBody, "extractBody");
function safelyExtractBody(object, keepalive = false) {
if (webidl.is.ReadableStream(object)) {
assert44(!util3.isDisturbed(object), "The body has already been consumed.");
assert44(!object.locked, "The stream is locked.");
}
return extractBody(object, keepalive);
}
__name(safelyExtractBody, "safelyExtractBody");
function cloneBody(instance, body) {
const [out1, out2] = body.stream.tee();
if (hasFinalizationRegistry) {
streamRegistry.register(instance, new WeakRef(out1));
}
body.stream = out1;
return {
stream: out2,
length: body.length,
source: body.source
};
}
__name(cloneBody, "cloneBody");
function throwIfAborted(state2) {
if (state2.aborted) {
throw new DOMException("The operation was aborted.", "AbortError");
}
}
__name(throwIfAborted, "throwIfAborted");
function bodyMixinMethods(instance, getInternalState) {
const methods = {
blob() {
return consumeBody(this, (bytes) => {
let mimeType = bodyMimeType(getInternalState(this));
if (mimeType === null) {
mimeType = "";
} else if (mimeType) {
mimeType = serializeAMimeType(mimeType);
}
return new Blob6([bytes], { type: mimeType });
}, instance, getInternalState);
},
arrayBuffer() {
return consumeBody(this, (bytes) => {
return new Uint8Array(bytes).buffer;
}, instance, getInternalState);
},
text() {
return consumeBody(this, utf8DecodeBytes, instance, getInternalState);
},
json() {
return consumeBody(this, parseJSONFromBytes, instance, getInternalState);
},
formData() {
return consumeBody(this, (value) => {
const mimeType = bodyMimeType(getInternalState(this));
if (mimeType !== null) {
switch (mimeType.essence) {
case "multipart/form-data": {
const parsed = multipartFormDataParser(value, mimeType);
const fd = new FormData11();
setFormDataState(fd, parsed);
return fd;
}
case "application/x-www-form-urlencoded": {
const entries = new URLSearchParams(value.toString());
const fd = new FormData11();
for (const [name2, value2] of entries) {
fd.append(name2, value2);
}
return fd;
}
}
}
throw new TypeError(
'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
);
}, instance, getInternalState);
},
bytes() {
return consumeBody(this, (bytes) => {
return new Uint8Array(bytes);
}, instance, getInternalState);
}
};
return methods;
}
__name(bodyMixinMethods, "bodyMixinMethods");
function mixinBody(prototype, getInternalState) {
Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState));
}
__name(mixinBody, "mixinBody");
async function consumeBody(object, convertBytesToJSValue, instance, getInternalState) {
webidl.brandCheck(object, instance);
const state2 = getInternalState(object);
if (bodyUnusable(state2)) {
throw new TypeError("Body is unusable: Body has already been read");
}
throwIfAborted(state2);
const promise = createDeferredPromise();
const errorSteps = /* @__PURE__ */ __name((error2) => promise.reject(error2), "errorSteps");
const successSteps = /* @__PURE__ */ __name((data) => {
try {
promise.resolve(convertBytesToJSValue(data));
} catch (e7) {
errorSteps(e7);
}
}, "successSteps");
if (state2.body == null) {
successSteps(Buffer.allocUnsafe(0));
return promise.promise;
}
fullyReadBody(state2.body, successSteps, errorSteps);
return promise.promise;
}
__name(consumeBody, "consumeBody");
function bodyUnusable(object) {
const body = object.body;
return body != null && (body.stream.locked || util3.isDisturbed(body.stream));
}
__name(bodyUnusable, "bodyUnusable");
function parseJSONFromBytes(bytes) {
return JSON.parse(utf8DecodeBytes(bytes));
}
__name(parseJSONFromBytes, "parseJSONFromBytes");
function bodyMimeType(requestOrResponse) {
const headers = requestOrResponse.headersList;
const mimeType = extractMimeType(headers);
if (mimeType === "failure") {
return null;
}
return mimeType;
}
__name(bodyMimeType, "bodyMimeType");
module3.exports = {
extractBody,
safelyExtractBody,
cloneBody,
mixinBody,
streamRegistry,
hasFinalizationRegistry,
bodyUnusable
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/client-h1.js
var require_client_h1 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/client-h1.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var util3 = require_util();
var { channels } = require_diagnostics();
var timers = require_timers();
var {
RequestContentLengthMismatchError,
ResponseContentLengthMismatchError,
RequestAbortedError,
HeadersTimeoutError,
HeadersOverflowError,
SocketError,
InformationalError,
BodyTimeoutError,
HTTPParserError,
ResponseExceededMaxSizeError
} = require_errors();
var {
kUrl,
kReset: kReset2,
kClient,
kParser,
kBlocking,
kRunning,
kPending,
kSize,
kWriting,
kQueue,
kNoRef,
kKeepAliveDefaultTimeout,
kHostHeader,
kPendingIdx,
kRunningIdx,
kError,
kPipelining,
kSocket,
kKeepAliveTimeoutValue,
kMaxHeadersSize,
kKeepAliveMaxTimeout,
kKeepAliveTimeoutThreshold,
kHeadersTimeout,
kBodyTimeout,
kStrictContentLength,
kMaxRequests,
kCounter,
kMaxResponseSize,
kOnError,
kResume,
kHTTPContext,
kClosed
} = require_symbols();
var constants4 = require_constants2();
var EMPTY_BUF = Buffer.alloc(0);
var FastBuffer = Buffer[Symbol.species];
var removeAllListeners = util3.removeAllListeners;
var extractBody;
async function lazyllhttp() {
const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
let mod;
try {
mod = await WebAssembly.compile(require_llhttp_simd_wasm());
} catch (e7) {
mod = await WebAssembly.compile(llhttpWasmData || require_llhttp_wasm());
}
return await WebAssembly.instantiate(mod, {
env: {
/**
* @param {number} p
* @param {number} at
* @param {number} len
* @returns {number}
*/
wasm_on_url: /* @__PURE__ */ __name((p6, at2, len) => {
return 0;
}, "wasm_on_url"),
/**
* @param {number} p
* @param {number} at
* @param {number} len
* @returns {number}
*/
wasm_on_status: /* @__PURE__ */ __name((p6, at2, len) => {
assert44(currentParser.ptr === p6);
const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len));
}, "wasm_on_status"),
/**
* @param {number} p
* @returns {number}
*/
wasm_on_message_begin: /* @__PURE__ */ __name((p6) => {
assert44(currentParser.ptr === p6);
return currentParser.onMessageBegin();
}, "wasm_on_message_begin"),
/**
* @param {number} p
* @param {number} at
* @param {number} len
* @returns {number}
*/
wasm_on_header_field: /* @__PURE__ */ __name((p6, at2, len) => {
assert44(currentParser.ptr === p6);
const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len));
}, "wasm_on_header_field"),
/**
* @param {number} p
* @param {number} at
* @param {number} len
* @returns {number}
*/
wasm_on_header_value: /* @__PURE__ */ __name((p6, at2, len) => {
assert44(currentParser.ptr === p6);
const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len));
}, "wasm_on_header_value"),
/**
* @param {number} p
* @param {number} statusCode
* @param {0|1} upgrade
* @param {0|1} shouldKeepAlive
* @returns {number}
*/
wasm_on_headers_complete: /* @__PURE__ */ __name((p6, statusCode, upgrade, shouldKeepAlive) => {
assert44(currentParser.ptr === p6);
return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1);
}, "wasm_on_headers_complete"),
/**
* @param {number} p
* @param {number} at
* @param {number} len
* @returns {number}
*/
wasm_on_body: /* @__PURE__ */ __name((p6, at2, len) => {
assert44(currentParser.ptr === p6);
const start = at2 - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len));
}, "wasm_on_body"),
/**
* @param {number} p
* @returns {number}
*/
wasm_on_message_complete: /* @__PURE__ */ __name((p6) => {
assert44(currentParser.ptr === p6);
return currentParser.onMessageComplete();
}, "wasm_on_message_complete")
}
});
}
__name(lazyllhttp, "lazyllhttp");
var llhttpInstance = null;
var llhttpPromise = lazyllhttp();
llhttpPromise.catch();
var currentParser = null;
var currentBufferRef = null;
var currentBufferSize = 0;
var currentBufferPtr = null;
var USE_NATIVE_TIMER = 0;
var USE_FAST_TIMER = 1;
var TIMEOUT_HEADERS = 2 | USE_FAST_TIMER;
var TIMEOUT_BODY = 4 | USE_FAST_TIMER;
var TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER;
var Parser2 = class {
static {
__name(this, "Parser");
}
/**
* @param {import('./client.js')} client
* @param {import('net').Socket} socket
* @param {*} llhttp
*/
constructor(client, socket, { exports: exports3 }) {
this.llhttp = exports3;
this.ptr = this.llhttp.llhttp_alloc(constants4.TYPE.RESPONSE);
this.client = client;
this.socket = socket;
this.timeout = null;
this.timeoutValue = null;
this.timeoutType = null;
this.statusCode = 0;
this.statusText = "";
this.upgrade = false;
this.headers = [];
this.headersSize = 0;
this.headersMaxSize = client[kMaxHeadersSize];
this.shouldKeepAlive = false;
this.paused = false;
this.resume = this.resume.bind(this);
this.bytesRead = 0;
this.keepAlive = "";
this.contentLength = "";
this.connection = "";
this.maxResponseSize = client[kMaxResponseSize];
}
setTimeout(delay, type) {
if (delay !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
if (this.timeout) {
timers.clearTimeout(this.timeout);
this.timeout = null;
}
if (delay) {
if (type & USE_FAST_TIMER) {
this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this));
} else {
this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this));
this.timeout?.unref();
}
}
this.timeoutValue = delay;
} else if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
this.timeoutType = type;
}
resume() {
if (this.socket.destroyed || !this.paused) {
return;
}
assert44(this.ptr != null);
assert44(currentParser === null);
this.llhttp.llhttp_resume(this.ptr);
assert44(this.timeoutType === TIMEOUT_BODY);
if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
this.paused = false;
this.execute(this.socket.read() || EMPTY_BUF);
this.readMore();
}
readMore() {
while (!this.paused && this.ptr) {
const chunk = this.socket.read();
if (chunk === null) {
break;
}
this.execute(chunk);
}
}
/**
* @param {Buffer} chunk
*/
execute(chunk) {
assert44(currentParser === null);
assert44(this.ptr != null);
assert44(!this.paused);
const { socket, llhttp } = this;
if (chunk.length > currentBufferSize) {
if (currentBufferPtr) {
llhttp.free(currentBufferPtr);
}
currentBufferSize = Math.ceil(chunk.length / 4096) * 4096;
currentBufferPtr = llhttp.malloc(currentBufferSize);
}
new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk);
try {
let ret;
try {
currentBufferRef = chunk;
currentParser = this;
ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length);
} catch (err) {
throw err;
} finally {
currentParser = null;
currentBufferRef = null;
}
if (ret !== constants4.ERROR.OK) {
const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
if (ret === constants4.ERROR.PAUSED_UPGRADE) {
this.onUpgrade(data);
} else if (ret === constants4.ERROR.PAUSED) {
this.paused = true;
socket.unshift(data);
} else {
const ptr = llhttp.llhttp_get_error_reason(this.ptr);
let message = "";
if (ptr) {
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
}
throw new HTTPParserError(message, constants4.ERROR[ret], data);
}
}
} catch (err) {
util3.destroy(socket, err);
}
}
destroy() {
assert44(currentParser === null);
assert44(this.ptr != null);
this.llhttp.llhttp_free(this.ptr);
this.ptr = null;
this.timeout && timers.clearTimeout(this.timeout);
this.timeout = null;
this.timeoutValue = null;
this.timeoutType = null;
this.paused = false;
}
/**
* @param {Buffer} buf
* @returns {0}
*/
onStatus(buf) {
this.statusText = buf.toString();
return 0;
}
/**
* @returns {0|-1}
*/
onMessageBegin() {
const { socket, client } = this;
if (socket.destroyed) {
return -1;
}
const request4 = client[kQueue][client[kRunningIdx]];
if (!request4) {
return -1;
}
request4.onResponseStarted();
return 0;
}
/**
* @param {Buffer} buf
* @returns {number}
*/
onHeaderField(buf) {
const len = this.headers.length;
if ((len & 1) === 0) {
this.headers.push(buf);
} else {
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
}
this.trackHeader(buf.length);
return 0;
}
/**
* @param {Buffer} buf
* @returns {number}
*/
onHeaderValue(buf) {
let len = this.headers.length;
if ((len & 1) === 1) {
this.headers.push(buf);
len += 1;
} else {
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
}
const key = this.headers[len - 2];
if (key.length === 10) {
const headerName = util3.bufferToLowerCasedHeaderName(key);
if (headerName === "keep-alive") {
this.keepAlive += buf.toString();
} else if (headerName === "connection") {
this.connection += buf.toString();
}
} else if (key.length === 14 && util3.bufferToLowerCasedHeaderName(key) === "content-length") {
this.contentLength += buf.toString();
}
this.trackHeader(buf.length);
return 0;
}
/**
* @param {number} len
*/
trackHeader(len) {
this.headersSize += len;
if (this.headersSize >= this.headersMaxSize) {
util3.destroy(this.socket, new HeadersOverflowError());
}
}
/**
* @param {Buffer} head
*/
onUpgrade(head) {
const { upgrade, client, socket, headers, statusCode } = this;
assert44(upgrade);
assert44(client[kSocket] === socket);
assert44(!socket.destroyed);
assert44(!this.paused);
assert44((headers.length & 1) === 0);
const request4 = client[kQueue][client[kRunningIdx]];
assert44(request4);
assert44(request4.upgrade || request4.method === "CONNECT");
this.statusCode = 0;
this.statusText = "";
this.shouldKeepAlive = false;
this.headers = [];
this.headersSize = 0;
socket.unshift(head);
socket[kParser].destroy();
socket[kParser] = null;
socket[kClient] = null;
socket[kError] = null;
removeAllListeners(socket);
client[kSocket] = null;
client[kHTTPContext] = null;
client[kQueue][client[kRunningIdx]++] = null;
client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade"));
try {
request4.onUpgrade(statusCode, headers, socket);
} catch (err) {
util3.destroy(socket, err);
}
client[kResume]();
}
/**
* @param {number} statusCode
* @param {boolean} upgrade
* @param {boolean} shouldKeepAlive
* @returns {number}
*/
onHeadersComplete(statusCode, upgrade, shouldKeepAlive) {
const { client, socket, headers, statusText } = this;
if (socket.destroyed) {
return -1;
}
const request4 = client[kQueue][client[kRunningIdx]];
if (!request4) {
return -1;
}
assert44(!this.upgrade);
assert44(this.statusCode < 200);
if (statusCode === 100) {
util3.destroy(socket, new SocketError("bad response", util3.getSocketInfo(socket)));
return -1;
}
if (upgrade && !request4.upgrade) {
util3.destroy(socket, new SocketError("bad upgrade", util3.getSocketInfo(socket)));
return -1;
}
assert44(this.timeoutType === TIMEOUT_HEADERS);
this.statusCode = statusCode;
this.shouldKeepAlive = shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD.
request4.method === "HEAD" && !socket[kReset2] && this.connection.toLowerCase() === "keep-alive";
if (this.statusCode >= 200) {
const bodyTimeout = request4.bodyTimeout != null ? request4.bodyTimeout : client[kBodyTimeout];
this.setTimeout(bodyTimeout, TIMEOUT_BODY);
} else if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
if (request4.method === "CONNECT") {
assert44(client[kRunning] === 1);
this.upgrade = true;
return 2;
}
if (upgrade) {
assert44(client[kRunning] === 1);
this.upgrade = true;
return 2;
}
assert44((this.headers.length & 1) === 0);
this.headers = [];
this.headersSize = 0;
if (this.shouldKeepAlive && client[kPipelining]) {
const keepAliveTimeout = this.keepAlive ? util3.parseKeepAliveTimeout(this.keepAlive) : null;
if (keepAliveTimeout != null) {
const timeout2 = Math.min(
keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
client[kKeepAliveMaxTimeout]
);
if (timeout2 <= 0) {
socket[kReset2] = true;
} else {
client[kKeepAliveTimeoutValue] = timeout2;
}
} else {
client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout];
}
} else {
socket[kReset2] = true;
}
const pause = request4.onHeaders(statusCode, headers, this.resume, statusText) === false;
if (request4.aborted) {
return -1;
}
if (request4.method === "HEAD") {
return 1;
}
if (statusCode < 200) {
return 1;
}
if (socket[kBlocking]) {
socket[kBlocking] = false;
client[kResume]();
}
return pause ? constants4.ERROR.PAUSED : 0;
}
/**
* @param {Buffer} buf
* @returns {number}
*/
onBody(buf) {
const { client, socket, statusCode, maxResponseSize } = this;
if (socket.destroyed) {
return -1;
}
const request4 = client[kQueue][client[kRunningIdx]];
assert44(request4);
assert44(this.timeoutType === TIMEOUT_BODY);
if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
assert44(statusCode >= 200);
if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
util3.destroy(socket, new ResponseExceededMaxSizeError());
return -1;
}
this.bytesRead += buf.length;
if (request4.onData(buf) === false) {
return constants4.ERROR.PAUSED;
}
return 0;
}
/**
* @returns {number}
*/
onMessageComplete() {
const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
return -1;
}
if (upgrade) {
return 0;
}
assert44(statusCode >= 100);
assert44((this.headers.length & 1) === 0);
const request4 = client[kQueue][client[kRunningIdx]];
assert44(request4);
this.statusCode = 0;
this.statusText = "";
this.bytesRead = 0;
this.contentLength = "";
this.keepAlive = "";
this.connection = "";
this.headers = [];
this.headersSize = 0;
if (statusCode < 200) {
return 0;
}
if (request4.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
util3.destroy(socket, new ResponseContentLengthMismatchError());
return -1;
}
request4.onComplete(headers);
client[kQueue][client[kRunningIdx]++] = null;
if (socket[kWriting]) {
assert44(client[kRunning] === 0);
util3.destroy(socket, new InformationalError("reset"));
return constants4.ERROR.PAUSED;
} else if (!shouldKeepAlive) {
util3.destroy(socket, new InformationalError("reset"));
return constants4.ERROR.PAUSED;
} else if (socket[kReset2] && client[kRunning] === 0) {
util3.destroy(socket, new InformationalError("reset"));
return constants4.ERROR.PAUSED;
} else if (client[kPipelining] == null || client[kPipelining] === 1) {
setImmediate(() => client[kResume]());
} else {
client[kResume]();
}
return 0;
}
};
function onParserTimeout(parser2) {
const { socket, timeoutType, client, paused } = parser2.deref();
if (timeoutType === TIMEOUT_HEADERS) {
if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
assert44(!paused, "cannot be paused while waiting for headers");
util3.destroy(socket, new HeadersTimeoutError());
}
} else if (timeoutType === TIMEOUT_BODY) {
if (!paused) {
util3.destroy(socket, new BodyTimeoutError());
}
} else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
assert44(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
util3.destroy(socket, new InformationalError("socket idle timeout"));
}
}
__name(onParserTimeout, "onParserTimeout");
async function connectH1(client, socket) {
client[kSocket] = socket;
if (!llhttpInstance) {
const noop = /* @__PURE__ */ __name(() => {
}, "noop");
socket.on("error", noop);
llhttpInstance = await llhttpPromise;
llhttpPromise = null;
socket.off("error", noop);
}
if (socket.errored) {
throw socket.errored;
}
if (socket.destroyed) {
throw new SocketError("destroyed");
}
socket[kNoRef] = false;
socket[kWriting] = false;
socket[kReset2] = false;
socket[kBlocking] = false;
socket[kParser] = new Parser2(client, socket, llhttpInstance);
util3.addListener(socket, "error", onHttpSocketError);
util3.addListener(socket, "readable", onHttpSocketReadable);
util3.addListener(socket, "end", onHttpSocketEnd);
util3.addListener(socket, "close", onHttpSocketClose);
socket[kClosed] = false;
socket.on("close", onSocketClose);
return {
version: "h1",
defaultPipelining: 1,
write(request4) {
return writeH1(client, request4);
},
resume() {
resumeH1(client);
},
/**
* @param {Error|undefined} err
* @param {() => void} callback
*/
destroy(err, callback) {
if (socket[kClosed]) {
queueMicrotask(callback);
} else {
socket.on("close", callback);
socket.destroy(err);
}
},
/**
* @returns {boolean}
*/
get destroyed() {
return socket.destroyed;
},
/**
* @param {import('../core/request.js')} request
* @returns {boolean}
*/
busy(request4) {
if (socket[kWriting] || socket[kReset2] || socket[kBlocking]) {
return true;
}
if (request4) {
if (client[kRunning] > 0 && !request4.idempotent) {
return true;
}
if (client[kRunning] > 0 && (request4.upgrade || request4.method === "CONNECT")) {
return true;
}
if (client[kRunning] > 0 && util3.bodyLength(request4.body) !== 0 && (util3.isStream(request4.body) || util3.isAsyncIterable(request4.body) || util3.isFormDataLike(request4.body))) {
return true;
}
}
return false;
}
};
}
__name(connectH1, "connectH1");
function onHttpSocketError(err) {
assert44(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
const parser2 = this[kParser];
if (err.code === "ECONNRESET" && parser2.statusCode && !parser2.shouldKeepAlive) {
parser2.onMessageComplete();
return;
}
this[kError] = err;
this[kClient][kOnError](err);
}
__name(onHttpSocketError, "onHttpSocketError");
function onHttpSocketReadable() {
this[kParser]?.readMore();
}
__name(onHttpSocketReadable, "onHttpSocketReadable");
function onHttpSocketEnd() {
const parser2 = this[kParser];
if (parser2.statusCode && !parser2.shouldKeepAlive) {
parser2.onMessageComplete();
return;
}
util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this)));
}
__name(onHttpSocketEnd, "onHttpSocketEnd");
function onHttpSocketClose() {
const parser2 = this[kParser];
if (parser2) {
if (!this[kError] && parser2.statusCode && !parser2.shouldKeepAlive) {
parser2.onMessageComplete();
}
this[kParser].destroy();
this[kParser] = null;
}
const err = this[kError] || new SocketError("closed", util3.getSocketInfo(this));
const client = this[kClient];
client[kSocket] = null;
client[kHTTPContext] = null;
if (client.destroyed) {
assert44(client[kPending] === 0);
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i5 = 0; i5 < requests.length; i5++) {
const request4 = requests[i5];
util3.errorRequest(client, request4, err);
}
} else if (client[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
const request4 = client[kQueue][client[kRunningIdx]];
client[kQueue][client[kRunningIdx]++] = null;
util3.errorRequest(client, request4, err);
}
client[kPendingIdx] = client[kRunningIdx];
assert44(client[kRunning] === 0);
client.emit("disconnect", client[kUrl], [client], err);
client[kResume]();
}
__name(onHttpSocketClose, "onHttpSocketClose");
function onSocketClose() {
this[kClosed] = true;
}
__name(onSocketClose, "onSocketClose");
function resumeH1(client) {
const socket = client[kSocket];
if (socket && !socket.destroyed) {
if (client[kSize] === 0) {
if (!socket[kNoRef] && socket.unref) {
socket.unref();
socket[kNoRef] = true;
}
} else if (socket[kNoRef] && socket.ref) {
socket.ref();
socket[kNoRef] = false;
}
if (client[kSize] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
}
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
const request4 = client[kQueue][client[kRunningIdx]];
const headersTimeout = request4.headersTimeout != null ? request4.headersTimeout : client[kHeadersTimeout];
socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS);
}
}
}
}
__name(resumeH1, "resumeH1");
function shouldSendContentLength(method) {
return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
}
__name(shouldSendContentLength, "shouldSendContentLength");
function writeH1(client, request4) {
const { method, path: path72, host, upgrade, blocking, reset } = request4;
let { body, headers, contentLength } = request4;
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
if (util3.isFormDataLike(body)) {
if (!extractBody) {
extractBody = require_body().extractBody;
}
const [bodyStream, contentType] = extractBody(body);
if (request4.contentType == null) {
headers.push("content-type", contentType);
}
body = bodyStream.stream;
contentLength = bodyStream.length;
} else if (util3.isBlobLike(body) && request4.contentType == null && body.type) {
headers.push("content-type", body.type);
}
if (body && typeof body.read === "function") {
body.read(0);
}
const bodyLength = util3.bodyLength(body);
contentLength = bodyLength ?? contentLength;
if (contentLength === null) {
contentLength = request4.contentLength;
}
if (contentLength === 0 && !expectsPayload) {
contentLength = null;
}
if (shouldSendContentLength(method) && contentLength > 0 && request4.contentLength !== null && request4.contentLength !== contentLength) {
if (client[kStrictContentLength]) {
util3.errorRequest(client, request4, new RequestContentLengthMismatchError());
return false;
}
process.emitWarning(new RequestContentLengthMismatchError());
}
const socket = client[kSocket];
const abort = /* @__PURE__ */ __name((err) => {
if (request4.aborted || request4.completed) {
return;
}
util3.errorRequest(client, request4, err || new RequestAbortedError());
util3.destroy(body);
util3.destroy(socket, new InformationalError("aborted"));
}, "abort");
try {
request4.onConnect(abort);
} catch (err) {
util3.errorRequest(client, request4, err);
}
if (request4.aborted) {
return false;
}
if (method === "HEAD") {
socket[kReset2] = true;
}
if (upgrade || method === "CONNECT") {
socket[kReset2] = true;
}
if (reset != null) {
socket[kReset2] = reset;
}
if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
socket[kReset2] = true;
}
if (blocking) {
socket[kBlocking] = true;
}
let header = `${method} ${path72} HTTP/1.1\r
`;
if (typeof host === "string") {
header += `host: ${host}\r
`;
} else {
header += client[kHostHeader];
}
if (upgrade) {
header += `connection: upgrade\r
upgrade: ${upgrade}\r
`;
} else if (client[kPipelining] && !socket[kReset2]) {
header += "connection: keep-alive\r\n";
} else {
header += "connection: close\r\n";
}
if (Array.isArray(headers)) {
for (let n6 = 0; n6 < headers.length; n6 += 2) {
const key = headers[n6 + 0];
const val2 = headers[n6 + 1];
if (Array.isArray(val2)) {
for (let i5 = 0; i5 < val2.length; i5++) {
header += `${key}: ${val2[i5]}\r
`;
}
} else {
header += `${key}: ${val2}\r
`;
}
}
}
if (channels.sendHeaders.hasSubscribers) {
channels.sendHeaders.publish({ request: request4, headers: header, socket });
}
if (!body || bodyLength === 0) {
writeBuffer(abort, null, client, request4, socket, contentLength, header, expectsPayload);
} else if (util3.isBuffer(body)) {
writeBuffer(abort, body, client, request4, socket, contentLength, header, expectsPayload);
} else if (util3.isBlobLike(body)) {
if (typeof body.stream === "function") {
writeIterable(abort, body.stream(), client, request4, socket, contentLength, header, expectsPayload);
} else {
writeBlob(abort, body, client, request4, socket, contentLength, header, expectsPayload);
}
} else if (util3.isStream(body)) {
writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload);
} else if (util3.isIterable(body)) {
writeIterable(abort, body, client, request4, socket, contentLength, header, expectsPayload);
} else {
assert44(false);
}
return true;
}
__name(writeH1, "writeH1");
function writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
assert44(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
let finished = false;
const writer = new AsyncWriter({ abort, socket, request: request4, contentLength, client, expectsPayload, header });
const onData = /* @__PURE__ */ __name(function(chunk) {
if (finished) {
return;
}
try {
if (!writer.write(chunk) && this.pause) {
this.pause();
}
} catch (err) {
util3.destroy(this, err);
}
}, "onData");
const onDrain = /* @__PURE__ */ __name(function() {
if (finished) {
return;
}
if (body.resume) {
body.resume();
}
}, "onDrain");
const onClose = /* @__PURE__ */ __name(function() {
queueMicrotask(() => {
body.removeListener("error", onFinished);
});
if (!finished) {
const err = new RequestAbortedError();
queueMicrotask(() => onFinished(err));
}
}, "onClose");
const onFinished = /* @__PURE__ */ __name(function(err) {
if (finished) {
return;
}
finished = true;
assert44(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
socket.off("drain", onDrain).off("error", onFinished);
body.removeListener("data", onData).removeListener("end", onFinished).removeListener("close", onClose);
if (!err) {
try {
writer.end();
} catch (er) {
err = er;
}
}
writer.destroy(err);
if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
util3.destroy(body, err);
} else {
util3.destroy(body);
}
}, "onFinished");
body.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose);
if (body.resume) {
body.resume();
}
socket.on("drain", onDrain).on("error", onFinished);
if (body.errorEmitted ?? body.errored) {
setImmediate(() => onFinished(body.errored));
} else if (body.endEmitted ?? body.readableEnded) {
setImmediate(() => onFinished(null));
}
if (body.closeEmitted ?? body.closed) {
setImmediate(onClose);
}
}
__name(writeStream, "writeStream");
function writeBuffer(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
try {
if (!body) {
if (contentLength === 0) {
socket.write(`${header}content-length: 0\r
\r
`, "latin1");
} else {
assert44(contentLength === null, "no body must not have content length");
socket.write(`${header}\r
`, "latin1");
}
} else if (util3.isBuffer(body)) {
assert44(contentLength === body.byteLength, "buffer body must have content length");
socket.cork();
socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
socket.write(body);
socket.uncork();
request4.onBodySent(body);
if (!expectsPayload && request4.reset !== false) {
socket[kReset2] = true;
}
}
request4.onRequestSent();
client[kResume]();
} catch (err) {
abort(err);
}
}
__name(writeBuffer, "writeBuffer");
async function writeBlob(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
assert44(contentLength === body.size, "blob body must have content length");
try {
if (contentLength != null && contentLength !== body.size) {
throw new RequestContentLengthMismatchError();
}
const buffer = Buffer.from(await body.arrayBuffer());
socket.cork();
socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
socket.write(buffer);
socket.uncork();
request4.onBodySent(buffer);
request4.onRequestSent();
if (!expectsPayload && request4.reset !== false) {
socket[kReset2] = true;
}
client[kResume]();
} catch (err) {
abort(err);
}
}
__name(writeBlob, "writeBlob");
async function writeIterable(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
assert44(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
let callback = null;
function onDrain() {
if (callback) {
const cb2 = callback;
callback = null;
cb2();
}
}
__name(onDrain, "onDrain");
const waitForDrain = /* @__PURE__ */ __name(() => new Promise((resolve25, reject) => {
assert44(callback === null);
if (socket[kError]) {
reject(socket[kError]);
} else {
callback = resolve25;
}
}), "waitForDrain");
socket.on("close", onDrain).on("drain", onDrain);
const writer = new AsyncWriter({ abort, socket, request: request4, contentLength, client, expectsPayload, header });
try {
for await (const chunk of body) {
if (socket[kError]) {
throw socket[kError];
}
if (!writer.write(chunk)) {
await waitForDrain();
}
}
writer.end();
} catch (err) {
writer.destroy(err);
} finally {
socket.off("close", onDrain).off("drain", onDrain);
}
}
__name(writeIterable, "writeIterable");
var AsyncWriter = class {
static {
__name(this, "AsyncWriter");
}
/**
*
* @param {object} arg
* @param {AbortCallback} arg.abort
* @param {import('net').Socket} arg.socket
* @param {import('../core/request.js')} arg.request
* @param {number} arg.contentLength
* @param {import('./client.js')} arg.client
* @param {boolean} arg.expectsPayload
* @param {string} arg.header
*/
constructor({ abort, socket, request: request4, contentLength, client, expectsPayload, header }) {
this.socket = socket;
this.request = request4;
this.contentLength = contentLength;
this.client = client;
this.bytesWritten = 0;
this.expectsPayload = expectsPayload;
this.header = header;
this.abort = abort;
socket[kWriting] = true;
}
/**
* @param {Buffer} chunk
* @returns
*/
write(chunk) {
const { socket, request: request4, contentLength, client, bytesWritten, expectsPayload, header } = this;
if (socket[kError]) {
throw socket[kError];
}
if (socket.destroyed) {
return false;
}
const len = Buffer.byteLength(chunk);
if (!len) {
return true;
}
if (contentLength !== null && bytesWritten + len > contentLength) {
if (client[kStrictContentLength]) {
throw new RequestContentLengthMismatchError();
}
process.emitWarning(new RequestContentLengthMismatchError());
}
socket.cork();
if (bytesWritten === 0) {
if (!expectsPayload && request4.reset !== false) {
socket[kReset2] = true;
}
if (contentLength === null) {
socket.write(`${header}transfer-encoding: chunked\r
`, "latin1");
} else {
socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
}
}
if (contentLength === null) {
socket.write(`\r
${len.toString(16)}\r
`, "latin1");
}
this.bytesWritten += len;
const ret = socket.write(chunk);
socket.uncork();
request4.onBodySent(chunk);
if (!ret) {
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
if (socket[kParser].timeout.refresh) {
socket[kParser].timeout.refresh();
}
}
}
return ret;
}
/**
* @returns {void}
*/
end() {
const { socket, contentLength, client, bytesWritten, expectsPayload, header, request: request4 } = this;
request4.onRequestSent();
socket[kWriting] = false;
if (socket[kError]) {
throw socket[kError];
}
if (socket.destroyed) {
return;
}
if (bytesWritten === 0) {
if (expectsPayload) {
socket.write(`${header}content-length: 0\r
\r
`, "latin1");
} else {
socket.write(`${header}\r
`, "latin1");
}
} else if (contentLength === null) {
socket.write("\r\n0\r\n\r\n", "latin1");
}
if (contentLength !== null && bytesWritten !== contentLength) {
if (client[kStrictContentLength]) {
throw new RequestContentLengthMismatchError();
} else {
process.emitWarning(new RequestContentLengthMismatchError());
}
}
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
if (socket[kParser].timeout.refresh) {
socket[kParser].timeout.refresh();
}
}
client[kResume]();
}
/**
* @param {Error} [err]
* @returns {void}
*/
destroy(err) {
const { socket, client, abort } = this;
socket[kWriting] = false;
if (err) {
assert44(client[kRunning] <= 1, "pipeline should only contain this request");
abort(err);
}
}
};
module3.exports = connectH1;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h2 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { pipeline } = require("stream");
var util3 = require_util();
var {
RequestContentLengthMismatchError,
RequestAbortedError,
SocketError,
InformationalError
} = require_errors();
var {
kUrl,
kReset: kReset2,
kClient,
kRunning,
kPending,
kQueue,
kPendingIdx,
kRunningIdx,
kError,
kSocket,
kStrictContentLength,
kOnError,
kMaxConcurrentStreams,
kHTTP2Session,
kResume,
kSize,
kHTTPContext,
kClosed,
kBodyTimeout
} = require_symbols();
var { channels } = require_diagnostics();
var kOpenStreams = Symbol("open streams");
var extractBody;
var http22;
try {
http22 = require("http2");
} catch {
http22 = { constants: {} };
}
var {
constants: {
HTTP2_HEADER_AUTHORITY,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_CONTENT_LENGTH,
HTTP2_HEADER_EXPECT,
HTTP2_HEADER_STATUS
}
} = http22;
function parseH2Headers(headers) {
const result = [];
for (const [name2, value] of Object.entries(headers)) {
if (Array.isArray(value)) {
for (const subvalue of value) {
result.push(Buffer.from(name2), Buffer.from(subvalue));
}
} else {
result.push(Buffer.from(name2), Buffer.from(value));
}
}
return result;
}
__name(parseH2Headers, "parseH2Headers");
async function connectH2(client, socket) {
client[kSocket] = socket;
const session = http22.connect(client[kUrl], {
createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
settings: {
// TODO(metcoder95): add support for PUSH
enablePush: false
}
});
session[kOpenStreams] = 0;
session[kClient] = client;
session[kSocket] = socket;
session[kHTTP2Session] = null;
util3.addListener(session, "error", onHttp2SessionError);
util3.addListener(session, "frameError", onHttp2FrameError);
util3.addListener(session, "end", onHttp2SessionEnd);
util3.addListener(session, "goaway", onHttp2SessionGoAway);
util3.addListener(session, "close", onHttp2SessionClose);
session.unref();
client[kHTTP2Session] = session;
socket[kHTTP2Session] = session;
util3.addListener(socket, "error", onHttp2SocketError);
util3.addListener(socket, "end", onHttp2SocketEnd);
util3.addListener(socket, "close", onHttp2SocketClose);
socket[kClosed] = false;
socket.on("close", onSocketClose);
return {
version: "h2",
defaultPipelining: Infinity,
write(request4) {
return writeH2(client, request4);
},
resume() {
resumeH2(client);
},
destroy(err, callback) {
if (socket[kClosed]) {
queueMicrotask(callback);
} else {
socket.destroy(err).on("close", callback);
}
},
get destroyed() {
return socket.destroyed;
},
busy() {
return false;
}
};
}
__name(connectH2, "connectH2");
function resumeH2(client) {
const socket = client[kSocket];
if (socket?.destroyed === false) {
if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
socket.unref();
client[kHTTP2Session].unref();
} else {
socket.ref();
client[kHTTP2Session].ref();
}
}
}
__name(resumeH2, "resumeH2");
function onHttp2SessionError(err) {
assert44(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
this[kSocket][kError] = err;
this[kClient][kOnError](err);
}
__name(onHttp2SessionError, "onHttp2SessionError");
function onHttp2FrameError(type, code, id) {
if (id === 0) {
const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`);
this[kSocket][kError] = err;
this[kClient][kOnError](err);
}
}
__name(onHttp2FrameError, "onHttp2FrameError");
function onHttp2SessionEnd() {
const err = new SocketError("other side closed", util3.getSocketInfo(this[kSocket]));
this.destroy(err);
util3.destroy(this[kSocket], err);
}
__name(onHttp2SessionEnd, "onHttp2SessionEnd");
function onHttp2SessionGoAway(errorCode) {
const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util3.getSocketInfo(this[kSocket]));
const client = this[kClient];
client[kSocket] = null;
client[kHTTPContext] = null;
this.close();
this[kHTTP2Session] = null;
util3.destroy(this[kSocket], err);
if (client[kRunningIdx] < client[kQueue].length) {
const request4 = client[kQueue][client[kRunningIdx]];
client[kQueue][client[kRunningIdx]++] = null;
util3.errorRequest(client, request4, err);
client[kPendingIdx] = client[kRunningIdx];
}
assert44(client[kRunning] === 0);
client.emit("disconnect", client[kUrl], [client], err);
client.emit("connectionError", client[kUrl], [client], err);
client[kResume]();
}
__name(onHttp2SessionGoAway, "onHttp2SessionGoAway");
function onHttp2SessionClose() {
const { [kClient]: client } = this;
const { [kSocket]: socket } = client;
const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util3.getSocketInfo(socket));
client[kSocket] = null;
client[kHTTPContext] = null;
if (client.destroyed) {
assert44(client[kPending] === 0);
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i5 = 0; i5 < requests.length; i5++) {
const request4 = requests[i5];
util3.errorRequest(client, request4, err);
}
}
}
__name(onHttp2SessionClose, "onHttp2SessionClose");
function onHttp2SocketClose() {
const err = this[kError] || new SocketError("closed", util3.getSocketInfo(this));
const client = this[kHTTP2Session][kClient];
client[kSocket] = null;
client[kHTTPContext] = null;
if (this[kHTTP2Session] !== null) {
this[kHTTP2Session].destroy(err);
}
client[kPendingIdx] = client[kRunningIdx];
assert44(client[kRunning] === 0);
client.emit("disconnect", client[kUrl], [client], err);
client[kResume]();
}
__name(onHttp2SocketClose, "onHttp2SocketClose");
function onHttp2SocketError(err) {
assert44(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
this[kError] = err;
this[kClient][kOnError](err);
}
__name(onHttp2SocketError, "onHttp2SocketError");
function onHttp2SocketEnd() {
util3.destroy(this, new SocketError("other side closed", util3.getSocketInfo(this)));
}
__name(onHttp2SocketEnd, "onHttp2SocketEnd");
function onSocketClose() {
this[kClosed] = true;
}
__name(onSocketClose, "onSocketClose");
function shouldSendContentLength(method) {
return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
}
__name(shouldSendContentLength, "shouldSendContentLength");
function writeH2(client, request4) {
const requestTimeout2 = request4.bodyTimeout ?? client[kBodyTimeout];
const session = client[kHTTP2Session];
const { method, path: path72, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4;
let { body } = request4;
if (upgrade) {
util3.errorRequest(client, request4, new Error("Upgrade not supported for H2"));
return false;
}
const headers = {};
for (let n6 = 0; n6 < reqHeaders.length; n6 += 2) {
const key = reqHeaders[n6 + 0];
const val2 = reqHeaders[n6 + 1];
if (Array.isArray(val2)) {
for (let i5 = 0; i5 < val2.length; i5++) {
if (headers[key]) {
headers[key] += `, ${val2[i5]}`;
} else {
headers[key] = val2[i5];
}
}
} else if (headers[key]) {
headers[key] += `, ${val2}`;
} else {
headers[key] = val2;
}
}
let stream2 = null;
const { hostname: hostname2, port } = client[kUrl];
headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname2}${port ? `:${port}` : ""}`;
headers[HTTP2_HEADER_METHOD] = method;
const abort = /* @__PURE__ */ __name((err) => {
if (request4.aborted || request4.completed) {
return;
}
err = err || new RequestAbortedError();
util3.errorRequest(client, request4, err);
if (stream2 != null) {
stream2.removeAllListeners("data");
stream2.close();
client[kOnError](err);
client[kResume]();
}
util3.destroy(body, err);
}, "abort");
try {
request4.onConnect(abort);
} catch (err) {
util3.errorRequest(client, request4, err);
}
if (request4.aborted) {
return false;
}
if (method === "CONNECT") {
session.ref();
stream2 = session.request(headers, { endStream: false, signal });
if (!stream2.pending) {
request4.onUpgrade(null, null, stream2);
++session[kOpenStreams];
client[kQueue][client[kRunningIdx]++] = null;
} else {
stream2.once("ready", () => {
request4.onUpgrade(null, null, stream2);
++session[kOpenStreams];
client[kQueue][client[kRunningIdx]++] = null;
});
}
stream2.once("close", () => {
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
});
stream2.setTimeout(requestTimeout2);
return true;
}
headers[HTTP2_HEADER_PATH] = path72;
headers[HTTP2_HEADER_SCHEME] = "https";
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
if (body && typeof body.read === "function") {
body.read(0);
}
let contentLength = util3.bodyLength(body);
if (util3.isFormDataLike(body)) {
extractBody ??= require_body().extractBody;
const [bodyStream, contentType] = extractBody(body);
headers["content-type"] = contentType;
body = bodyStream.stream;
contentLength = bodyStream.length;
}
if (contentLength == null) {
contentLength = request4.contentLength;
}
if (contentLength === 0 || !expectsPayload) {
contentLength = null;
}
if (shouldSendContentLength(method) && contentLength > 0 && request4.contentLength != null && request4.contentLength !== contentLength) {
if (client[kStrictContentLength]) {
util3.errorRequest(client, request4, new RequestContentLengthMismatchError());
return false;
}
process.emitWarning(new RequestContentLengthMismatchError());
}
if (contentLength != null) {
assert44(body, "no body must not have content length");
headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
}
session.ref();
if (channels.sendHeaders.hasSubscribers) {
let header = "";
for (const key in headers) {
header += `${key}: ${headers[key]}\r
`;
}
channels.sendHeaders.publish({ request: request4, headers: header, socket: session[kSocket] });
}
const shouldEndStream = method === "GET" || method === "HEAD" || body === null;
if (expectContinue) {
headers[HTTP2_HEADER_EXPECT] = "100-continue";
stream2 = session.request(headers, { endStream: shouldEndStream, signal });
stream2.once("continue", writeBodyH2);
} else {
stream2 = session.request(headers, {
endStream: shouldEndStream,
signal
});
writeBodyH2();
}
++session[kOpenStreams];
stream2.setTimeout(requestTimeout2);
stream2.once("response", (headers2) => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
request4.onResponseStarted();
if (request4.aborted) {
stream2.removeAllListeners("data");
return;
}
if (request4.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream2.resume.bind(stream2), "") === false) {
stream2.pause();
}
});
stream2.on("data", (chunk) => {
if (request4.onData(chunk) === false) {
stream2.pause();
}
});
stream2.once("end", (err) => {
stream2.removeAllListeners("data");
if (stream2.state?.state == null || stream2.state.state < 6) {
if (!request4.aborted && !request4.completed) {
request4.onComplete({});
}
client[kQueue][client[kRunningIdx]++] = null;
client[kResume]();
} else {
--session[kOpenStreams];
if (session[kOpenStreams] === 0) {
session.unref();
}
abort(err ?? new InformationalError("HTTP/2: stream half-closed (remote)"));
client[kQueue][client[kRunningIdx]++] = null;
client[kPendingIdx] = client[kRunningIdx];
client[kResume]();
}
});
stream2.once("close", () => {
stream2.removeAllListeners("data");
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) {
session.unref();
}
});
stream2.once("error", function(err) {
stream2.removeAllListeners("data");
abort(err);
});
stream2.once("frameError", (type, code) => {
stream2.removeAllListeners("data");
abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`));
});
stream2.on("aborted", () => {
stream2.removeAllListeners("data");
});
stream2.on("timeout", () => {
const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout2}"`);
stream2.removeAllListeners("data");
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) {
session.unref();
}
abort(err);
});
stream2.once("trailers", (trailers) => {
if (request4.aborted || request4.completed) {
return;
}
request4.onComplete(trailers);
});
return true;
function writeBodyH2() {
if (!body || contentLength === 0) {
writeBuffer(
abort,
stream2,
null,
client,
request4,
client[kSocket],
contentLength,
expectsPayload
);
} else if (util3.isBuffer(body)) {
writeBuffer(
abort,
stream2,
body,
client,
request4,
client[kSocket],
contentLength,
expectsPayload
);
} else if (util3.isBlobLike(body)) {
if (typeof body.stream === "function") {
writeIterable(
abort,
stream2,
body.stream(),
client,
request4,
client[kSocket],
contentLength,
expectsPayload
);
} else {
writeBlob(
abort,
stream2,
body,
client,
request4,
client[kSocket],
contentLength,
expectsPayload
);
}
} else if (util3.isStream(body)) {
writeStream(
abort,
client[kSocket],
expectsPayload,
stream2,
body,
client,
request4,
contentLength
);
} else if (util3.isIterable(body)) {
writeIterable(
abort,
stream2,
body,
client,
request4,
client[kSocket],
contentLength,
expectsPayload
);
} else {
assert44(false);
}
}
__name(writeBodyH2, "writeBodyH2");
}
__name(writeH2, "writeH2");
function writeBuffer(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
try {
if (body != null && util3.isBuffer(body)) {
assert44(contentLength === body.byteLength, "buffer body must have content length");
h2stream.cork();
h2stream.write(body);
h2stream.uncork();
h2stream.end();
request4.onBodySent(body);
}
if (!expectsPayload) {
socket[kReset2] = true;
}
request4.onRequestSent();
client[kResume]();
} catch (error2) {
abort(error2);
}
}
__name(writeBuffer, "writeBuffer");
function writeStream(abort, socket, expectsPayload, h2stream, body, client, request4, contentLength) {
assert44(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
const pipe = pipeline(
body,
h2stream,
(err) => {
if (err) {
util3.destroy(pipe, err);
abort(err);
} else {
util3.removeAllListeners(pipe);
request4.onRequestSent();
if (!expectsPayload) {
socket[kReset2] = true;
}
client[kResume]();
}
}
);
util3.addListener(pipe, "data", onPipeData);
function onPipeData(chunk) {
request4.onBodySent(chunk);
}
__name(onPipeData, "onPipeData");
}
__name(writeStream, "writeStream");
async function writeBlob(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
assert44(contentLength === body.size, "blob body must have content length");
try {
if (contentLength != null && contentLength !== body.size) {
throw new RequestContentLengthMismatchError();
}
const buffer = Buffer.from(await body.arrayBuffer());
h2stream.cork();
h2stream.write(buffer);
h2stream.uncork();
h2stream.end();
request4.onBodySent(buffer);
request4.onRequestSent();
if (!expectsPayload) {
socket[kReset2] = true;
}
client[kResume]();
} catch (err) {
abort(err);
}
}
__name(writeBlob, "writeBlob");
async function writeIterable(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
assert44(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
let callback = null;
function onDrain() {
if (callback) {
const cb2 = callback;
callback = null;
cb2();
}
}
__name(onDrain, "onDrain");
const waitForDrain = /* @__PURE__ */ __name(() => new Promise((resolve25, reject) => {
assert44(callback === null);
if (socket[kError]) {
reject(socket[kError]);
} else {
callback = resolve25;
}
}), "waitForDrain");
h2stream.on("close", onDrain).on("drain", onDrain);
try {
for await (const chunk of body) {
if (socket[kError]) {
throw socket[kError];
}
const res = h2stream.write(chunk);
request4.onBodySent(chunk);
if (!res) {
await waitForDrain();
}
}
h2stream.end();
request4.onRequestSent();
if (!expectsPayload) {
socket[kReset2] = true;
}
client[kResume]();
} catch (err) {
abort(err);
} finally {
h2stream.off("close", onDrain).off("drain", onDrain);
}
}
__name(writeIterable, "writeIterable");
module3.exports = connectH2;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/client.js
var require_client = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/client.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var net2 = require("net");
var http5 = require("http");
var util3 = require_util();
var { ClientStats } = require_stats();
var { channels } = require_diagnostics();
var Request4 = require_request();
var DispatcherBase = require_dispatcher_base();
var {
InvalidArgumentError,
InformationalError,
ClientDestroyedError
} = require_errors();
var buildConnector = require_connect();
var {
kUrl,
kServerName,
kClient,
kBusy,
kConnect,
kResuming,
kRunning,
kPending,
kSize,
kQueue,
kConnected,
kConnecting,
kNeedDrain,
kKeepAliveDefaultTimeout,
kHostHeader,
kPendingIdx,
kRunningIdx,
kError,
kPipelining,
kKeepAliveTimeoutValue,
kMaxHeadersSize,
kKeepAliveMaxTimeout,
kKeepAliveTimeoutThreshold,
kHeadersTimeout,
kBodyTimeout,
kStrictContentLength,
kConnector,
kMaxRequests,
kCounter,
kClose,
kDestroy,
kDispatch,
kLocalAddress,
kMaxResponseSize,
kOnError,
kHTTPContext,
kMaxConcurrentStreams,
kResume
} = require_symbols();
var connectH1 = require_client_h1();
var connectH2 = require_client_h2();
var kClosedResolve = Symbol("kClosedResolve");
var getDefaultNodeMaxHeaderSize = http5 && http5.maxHeaderSize && Number.isInteger(http5.maxHeaderSize) && http5.maxHeaderSize > 0 ? () => http5.maxHeaderSize : () => {
throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
};
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
function getPipelining(client) {
return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
}
__name(getPipelining, "getPipelining");
var Client2 = class extends DispatcherBase {
static {
__name(this, "Client");
}
/**
*
* @param {string|URL} url
* @param {import('../../types/client.js').Client.Options} options
*/
constructor(url4, {
maxHeaderSize,
headersTimeout,
socketTimeout,
requestTimeout: requestTimeout2,
connectTimeout,
bodyTimeout,
idleTimeout,
keepAlive,
keepAliveTimeout,
maxKeepAliveTimeout,
keepAliveMaxTimeout,
keepAliveTimeoutThreshold,
socketPath,
pipelining,
tls,
strictContentLength,
maxCachedSessions,
connect: connect2,
maxRequestsPerClient,
localAddress,
maxResponseSize,
autoSelectFamily,
autoSelectFamilyAttemptTimeout,
// h2
maxConcurrentStreams,
allowH2
} = {}) {
if (keepAlive !== void 0) {
throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
}
if (socketTimeout !== void 0) {
throw new InvalidArgumentError("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");
}
if (requestTimeout2 !== void 0) {
throw new InvalidArgumentError("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");
}
if (idleTimeout !== void 0) {
throw new InvalidArgumentError("unsupported idleTimeout, use keepAliveTimeout instead");
}
if (maxKeepAliveTimeout !== void 0) {
throw new InvalidArgumentError("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");
}
if (maxHeaderSize != null) {
if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
throw new InvalidArgumentError("invalid maxHeaderSize");
}
} else {
maxHeaderSize = getDefaultNodeMaxHeaderSize();
}
if (socketPath != null && typeof socketPath !== "string") {
throw new InvalidArgumentError("invalid socketPath");
}
if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
throw new InvalidArgumentError("invalid connectTimeout");
}
if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
throw new InvalidArgumentError("invalid keepAliveTimeout");
}
if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
throw new InvalidArgumentError("invalid keepAliveMaxTimeout");
}
if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
throw new InvalidArgumentError("invalid keepAliveTimeoutThreshold");
}
if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError("headersTimeout must be a positive integer or zero");
}
if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
throw new InvalidArgumentError("bodyTimeout must be a positive integer or zero");
}
if (connect2 != null && typeof connect2 !== "function" && typeof connect2 !== "object") {
throw new InvalidArgumentError("connect must be a function or an object");
}
if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
}
if (localAddress != null && (typeof localAddress !== "string" || net2.isIP(localAddress) === 0)) {
throw new InvalidArgumentError("localAddress must be valid string IP address");
}
if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
throw new InvalidArgumentError("maxResponseSize must be a positive number");
}
if (autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)) {
throw new InvalidArgumentError("autoSelectFamilyAttemptTimeout must be a positive number");
}
if (allowH2 != null && typeof allowH2 !== "boolean") {
throw new InvalidArgumentError("allowH2 must be a valid boolean value");
}
if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== "number" || maxConcurrentStreams < 1)) {
throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0");
}
super();
if (typeof connect2 !== "function") {
connect2 = buildConnector({
...tls,
maxCachedSessions,
allowH2,
socketPath,
timeout: connectTimeout,
...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
...connect2
});
}
this[kUrl] = util3.parseOrigin(url4);
this[kConnector] = connect2;
this[kPipelining] = pipelining != null ? pipelining : 1;
this[kMaxHeadersSize] = maxHeaderSize;
this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout;
this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout;
this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold;
this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout];
this[kServerName] = null;
this[kLocalAddress] = localAddress != null ? localAddress : null;
this[kResuming] = 0;
this[kNeedDrain] = 0;
this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ""}\r
`;
this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e5;
this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e5;
this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength;
this[kMaxRequests] = maxRequestsPerClient;
this[kClosedResolve] = null;
this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
this[kHTTPContext] = null;
this[kQueue] = [];
this[kRunningIdx] = 0;
this[kPendingIdx] = 0;
this[kResume] = (sync) => resume(this, sync);
this[kOnError] = (err) => onError(this, err);
}
get pipelining() {
return this[kPipelining];
}
set pipelining(value) {
this[kPipelining] = value;
this[kResume](true);
}
get stats() {
return new ClientStats(this);
}
get [kPending]() {
return this[kQueue].length - this[kPendingIdx];
}
get [kRunning]() {
return this[kPendingIdx] - this[kRunningIdx];
}
get [kSize]() {
return this[kQueue].length - this[kRunningIdx];
}
get [kConnected]() {
return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed;
}
get [kBusy]() {
return Boolean(
this[kHTTPContext]?.busy(null) || this[kSize] >= (getPipelining(this) || 1) || this[kPending] > 0
);
}
/* istanbul ignore: only used for test */
[kConnect](cb2) {
connect(this);
this.once("connect", cb2);
}
[kDispatch](opts, handler) {
const origin = opts.origin || this[kUrl].origin;
const request4 = new Request4(origin, opts, handler);
this[kQueue].push(request4);
if (this[kResuming]) {
} else if (util3.bodyLength(request4.body) == null && util3.isIterable(request4.body)) {
this[kResuming] = 1;
queueMicrotask(() => resume(this));
} else {
this[kResume](true);
}
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
this[kNeedDrain] = 2;
}
return this[kNeedDrain] < 2;
}
async [kClose]() {
return new Promise((resolve25) => {
if (this[kSize]) {
this[kClosedResolve] = resolve25;
} else {
resolve25(null);
}
});
}
async [kDestroy](err) {
return new Promise((resolve25) => {
const requests = this[kQueue].splice(this[kPendingIdx]);
for (let i5 = 0; i5 < requests.length; i5++) {
const request4 = requests[i5];
util3.errorRequest(this, request4, err);
}
const callback = /* @__PURE__ */ __name(() => {
if (this[kClosedResolve]) {
this[kClosedResolve]();
this[kClosedResolve] = null;
}
resolve25(null);
}, "callback");
if (this[kHTTPContext]) {
this[kHTTPContext].destroy(err, callback);
this[kHTTPContext] = null;
} else {
queueMicrotask(callback);
}
this[kResume]();
});
}
};
function onError(client, err) {
if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
assert44(client[kPendingIdx] === client[kRunningIdx]);
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i5 = 0; i5 < requests.length; i5++) {
const request4 = requests[i5];
util3.errorRequest(client, request4, err);
}
assert44(client[kSize] === 0);
}
}
__name(onError, "onError");
async function connect(client) {
assert44(!client[kConnecting]);
assert44(!client[kHTTPContext]);
let { host, hostname: hostname2, protocol, port } = client[kUrl];
if (hostname2[0] === "[") {
const idx = hostname2.indexOf("]");
assert44(idx !== -1);
const ip = hostname2.substring(1, idx);
assert44(net2.isIPv6(ip));
hostname2 = ip;
}
client[kConnecting] = true;
if (channels.beforeConnect.hasSubscribers) {
channels.beforeConnect.publish({
connectParams: {
host,
hostname: hostname2,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector]
});
}
try {
const socket = await new Promise((resolve25, reject) => {
client[kConnector]({
host,
hostname: hostname2,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
}, (err, socket2) => {
if (err) {
reject(err);
} else {
resolve25(socket2);
}
});
});
if (client.destroyed) {
util3.destroy(socket.on("error", noop), new ClientDestroyedError());
return;
}
assert44(socket);
try {
client[kHTTPContext] = socket.alpnProtocol === "h2" ? await connectH2(client, socket) : await connectH1(client, socket);
} catch (err) {
socket.destroy().on("error", noop);
throw err;
}
client[kConnecting] = false;
socket[kCounter] = 0;
socket[kMaxRequests] = client[kMaxRequests];
socket[kClient] = client;
socket[kError] = null;
if (channels.connected.hasSubscribers) {
channels.connected.publish({
connectParams: {
host,
hostname: hostname2,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
socket
});
}
client.emit("connect", client[kUrl], [client]);
} catch (err) {
if (client.destroyed) {
return;
}
client[kConnecting] = false;
if (channels.connectError.hasSubscribers) {
channels.connectError.publish({
connectParams: {
host,
hostname: hostname2,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
error: err
});
}
if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
assert44(client[kRunning] === 0);
while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
const request4 = client[kQueue][client[kPendingIdx]++];
util3.errorRequest(client, request4, err);
}
} else {
onError(client, err);
}
client.emit("connectionError", client[kUrl], [client], err);
}
client[kResume]();
}
__name(connect, "connect");
function emitDrain(client) {
client[kNeedDrain] = 0;
client.emit("drain", client[kUrl], [client]);
}
__name(emitDrain, "emitDrain");
function resume(client, sync) {
if (client[kResuming] === 2) {
return;
}
client[kResuming] = 2;
_resume(client, sync);
client[kResuming] = 0;
if (client[kRunningIdx] > 256) {
client[kQueue].splice(0, client[kRunningIdx]);
client[kPendingIdx] -= client[kRunningIdx];
client[kRunningIdx] = 0;
}
}
__name(resume, "resume");
function _resume(client, sync) {
while (true) {
if (client.destroyed) {
assert44(client[kPending] === 0);
return;
}
if (client[kClosedResolve] && !client[kSize]) {
client[kClosedResolve]();
client[kClosedResolve] = null;
return;
}
if (client[kHTTPContext]) {
client[kHTTPContext].resume();
}
if (client[kBusy]) {
client[kNeedDrain] = 2;
} else if (client[kNeedDrain] === 2) {
if (sync) {
client[kNeedDrain] = 1;
queueMicrotask(() => emitDrain(client));
} else {
emitDrain(client);
}
continue;
}
if (client[kPending] === 0) {
return;
}
if (client[kRunning] >= (getPipelining(client) || 1)) {
return;
}
const request4 = client[kQueue][client[kPendingIdx]];
if (client[kUrl].protocol === "https:" && client[kServerName] !== request4.servername) {
if (client[kRunning] > 0) {
return;
}
client[kServerName] = request4.servername;
client[kHTTPContext]?.destroy(new InformationalError("servername changed"), () => {
client[kHTTPContext] = null;
resume(client);
});
}
if (client[kConnecting]) {
return;
}
if (!client[kHTTPContext]) {
connect(client);
return;
}
if (client[kHTTPContext].destroyed) {
return;
}
if (client[kHTTPContext].busy(request4)) {
return;
}
if (!request4.aborted && client[kHTTPContext].write(request4)) {
client[kPendingIdx]++;
} else {
client[kQueue].splice(client[kPendingIdx], 1);
}
}
}
__name(_resume, "_resume");
module3.exports = Client2;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/fixed-queue.js
var require_fixed_queue = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/fixed-queue.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var kSize = 2048;
var kMask = kSize - 1;
var FixedCircularBuffer = class {
static {
__name(this, "FixedCircularBuffer");
}
constructor() {
this.bottom = 0;
this.top = 0;
this.list = new Array(kSize).fill(void 0);
this.next = null;
}
/**
* @returns {boolean}
*/
isEmpty() {
return this.top === this.bottom;
}
/**
* @returns {boolean}
*/
isFull() {
return (this.top + 1 & kMask) === this.bottom;
}
/**
* @param {T} data
* @returns {void}
*/
push(data) {
this.list[this.top] = data;
this.top = this.top + 1 & kMask;
}
/**
* @returns {T|null}
*/
shift() {
const nextItem = this.list[this.bottom];
if (nextItem === void 0) {
return null;
}
this.list[this.bottom] = void 0;
this.bottom = this.bottom + 1 & kMask;
return nextItem;
}
};
module3.exports = class FixedQueue {
static {
__name(this, "FixedQueue");
}
constructor() {
this.head = this.tail = new FixedCircularBuffer();
}
/**
* @returns {boolean}
*/
isEmpty() {
return this.head.isEmpty();
}
/**
* @param {T} data
*/
push(data) {
if (this.head.isFull()) {
this.head = this.head.next = new FixedCircularBuffer();
}
this.head.push(data);
}
/**
* @returns {T|null}
*/
shift() {
const tail = this.tail;
const next = tail.shift();
if (tail.isEmpty() && tail.next !== null) {
this.tail = tail.next;
tail.next = null;
}
return next;
}
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/pool-base.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { PoolStats } = require_stats();
var DispatcherBase = require_dispatcher_base();
var FixedQueue = require_fixed_queue();
var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
var kClients = Symbol("clients");
var kNeedDrain = Symbol("needDrain");
var kQueue = Symbol("queue");
var kClosedResolve = Symbol("closed resolve");
var kOnDrain = Symbol("onDrain");
var kOnConnect = Symbol("onConnect");
var kOnDisconnect = Symbol("onDisconnect");
var kOnConnectionError = Symbol("onConnectionError");
var kGetDispatcher = Symbol("get dispatcher");
var kAddClient = Symbol("add client");
var kRemoveClient = Symbol("remove client");
var PoolBase = class extends DispatcherBase {
static {
__name(this, "PoolBase");
}
constructor() {
super();
this[kQueue] = new FixedQueue();
this[kClients] = [];
this[kQueued] = 0;
const pool = this;
this[kOnDrain] = /* @__PURE__ */ __name(function onDrain(origin, targets) {
const queue = pool[kQueue];
let needDrain = false;
while (!needDrain) {
const item = queue.shift();
if (!item) {
break;
}
pool[kQueued]--;
needDrain = !this.dispatch(item.opts, item.handler);
}
this[kNeedDrain] = needDrain;
if (!this[kNeedDrain] && pool[kNeedDrain]) {
pool[kNeedDrain] = false;
pool.emit("drain", origin, [pool, ...targets]);
}
if (pool[kClosedResolve] && queue.isEmpty()) {
Promise.all(pool[kClients].map((c6) => c6.close())).then(pool[kClosedResolve]);
}
}, "onDrain");
this[kOnConnect] = (origin, targets) => {
pool.emit("connect", origin, [pool, ...targets]);
};
this[kOnDisconnect] = (origin, targets, err) => {
pool.emit("disconnect", origin, [pool, ...targets], err);
};
this[kOnConnectionError] = (origin, targets, err) => {
pool.emit("connectionError", origin, [pool, ...targets], err);
};
}
get [kBusy]() {
return this[kNeedDrain];
}
get [kConnected]() {
return this[kClients].filter((client) => client[kConnected]).length;
}
get [kFree]() {
return this[kClients].filter((client) => client[kConnected] && !client[kNeedDrain]).length;
}
get [kPending]() {
let ret = this[kQueued];
for (const { [kPending]: pending } of this[kClients]) {
ret += pending;
}
return ret;
}
get [kRunning]() {
let ret = 0;
for (const { [kRunning]: running } of this[kClients]) {
ret += running;
}
return ret;
}
get [kSize]() {
let ret = this[kQueued];
for (const { [kSize]: size } of this[kClients]) {
ret += size;
}
return ret;
}
get stats() {
return new PoolStats(this);
}
async [kClose]() {
if (this[kQueue].isEmpty()) {
await Promise.all(this[kClients].map((c6) => c6.close()));
} else {
await new Promise((resolve25) => {
this[kClosedResolve] = resolve25;
});
}
}
async [kDestroy](err) {
while (true) {
const item = this[kQueue].shift();
if (!item) {
break;
}
item.handler.onError(err);
}
await Promise.all(this[kClients].map((c6) => c6.destroy(err)));
}
[kDispatch](opts, handler) {
const dispatcher = this[kGetDispatcher]();
if (!dispatcher) {
this[kNeedDrain] = true;
this[kQueue].push({ opts, handler });
this[kQueued]++;
} else if (!dispatcher.dispatch(opts, handler)) {
dispatcher[kNeedDrain] = true;
this[kNeedDrain] = !this[kGetDispatcher]();
}
return !this[kNeedDrain];
}
[kAddClient](client) {
client.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
this[kClients].push(client);
if (this[kNeedDrain]) {
queueMicrotask(() => {
if (this[kNeedDrain]) {
this[kOnDrain](client[kUrl], [this, client]);
}
});
}
return this;
}
[kRemoveClient](client) {
client.close(() => {
const idx = this[kClients].indexOf(client);
if (idx !== -1) {
this[kClients].splice(idx, 1);
}
});
this[kNeedDrain] = this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
}
};
module3.exports = {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kGetDispatcher
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/pool.js
var require_pool = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/pool.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kGetDispatcher,
kRemoveClient
} = require_pool_base();
var Client2 = require_client();
var {
InvalidArgumentError
} = require_errors();
var util3 = require_util();
var { kUrl } = require_symbols();
var buildConnector = require_connect();
var kOptions = Symbol("options");
var kConnections = Symbol("connections");
var kFactory = Symbol("factory");
function defaultFactory(origin, opts) {
return new Client2(origin, opts);
}
__name(defaultFactory, "defaultFactory");
var Pool = class extends PoolBase {
static {
__name(this, "Pool");
}
constructor(origin, {
connections,
factory = defaultFactory,
connect,
connectTimeout,
tls,
maxCachedSessions,
socketPath,
autoSelectFamily,
autoSelectFamilyAttemptTimeout,
allowH2,
clientTtl,
...options
} = {}) {
if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
throw new InvalidArgumentError("invalid connections");
}
if (typeof factory !== "function") {
throw new InvalidArgumentError("factory must be a function.");
}
if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
throw new InvalidArgumentError("connect must be a function or an object");
}
super();
if (typeof connect !== "function") {
connect = buildConnector({
...tls,
maxCachedSessions,
allowH2,
socketPath,
timeout: connectTimeout,
...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
...connect
});
}
this[kConnections] = connections || null;
this[kUrl] = util3.parseOrigin(origin);
this[kOptions] = { ...util3.deepClone(options), connect, allowH2, clientTtl };
this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
this[kFactory] = factory;
this.on("connect", (origin2, targets) => {
if (clientTtl != null && clientTtl > 0) {
for (const target of targets) {
Object.assign(target, { ttl: Date.now() });
}
}
});
this.on("connectionError", (origin2, targets, error2) => {
for (const target of targets) {
const idx = this[kClients].indexOf(target);
if (idx !== -1) {
this[kClients].splice(idx, 1);
}
}
});
}
[kGetDispatcher]() {
const clientTtlOption = this[kOptions].clientTtl;
for (const client of this[kClients]) {
if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
this[kRemoveClient](client);
} else if (!client[kNeedDrain]) {
return client;
}
}
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
this[kAddClient](dispatcher);
return dispatcher;
}
}
};
module3.exports = Pool;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/balanced-pool.js
var require_balanced_pool = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/balanced-pool.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
BalancedPoolMissingUpstreamError,
InvalidArgumentError
} = require_errors();
var {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kGetDispatcher
} = require_pool_base();
var Pool = require_pool();
var { kUrl } = require_symbols();
var { parseOrigin } = require_util();
var kFactory = Symbol("factory");
var kOptions = Symbol("options");
var kGreatestCommonDivisor = Symbol("kGreatestCommonDivisor");
var kCurrentWeight = Symbol("kCurrentWeight");
var kIndex = Symbol("kIndex");
var kWeight = Symbol("kWeight");
var kMaxWeightPerServer = Symbol("kMaxWeightPerServer");
var kErrorPenalty = Symbol("kErrorPenalty");
function getGreatestCommonDivisor(a5, b6) {
if (a5 === 0) return b6;
while (b6 !== 0) {
const t7 = b6;
b6 = a5 % b6;
a5 = t7;
}
return a5;
}
__name(getGreatestCommonDivisor, "getGreatestCommonDivisor");
function defaultFactory(origin, opts) {
return new Pool(origin, opts);
}
__name(defaultFactory, "defaultFactory");
var BalancedPool = class extends PoolBase {
static {
__name(this, "BalancedPool");
}
constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
if (typeof factory !== "function") {
throw new InvalidArgumentError("factory must be a function.");
}
super();
this[kOptions] = opts;
this[kIndex] = -1;
this[kCurrentWeight] = 0;
this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
this[kErrorPenalty] = this[kOptions].errorPenalty || 15;
if (!Array.isArray(upstreams)) {
upstreams = [upstreams];
}
this[kFactory] = factory;
for (const upstream of upstreams) {
this.addUpstream(upstream);
}
this._updateBalancedPoolStats();
}
addUpstream(upstream) {
const upstreamOrigin = parseOrigin(upstream).origin;
if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
return this;
}
const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]));
this[kAddClient](pool);
pool.on("connect", () => {
pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
});
pool.on("connectionError", () => {
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
this._updateBalancedPoolStats();
});
pool.on("disconnect", (...args) => {
const err = args[2];
if (err && err.code === "UND_ERR_SOCKET") {
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
this._updateBalancedPoolStats();
}
});
for (const client of this[kClients]) {
client[kWeight] = this[kMaxWeightPerServer];
}
this._updateBalancedPoolStats();
return this;
}
_updateBalancedPoolStats() {
let result = 0;
for (let i5 = 0; i5 < this[kClients].length; i5++) {
result = getGreatestCommonDivisor(this[kClients][i5][kWeight], result);
}
this[kGreatestCommonDivisor] = result;
}
removeUpstream(upstream) {
const upstreamOrigin = parseOrigin(upstream).origin;
const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
if (pool) {
this[kRemoveClient](pool);
}
return this;
}
get upstreams() {
return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p6) => p6[kUrl].origin);
}
[kGetDispatcher]() {
if (this[kClients].length === 0) {
throw new BalancedPoolMissingUpstreamError();
}
const dispatcher = this[kClients].find((dispatcher2) => !dispatcher2[kNeedDrain] && dispatcher2.closed !== true && dispatcher2.destroyed !== true);
if (!dispatcher) {
return;
}
const allClientsBusy = this[kClients].map((pool) => pool[kNeedDrain]).reduce((a5, b6) => a5 && b6, true);
if (allClientsBusy) {
return;
}
let counter = 0;
let maxWeightIndex = this[kClients].findIndex((pool) => !pool[kNeedDrain]);
while (counter++ < this[kClients].length) {
this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
const pool = this[kClients][this[kIndex]];
if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
maxWeightIndex = this[kIndex];
}
if (this[kIndex] === 0) {
this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor];
if (this[kCurrentWeight] <= 0) {
this[kCurrentWeight] = this[kMaxWeightPerServer];
}
}
if (pool[kWeight] >= this[kCurrentWeight] && !pool[kNeedDrain]) {
return pool;
}
}
this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight];
this[kIndex] = maxWeightIndex;
return this[kClients][maxWeightIndex];
}
};
module3.exports = BalancedPool;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/agent.js
var require_agent = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/agent.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { InvalidArgumentError } = require_errors();
var { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
var DispatcherBase = require_dispatcher_base();
var Pool = require_pool();
var Client2 = require_client();
var util3 = require_util();
var kOnConnect = Symbol("onConnect");
var kOnDisconnect = Symbol("onDisconnect");
var kOnConnectionError = Symbol("onConnectionError");
var kOnDrain = Symbol("onDrain");
var kFactory = Symbol("factory");
var kOptions = Symbol("options");
function defaultFactory(origin, opts) {
return opts && opts.connections === 1 ? new Client2(origin, opts) : new Pool(origin, opts);
}
__name(defaultFactory, "defaultFactory");
var Agent = class extends DispatcherBase {
static {
__name(this, "Agent");
}
constructor({ factory = defaultFactory, connect, ...options } = {}) {
if (typeof factory !== "function") {
throw new InvalidArgumentError("factory must be a function.");
}
if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
throw new InvalidArgumentError("connect must be a function or an object");
}
super();
if (connect && typeof connect !== "function") {
connect = { ...connect };
}
this[kOptions] = { ...util3.deepClone(options), connect };
this[kFactory] = factory;
this[kClients] = /* @__PURE__ */ new Map();
this[kOnDrain] = (origin, targets) => {
this.emit("drain", origin, [this, ...targets]);
};
this[kOnConnect] = (origin, targets) => {
const result = this[kClients].get(origin);
if (result) {
result.count += 1;
}
this.emit("connect", origin, [this, ...targets]);
};
this[kOnDisconnect] = (origin, targets, err) => {
const result = this[kClients].get(origin);
if (result) {
result.count -= 1;
if (result.count <= 0) {
this[kClients].delete(origin);
result.dispatcher.destroy();
}
}
this.emit("disconnect", origin, [this, ...targets], err);
};
this[kOnConnectionError] = (origin, targets, err) => {
this.emit("connectionError", origin, [this, ...targets], err);
};
}
get [kRunning]() {
let ret = 0;
for (const { dispatcher } of this[kClients].values()) {
ret += dispatcher[kRunning];
}
return ret;
}
[kDispatch](opts, handler) {
let key;
if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
key = String(opts.origin);
} else {
throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
}
const result = this[kClients].get(key);
let dispatcher = result && result.dispatcher;
if (!dispatcher) {
dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
this[kClients].set(key, { count: 0, dispatcher });
}
return dispatcher.dispatch(opts, handler);
}
async [kClose]() {
const closePromises = [];
for (const { dispatcher } of this[kClients].values()) {
closePromises.push(dispatcher.close());
}
this[kClients].clear();
await Promise.all(closePromises);
}
async [kDestroy](err) {
const destroyPromises = [];
for (const { dispatcher } of this[kClients].values()) {
destroyPromises.push(dispatcher.destroy(err));
}
this[kClients].clear();
await Promise.all(destroyPromises);
}
get stats() {
const allClientStats = {};
for (const { dispatcher } of this[kClients].values()) {
if (dispatcher.stats) {
allClientStats[dispatcher[kUrl].origin] = dispatcher.stats;
}
}
return allClientStats;
}
};
module3.exports = Agent;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { kProxy, kClose, kDestroy, kDispatch, kConnector } = require_symbols();
var { URL: URL7 } = require("url");
var Agent = require_agent();
var Pool = require_pool();
var DispatcherBase = require_dispatcher_base();
var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
var buildConnector = require_connect();
var Client2 = require_client();
var kAgent = Symbol("proxy agent");
var kClient = Symbol("proxy client");
var kProxyHeaders = Symbol("proxy headers");
var kRequestTls = Symbol("request tls settings");
var kProxyTls = Symbol("proxy tls settings");
var kConnectEndpoint = Symbol("connect endpoint function");
var kTunnelProxy = Symbol("tunnel proxy");
function defaultProtocolPort(protocol) {
return protocol === "https:" ? 443 : 80;
}
__name(defaultProtocolPort, "defaultProtocolPort");
function defaultFactory(origin, opts) {
return new Pool(origin, opts);
}
__name(defaultFactory, "defaultFactory");
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
var ProxyClient = class extends DispatcherBase {
static {
__name(this, "ProxyClient");
}
#client = null;
constructor(origin, opts) {
if (typeof origin === "string") {
origin = new URL7(origin);
}
if (origin.protocol !== "http:" && origin.protocol !== "https:") {
throw new InvalidArgumentError("ProxyClient only supports http and https protocols");
}
super();
this.#client = new Client2(origin, opts);
}
async [kClose]() {
await this.#client.close();
}
async [kDestroy]() {
await this.#client.destroy();
}
async [kDispatch](opts, handler) {
const { method, origin } = opts;
if (method === "CONNECT") {
this.#client[kConnector](
{
origin,
port: opts.port || defaultProtocolPort(opts.protocol),
path: opts.host,
signal: opts.signal,
headers: {
...this[kProxyHeaders],
host: opts.host
},
servername: this[kProxyTls]?.servername || opts.servername
},
(err, socket) => {
if (err) {
handler.callback(err);
} else {
handler.callback(null, { socket, statusCode: 200 });
}
}
);
return;
}
if (typeof origin === "string") {
opts.origin = new URL7(origin);
}
return this.#client.dispatch(opts, handler);
}
};
var ProxyAgent2 = class extends DispatcherBase {
static {
__name(this, "ProxyAgent");
}
constructor(opts) {
if (!opts || typeof opts === "object" && !(opts instanceof URL7) && !opts.uri) {
throw new InvalidArgumentError("Proxy uri is mandatory");
}
const { clientFactory = defaultFactory } = opts;
if (typeof clientFactory !== "function") {
throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.");
}
const { proxyTunnel = true } = opts;
super();
const url4 = this.#getUrl(opts);
const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url4;
this[kProxy] = { uri: href, protocol };
this[kRequestTls] = opts.requestTls;
this[kProxyTls] = opts.proxyTls;
this[kProxyHeaders] = opts.headers || {};
if (opts.auth && opts.token) {
throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
} else if (opts.auth) {
this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`;
} else if (opts.token) {
this[kProxyHeaders]["proxy-authorization"] = opts.token;
} else if (username && password) {
this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`;
}
const factory = !proxyTunnel && protocol === "http:" ? (origin2, options) => {
if (origin2.protocol === "http:") {
return new ProxyClient(origin2, options);
}
return new Client2(origin2, options);
} : void 0;
const connect = buildConnector({ ...opts.proxyTls });
this[kConnectEndpoint] = buildConnector({ ...opts.requestTls });
this[kClient] = clientFactory(url4, { connect, factory });
this[kTunnelProxy] = proxyTunnel;
this[kAgent] = new Agent({
...opts,
connect: /* @__PURE__ */ __name(async (opts2, callback) => {
let requestedPath = opts2.host;
if (!opts2.port) {
requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
}
try {
const { socket, statusCode } = await this[kClient].connect({
origin,
port,
path: requestedPath,
signal: opts2.signal,
headers: {
...this[kProxyHeaders],
host: opts2.host,
...opts2.connections == null || opts2.connections > 0 ? { "proxy-connection": "keep-alive" } : {}
},
servername: this[kProxyTls]?.servername || proxyHostname
});
if (statusCode !== 200) {
socket.on("error", noop).destroy();
callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
}
if (opts2.protocol !== "https:") {
callback(null, socket);
return;
}
let servername;
if (this[kRequestTls]) {
servername = this[kRequestTls].servername;
} else {
servername = opts2.servername;
}
this[kConnectEndpoint]({ ...opts2, servername, httpSocket: socket }, callback);
} catch (err) {
if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
callback(new SecureProxyConnectionError(err));
} else {
callback(err);
}
}
}, "connect")
});
}
dispatch(opts, handler) {
const headers = buildHeaders(opts.headers);
throwIfProxyAuthIsSent(headers);
if (headers && !("host" in headers) && !("Host" in headers)) {
const { host } = new URL7(opts.origin);
headers.host = host;
}
if (!this.#shouldConnect(new URL7(opts.origin))) {
opts.path = opts.origin + opts.path;
}
return this[kAgent].dispatch(
{
...opts,
headers
},
handler
);
}
/**
* @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts
* @returns {URL}
*/
#getUrl(opts) {
if (typeof opts === "string") {
return new URL7(opts);
} else if (opts instanceof URL7) {
return opts;
} else {
return new URL7(opts.uri);
}
}
async [kClose]() {
await this[kAgent].close();
await this[kClient].close();
}
async [kDestroy]() {
await this[kAgent].destroy();
await this[kClient].destroy();
}
#shouldConnect(uri) {
if (typeof uri === "string") {
uri = new URL7(uri);
}
if (this[kTunnelProxy]) {
return true;
}
if (uri.protocol !== "http:" || this[kProxy].protocol !== "http:") {
return true;
}
return false;
}
};
function buildHeaders(headers) {
if (Array.isArray(headers)) {
const headersPair = {};
for (let i5 = 0; i5 < headers.length; i5 += 2) {
headersPair[headers[i5]] = headers[i5 + 1];
}
return headersPair;
}
return headers;
}
__name(buildHeaders, "buildHeaders");
function throwIfProxyAuthIsSent(headers) {
const existProxyAuth = headers && Object.keys(headers).find((key) => key.toLowerCase() === "proxy-authorization");
if (existProxyAuth) {
throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
}
}
__name(throwIfProxyAuthIsSent, "throwIfProxyAuthIsSent");
module3.exports = ProxyAgent2;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DispatcherBase = require_dispatcher_base();
var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
var ProxyAgent2 = require_proxy_agent();
var Agent = require_agent();
var DEFAULT_PORTS2 = {
"http:": 80,
"https:": 443
};
var EnvHttpProxyAgent = class extends DispatcherBase {
static {
__name(this, "EnvHttpProxyAgent");
}
#noProxyValue = null;
#noProxyEntries = null;
#opts = null;
constructor(opts = {}) {
super();
this.#opts = opts;
const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
this[kNoProxyAgent] = new Agent(agentOpts);
const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
if (HTTP_PROXY) {
this[kHttpProxyAgent] = new ProxyAgent2({ ...agentOpts, uri: HTTP_PROXY });
} else {
this[kHttpProxyAgent] = this[kNoProxyAgent];
}
const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY;
if (HTTPS_PROXY) {
this[kHttpsProxyAgent] = new ProxyAgent2({ ...agentOpts, uri: HTTPS_PROXY });
} else {
this[kHttpsProxyAgent] = this[kHttpProxyAgent];
}
this.#parseNoProxy();
}
[kDispatch](opts, handler) {
const url4 = new URL(opts.origin);
const agent = this.#getProxyAgentForUrl(url4);
return agent.dispatch(opts, handler);
}
async [kClose]() {
await this[kNoProxyAgent].close();
if (!this[kHttpProxyAgent][kClosed]) {
await this[kHttpProxyAgent].close();
}
if (!this[kHttpsProxyAgent][kClosed]) {
await this[kHttpsProxyAgent].close();
}
}
async [kDestroy](err) {
await this[kNoProxyAgent].destroy(err);
if (!this[kHttpProxyAgent][kDestroyed]) {
await this[kHttpProxyAgent].destroy(err);
}
if (!this[kHttpsProxyAgent][kDestroyed]) {
await this[kHttpsProxyAgent].destroy(err);
}
}
#getProxyAgentForUrl(url4) {
let { protocol, host: hostname2, port } = url4;
hostname2 = hostname2.replace(/:\d*$/, "").toLowerCase();
port = Number.parseInt(port, 10) || DEFAULT_PORTS2[protocol] || 0;
if (!this.#shouldProxy(hostname2, port)) {
return this[kNoProxyAgent];
}
if (protocol === "https:") {
return this[kHttpsProxyAgent];
}
return this[kHttpProxyAgent];
}
#shouldProxy(hostname2, port) {
if (this.#noProxyChanged) {
this.#parseNoProxy();
}
if (this.#noProxyEntries.length === 0) {
return true;
}
if (this.#noProxyValue === "*") {
return false;
}
for (let i5 = 0; i5 < this.#noProxyEntries.length; i5++) {
const entry = this.#noProxyEntries[i5];
if (entry.port && entry.port !== port) {
continue;
}
if (!/^[.*]/.test(entry.hostname)) {
if (hostname2 === entry.hostname) {
return false;
}
} else {
if (hostname2.endsWith(entry.hostname.replace(/^\*/, ""))) {
return false;
}
}
}
return true;
}
#parseNoProxy() {
const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv;
const noProxySplit = noProxyValue.split(/[,\s]/);
const noProxyEntries = [];
for (let i5 = 0; i5 < noProxySplit.length; i5++) {
const entry = noProxySplit[i5];
if (!entry) {
continue;
}
const parsed = entry.match(/^(.+):(\d+)$/);
noProxyEntries.push({
hostname: (parsed ? parsed[1] : entry).toLowerCase(),
port: parsed ? Number.parseInt(parsed[2], 10) : 0
});
}
this.#noProxyValue = noProxyValue;
this.#noProxyEntries = noProxyEntries;
}
get #noProxyChanged() {
if (this.#opts.noProxy !== void 0) {
return false;
}
return this.#noProxyValue !== this.#noProxyEnv;
}
get #noProxyEnv() {
return process.env.no_proxy ?? process.env.NO_PROXY ?? "";
}
};
module3.exports = EnvHttpProxyAgent;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/retry-handler.js
var require_retry_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/retry-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { kRetryHandlerDefaultRetry } = require_symbols();
var { RequestRetryError } = require_errors();
var WrapHandler = require_wrap_handler();
var {
isDisturbed,
parseRangeHeader,
wrapRequestBody
} = require_util();
function calculateRetryAfterHeader(retryAfter) {
const retryTime = new Date(retryAfter).getTime();
return isNaN(retryTime) ? 0 : retryTime - Date.now();
}
__name(calculateRetryAfterHeader, "calculateRetryAfterHeader");
var RetryHandler = class _RetryHandler {
static {
__name(this, "RetryHandler");
}
constructor(opts, { dispatch, handler }) {
const { retryOptions, ...dispatchOpts } = opts;
const {
// Retry scoped
retry: retryFn,
maxRetries,
maxTimeout,
minTimeout,
timeoutFactor,
// Response scoped
methods,
errorCodes,
retryAfter,
statusCodes,
throwOnError
} = retryOptions ?? {};
this.error = null;
this.dispatch = dispatch;
this.handler = WrapHandler.wrap(handler);
this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
this.retryOpts = {
throwOnError: throwOnError ?? true,
retry: retryFn ?? _RetryHandler[kRetryHandlerDefaultRetry],
retryAfter: retryAfter ?? true,
maxTimeout: maxTimeout ?? 30 * 1e3,
// 30s,
minTimeout: minTimeout ?? 500,
// .5s
timeoutFactor: timeoutFactor ?? 2,
maxRetries: maxRetries ?? 5,
// What errors we should retry
methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"],
// Indicates which errors to retry
statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
// List of errors to retry
errorCodes: errorCodes ?? [
"ECONNRESET",
"ECONNREFUSED",
"ENOTFOUND",
"ENETDOWN",
"ENETUNREACH",
"EHOSTDOWN",
"EHOSTUNREACH",
"EPIPE",
"UND_ERR_SOCKET"
]
};
this.retryCount = 0;
this.retryCountCheckpoint = 0;
this.headersSent = false;
this.start = 0;
this.end = null;
this.etag = null;
}
onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) {
if (this.retryOpts.throwOnError) {
if (this.retryOpts.statusCodes.includes(statusCode) === false) {
this.headersSent = true;
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
} else {
this.error = err;
}
return;
}
if (isDisturbed(this.opts.body)) {
this.headersSent = true;
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
return;
}
function shouldRetry(passedErr) {
if (passedErr) {
this.headersSent = true;
this.headersSent = true;
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
controller.resume();
return;
}
this.error = err;
controller.resume();
}
__name(shouldRetry, "shouldRetry");
controller.pause();
this.retryOpts.retry(
err,
{
state: { counter: this.retryCount },
opts: { retryOptions: this.retryOpts, ...this.opts }
},
shouldRetry.bind(this)
);
}
onRequestStart(controller, context2) {
if (!this.headersSent) {
this.handler.onRequestStart?.(controller, context2);
}
}
onRequestUpgrade(controller, statusCode, headers, socket) {
this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
static [kRetryHandlerDefaultRetry](err, { state: state2, opts }, cb2) {
const { statusCode, code, headers } = err;
const { method, retryOptions } = opts;
const {
maxRetries,
minTimeout,
maxTimeout,
timeoutFactor,
statusCodes,
errorCodes,
methods
} = retryOptions;
const { counter } = state2;
if (code && code !== "UND_ERR_REQ_RETRY" && !errorCodes.includes(code)) {
cb2(err);
return;
}
if (Array.isArray(methods) && !methods.includes(method)) {
cb2(err);
return;
}
if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
cb2(err);
return;
}
if (counter > maxRetries) {
cb2(err);
return;
}
let retryAfterHeader = headers?.["retry-after"];
if (retryAfterHeader) {
retryAfterHeader = Number(retryAfterHeader);
retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers["retry-after"]) : retryAfterHeader * 1e3;
}
const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
setTimeout(() => cb2(null), retryTimeout);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
this.error = null;
this.retryCount += 1;
if (statusCode >= 300) {
const err = new RequestRetryError("Request failed", statusCode, {
headers,
data: {
count: this.retryCount
}
});
this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err);
return;
}
if (this.headersSent) {
if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
throw new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, {
headers,
data: { count: this.retryCount }
});
}
const contentRange = parseRangeHeader(headers["content-range"]);
if (!contentRange) {
throw new RequestRetryError("Content-Range mismatch", statusCode, {
headers,
data: { count: this.retryCount }
});
}
if (this.etag != null && this.etag !== headers.etag) {
throw new RequestRetryError("ETag mismatch", statusCode, {
headers,
data: { count: this.retryCount }
});
}
const { start, size, end = size ? size - 1 : null } = contentRange;
assert44(this.start === start, "content-range mismatch");
assert44(this.end == null || this.end === end, "content-range mismatch");
return;
}
if (this.end == null) {
if (statusCode === 206) {
const range = parseRangeHeader(headers["content-range"]);
if (range == null) {
this.headersSent = true;
this.handler.onResponseStart?.(
controller,
statusCode,
headers,
statusMessage
);
return;
}
const { start, size, end = size ? size - 1 : null } = range;
assert44(
start != null && Number.isFinite(start),
"content-range mismatch"
);
assert44(end != null && Number.isFinite(end), "invalid content-length");
this.start = start;
this.end = end;
}
if (this.end == null) {
const contentLength = headers["content-length"];
this.end = contentLength != null ? Number(contentLength) - 1 : null;
}
assert44(Number.isFinite(this.start));
assert44(
this.end == null || Number.isFinite(this.end),
"invalid content-length"
);
this.resume = true;
this.etag = headers.etag != null ? headers.etag : null;
if (this.etag != null && this.etag[0] === "W" && this.etag[1] === "/") {
this.etag = null;
}
this.headersSent = true;
this.handler.onResponseStart?.(
controller,
statusCode,
headers,
statusMessage
);
} else {
throw new RequestRetryError("Request failed", statusCode, {
headers,
data: { count: this.retryCount }
});
}
}
onResponseData(controller, chunk) {
if (this.error) {
return;
}
this.start += chunk.length;
this.handler.onResponseData?.(controller, chunk);
}
onResponseEnd(controller, trailers) {
if (this.error && this.retryOpts.throwOnError) {
throw this.error;
}
if (!this.error) {
this.retryCount = 0;
return this.handler.onResponseEnd?.(controller, trailers);
}
this.retry(controller);
}
retry(controller) {
if (this.start !== 0) {
const headers = { range: `bytes=${this.start}-${this.end ?? ""}` };
if (this.etag != null) {
headers["if-match"] = this.etag;
}
this.opts = {
...this.opts,
headers: {
...this.opts.headers,
...headers
}
};
}
try {
this.retryCountCheckpoint = this.retryCount;
this.dispatch(this.opts, this);
} catch (err) {
this.handler.onResponseError?.(controller, err);
}
}
onResponseError(controller, err) {
if (controller?.aborted || isDisturbed(this.opts.body)) {
this.handler.onResponseError?.(controller, err);
return;
}
function shouldRetry(returnedErr) {
if (!returnedErr) {
this.retry(controller);
return;
}
this.handler?.onResponseError?.(controller, returnedErr);
}
__name(shouldRetry, "shouldRetry");
if (this.retryCount - this.retryCountCheckpoint > 0) {
this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
} else {
this.retryCount += 1;
}
this.retryOpts.retry(
err,
{
state: { counter: this.retryCount },
opts: { retryOptions: this.retryOpts, ...this.opts }
},
shouldRetry.bind(this)
);
}
};
module3.exports = RetryHandler;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/retry-agent.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var Dispatcher2 = require_dispatcher();
var RetryHandler = require_retry_handler();
var RetryAgent = class extends Dispatcher2 {
static {
__name(this, "RetryAgent");
}
#agent = null;
#options = null;
constructor(agent, options = {}) {
super(options);
this.#agent = agent;
this.#options = options;
}
dispatch(opts, handler) {
const retry2 = new RetryHandler({
...opts,
retryOptions: this.#options
}, {
dispatch: this.#agent.dispatch.bind(this.#agent),
handler
});
return this.#agent.dispatch(opts, retry2);
}
close() {
return this.#agent.close();
}
destroy() {
return this.#agent.destroy();
}
};
module3.exports = RetryAgent;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/h2c-client.js
var require_h2c_client = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/dispatcher/h2c-client.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { connect } = require("net");
var { kClose, kDestroy } = require_symbols();
var { InvalidArgumentError } = require_errors();
var util3 = require_util();
var Client2 = require_client();
var DispatcherBase = require_dispatcher_base();
var H2CClient = class extends DispatcherBase {
static {
__name(this, "H2CClient");
}
#client = null;
constructor(origin, clientOpts) {
super();
if (typeof origin === "string") {
origin = new URL(origin);
}
if (origin.protocol !== "http:") {
throw new InvalidArgumentError(
"h2c-client: Only h2c protocol is supported"
);
}
const { connect: connect2, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
let defaultMaxConcurrentStreams = 100;
let defaultPipelining = 100;
if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
defaultMaxConcurrentStreams = maxConcurrentStreams;
}
if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
defaultPipelining = pipelining;
}
if (defaultPipelining > defaultMaxConcurrentStreams) {
throw new InvalidArgumentError(
"h2c-client: pipelining cannot be greater than maxConcurrentStreams"
);
}
this.#client = new Client2(origin, {
...opts,
connect: this.#buildConnector(connect2),
maxConcurrentStreams: defaultMaxConcurrentStreams,
pipelining: defaultPipelining,
allowH2: true
});
}
#buildConnector(connectOpts) {
return (opts, callback) => {
const timeout2 = connectOpts?.connectOpts ?? 1e4;
const { hostname: hostname2, port, pathname } = opts;
const socket = connect({
...opts,
host: hostname2,
port,
pathname
});
if (opts.keepAlive == null || opts.keepAlive) {
const keepAliveInitialDelay = opts.keepAliveInitialDelay == null ? 6e4 : opts.keepAliveInitialDelay;
socket.setKeepAlive(true, keepAliveInitialDelay);
}
socket.alpnProtocol = "h2";
const clearConnectTimeout = util3.setupConnectTimeout(
new WeakRef(socket),
{ timeout: timeout2, hostname: hostname2, port }
);
socket.setNoDelay(true).once("connect", function() {
queueMicrotask(clearConnectTimeout);
if (callback) {
const cb2 = callback;
callback = null;
cb2(null, this);
}
}).on("error", function(err) {
queueMicrotask(clearConnectTimeout);
if (callback) {
const cb2 = callback;
callback = null;
cb2(err);
}
});
return socket;
};
}
dispatch(opts, handler) {
return this.#client.dispatch(opts, handler);
}
async [kClose]() {
await this.#client.close();
}
async [kDestroy]() {
await this.#client.destroy();
}
};
module3.exports = H2CClient;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/readable.js
var require_readable = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/readable.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { Readable: Readable8 } = require("stream");
var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError2 } = require_errors();
var util3 = require_util();
var { ReadableStreamFrom } = require_util();
var kConsume = Symbol("kConsume");
var kReading = Symbol("kReading");
var kBody = Symbol("kBody");
var kAbort = Symbol("kAbort");
var kContentType = Symbol("kContentType");
var kContentLength = Symbol("kContentLength");
var kUsed = Symbol("kUsed");
var kBytesRead = Symbol("kBytesRead");
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
var BodyReadable = class extends Readable8 {
static {
__name(this, "BodyReadable");
}
/**
* @param {object} opts
* @param {(this: Readable, size: number) => void} opts.resume
* @param {() => (void | null)} opts.abort
* @param {string} [opts.contentType = '']
* @param {number} [opts.contentLength]
* @param {number} [opts.highWaterMark = 64 * 1024]
*/
constructor({
resume,
abort,
contentType = "",
contentLength,
highWaterMark = 64 * 1024
// Same as nodejs fs streams.
}) {
super({
autoDestroy: true,
read: resume,
highWaterMark
});
this._readableState.dataEmitted = false;
this[kAbort] = abort;
this[kConsume] = null;
this[kBytesRead] = 0;
this[kBody] = null;
this[kUsed] = false;
this[kContentType] = contentType;
this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null;
this[kReading] = false;
}
/**
* @param {Error|null} err
* @param {(error:(Error|null)) => void} callback
* @returns {void}
*/
_destroy(err, callback) {
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError();
}
if (err) {
this[kAbort]();
}
if (!this[kUsed]) {
setImmediate(() => {
callback(err);
});
} else {
callback(err);
}
}
/**
* @param {string} event
* @param {(...args: any[]) => void} listener
* @returns {this}
*/
on(event, listener) {
if (event === "data" || event === "readable") {
this[kReading] = true;
this[kUsed] = true;
}
return super.on(event, listener);
}
/**
* @param {string} event
* @param {(...args: any[]) => void} listener
* @returns {this}
*/
addListener(event, listener) {
return this.on(event, listener);
}
/**
* @param {string|symbol} event
* @param {(...args: any[]) => void} listener
* @returns {this}
*/
off(event, listener) {
const ret = super.off(event, listener);
if (event === "data" || event === "readable") {
this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
}
return ret;
}
/**
* @param {string|symbol} event
* @param {(...args: any[]) => void} listener
* @returns {this}
*/
removeListener(event, listener) {
return this.off(event, listener);
}
/**
* @param {Buffer|null} chunk
* @returns {boolean}
*/
push(chunk) {
this[kBytesRead] += chunk ? chunk.length : 0;
if (this[kConsume] && chunk !== null) {
consumePush(this[kConsume], chunk);
return this[kReading] ? super.push(chunk) : true;
}
return super.push(chunk);
}
/**
* Consumes and returns the body as a string.
*
* @see https://fetch.spec.whatwg.org/#dom-body-text
* @returns {Promise<string>}
*/
text() {
return consume(this, "text");
}
/**
* Consumes and returns the body as a JavaScript Object.
*
* @see https://fetch.spec.whatwg.org/#dom-body-json
* @returns {Promise<unknown>}
*/
json() {
return consume(this, "json");
}
/**
* Consumes and returns the body as a Blob
*
* @see https://fetch.spec.whatwg.org/#dom-body-blob
* @returns {Promise<Blob>}
*/
blob() {
return consume(this, "blob");
}
/**
* Consumes and returns the body as an Uint8Array.
*
* @see https://fetch.spec.whatwg.org/#dom-body-bytes
* @returns {Promise<Uint8Array>}
*/
bytes() {
return consume(this, "bytes");
}
/**
* Consumes and returns the body as an ArrayBuffer.
*
* @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer
* @returns {Promise<ArrayBuffer>}
*/
arrayBuffer() {
return consume(this, "arrayBuffer");
}
/**
* Not implemented
*
* @see https://fetch.spec.whatwg.org/#dom-body-formdata
* @throws {NotSupportedError}
*/
async formData() {
throw new NotSupportedError();
}
/**
* Returns true if the body is not null and the body has been consumed.
* Otherwise, returns false.
*
* @see https://fetch.spec.whatwg.org/#dom-body-bodyused
* @readonly
* @returns {boolean}
*/
get bodyUsed() {
return util3.isDisturbed(this);
}
/**
* @see https://fetch.spec.whatwg.org/#dom-body-body
* @readonly
* @returns {ReadableStream}
*/
get body() {
if (!this[kBody]) {
this[kBody] = ReadableStreamFrom(this);
if (this[kConsume]) {
this[kBody].getReader();
assert44(this[kBody].locked);
}
}
return this[kBody];
}
/**
* Dumps the response body by reading `limit` number of bytes.
* @param {object} opts
* @param {number} [opts.limit = 131072] Number of bytes to read.
* @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump.
* @returns {Promise<null>}
*/
async dump(opts) {
const signal = opts?.signal;
if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) {
throw new InvalidArgumentError("signal must be an AbortSignal");
}
const limit = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024;
signal?.throwIfAborted();
if (this._readableState.closeEmitted) {
return null;
}
return await new Promise((resolve25, reject) => {
if (this[kContentLength] && this[kContentLength] > limit || this[kBytesRead] > limit) {
this.destroy(new AbortError2());
}
if (signal) {
const onAbort = /* @__PURE__ */ __name(() => {
this.destroy(signal.reason ?? new AbortError2());
}, "onAbort");
signal.addEventListener("abort", onAbort);
this.on("close", function() {
signal.removeEventListener("abort", onAbort);
if (signal.aborted) {
reject(signal.reason ?? new AbortError2());
} else {
resolve25(null);
}
});
} else {
this.on("close", resolve25);
}
this.on("error", noop).on("data", () => {
if (this[kBytesRead] > limit) {
this.destroy();
}
}).resume();
});
}
/**
* @param {BufferEncoding} encoding
* @returns {this}
*/
setEncoding(encoding) {
if (Buffer.isEncoding(encoding)) {
this._readableState.encoding = encoding;
}
return this;
}
};
function isLocked(bodyReadable) {
return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null;
}
__name(isLocked, "isLocked");
function isUnusable(bodyReadable) {
return util3.isDisturbed(bodyReadable) || isLocked(bodyReadable);
}
__name(isUnusable, "isUnusable");
function consume(stream2, type) {
assert44(!stream2[kConsume]);
return new Promise((resolve25, reject) => {
if (isUnusable(stream2)) {
const rState = stream2._readableState;
if (rState.destroyed && rState.closeEmitted === false) {
stream2.on("error", (err) => {
reject(err);
}).on("close", () => {
reject(new TypeError("unusable"));
});
} else {
reject(rState.errored ?? new TypeError("unusable"));
}
} else {
queueMicrotask(() => {
stream2[kConsume] = {
type,
stream: stream2,
resolve: resolve25,
reject,
length: 0,
body: []
};
stream2.on("error", function(err) {
consumeFinish(this[kConsume], err);
}).on("close", function() {
if (this[kConsume].body !== null) {
consumeFinish(this[kConsume], new RequestAbortedError());
}
});
consumeStart(stream2[kConsume]);
});
}
});
}
__name(consume, "consume");
function consumeStart(consume2) {
if (consume2.body === null) {
return;
}
const { _readableState: state2 } = consume2.stream;
if (state2.bufferIndex) {
const start = state2.bufferIndex;
const end = state2.buffer.length;
for (let n6 = start; n6 < end; n6++) {
consumePush(consume2, state2.buffer[n6]);
}
} else {
for (const chunk of state2.buffer) {
consumePush(consume2, chunk);
}
}
if (state2.endEmitted) {
consumeEnd(this[kConsume], this._readableState.encoding);
} else {
consume2.stream.on("end", function() {
consumeEnd(this[kConsume], this._readableState.encoding);
});
}
consume2.stream.resume();
while (consume2.stream.read() != null) {
}
}
__name(consumeStart, "consumeStart");
function chunksDecode(chunks, length, encoding) {
if (chunks.length === 0 || length === 0) {
return "";
}
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length);
const bufferLength = buffer.length;
const start = bufferLength > 2 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191 ? 3 : 0;
if (!encoding || encoding === "utf8" || encoding === "utf-8") {
return buffer.utf8Slice(start, bufferLength);
} else {
return buffer.subarray(start, bufferLength).toString(encoding);
}
}
__name(chunksDecode, "chunksDecode");
function chunksConcat(chunks, length) {
if (chunks.length === 0 || length === 0) {
return new Uint8Array(0);
}
if (chunks.length === 1) {
return new Uint8Array(chunks[0]);
}
const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer);
let offset = 0;
for (let i5 = 0; i5 < chunks.length; ++i5) {
const chunk = chunks[i5];
buffer.set(chunk, offset);
offset += chunk.length;
}
return buffer;
}
__name(chunksConcat, "chunksConcat");
function consumeEnd(consume2, encoding) {
const { type, body, resolve: resolve25, stream: stream2, length } = consume2;
try {
if (type === "text") {
resolve25(chunksDecode(body, length, encoding));
} else if (type === "json") {
resolve25(JSON.parse(chunksDecode(body, length, encoding)));
} else if (type === "arrayBuffer") {
resolve25(chunksConcat(body, length).buffer);
} else if (type === "blob") {
resolve25(new Blob(body, { type: stream2[kContentType] }));
} else if (type === "bytes") {
resolve25(chunksConcat(body, length));
}
consumeFinish(consume2);
} catch (err) {
stream2.destroy(err);
}
}
__name(consumeEnd, "consumeEnd");
function consumePush(consume2, chunk) {
consume2.length += chunk.length;
consume2.body.push(chunk);
}
__name(consumePush, "consumePush");
function consumeFinish(consume2, err) {
if (consume2.body === null) {
return;
}
if (err) {
consume2.reject(err);
} else {
consume2.resolve();
}
consume2.type = null;
consume2.stream = null;
consume2.resolve = null;
consume2.reject = null;
consume2.length = 0;
consume2.body = null;
}
__name(consumeFinish, "consumeFinish");
module3.exports = {
Readable: BodyReadable,
chunksDecode
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-request.js
var require_api_request = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-request.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { AsyncResource } = require("async_hooks");
var { Readable: Readable8 } = require_readable();
var { InvalidArgumentError, RequestAbortedError } = require_errors();
var util3 = require_util();
function noop() {
}
__name(noop, "noop");
var RequestHandler = class extends AsyncResource {
static {
__name(this, "RequestHandler");
}
constructor(opts, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts;
try {
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) {
throw new InvalidArgumentError("invalid highWaterMark");
}
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
if (method === "CONNECT") {
throw new InvalidArgumentError("invalid method");
}
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
super("UNDICI_REQUEST");
} catch (err) {
if (util3.isStream(body)) {
util3.destroy(body.on("error", noop), err);
}
throw err;
}
this.method = method;
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.callback = callback;
this.res = null;
this.abort = null;
this.body = body;
this.trailers = {};
this.context = null;
this.onInfo = onInfo || null;
this.highWaterMark = highWaterMark;
this.reason = null;
this.removeAbortListener = null;
if (signal?.aborted) {
this.reason = signal.reason ?? new RequestAbortedError();
} else if (signal) {
this.removeAbortListener = util3.addAbortListener(signal, () => {
this.reason = signal.reason ?? new RequestAbortedError();
if (this.res) {
util3.destroy(this.res.on("error", noop), this.reason);
} else if (this.abort) {
this.abort(this.reason);
}
});
}
}
onConnect(abort, context2) {
if (this.reason) {
abort(this.reason);
return;
}
assert44(this.callback);
this.abort = abort;
this.context = context2;
}
onHeaders(statusCode, rawHeaders, resume, statusMessage) {
const { callback, opaque, abort, context: context2, responseHeaders, highWaterMark } = this;
const headers = responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
if (statusCode < 200) {
if (this.onInfo) {
this.onInfo({ statusCode, headers });
}
return;
}
const parsedHeaders = responseHeaders === "raw" ? util3.parseHeaders(rawHeaders) : headers;
const contentType = parsedHeaders["content-type"];
const contentLength = parsedHeaders["content-length"];
const res = new Readable8({
resume,
abort,
contentType,
contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
highWaterMark
});
if (this.removeAbortListener) {
res.on("close", this.removeAbortListener);
this.removeAbortListener = null;
}
this.callback = null;
this.res = res;
if (callback !== null) {
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
trailers: this.trailers,
opaque,
body: res,
context: context2
});
}
}
onData(chunk) {
return this.res.push(chunk);
}
onComplete(trailers) {
util3.parseHeaders(trailers, this.trailers);
this.res.push(null);
}
onError(err) {
const { res, callback, body, opaque } = this;
if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
if (res) {
this.res = null;
queueMicrotask(() => {
util3.destroy(res.on("error", noop), err);
});
}
if (body) {
this.body = null;
if (util3.isStream(body)) {
body.on("error", noop);
util3.destroy(body, err);
}
}
if (this.removeAbortListener) {
this.removeAbortListener();
this.removeAbortListener = null;
}
}
};
function request4(opts, callback) {
if (callback === void 0) {
return new Promise((resolve25, reject) => {
request4.call(this, opts, (err, data) => {
return err ? reject(err) : resolve25(data);
});
});
}
try {
const handler = new RequestHandler(opts, callback);
this.dispatch(opts, handler);
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts?.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
__name(request4, "request");
module3.exports = request4;
module3.exports.RequestHandler = RequestHandler;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/abort-signal.js
var require_abort_signal = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/abort-signal.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { addAbortListener } = require_util();
var { RequestAbortedError } = require_errors();
var kListener = Symbol("kListener");
var kSignal = Symbol("kSignal");
function abort(self2) {
if (self2.abort) {
self2.abort(self2[kSignal]?.reason);
} else {
self2.reason = self2[kSignal]?.reason ?? new RequestAbortedError();
}
removeSignal(self2);
}
__name(abort, "abort");
function addSignal(self2, signal) {
self2.reason = null;
self2[kSignal] = null;
self2[kListener] = null;
if (!signal) {
return;
}
if (signal.aborted) {
abort(self2);
return;
}
self2[kSignal] = signal;
self2[kListener] = () => {
abort(self2);
};
addAbortListener(self2[kSignal], self2[kListener]);
}
__name(addSignal, "addSignal");
function removeSignal(self2) {
if (!self2[kSignal]) {
return;
}
if ("removeEventListener" in self2[kSignal]) {
self2[kSignal].removeEventListener("abort", self2[kListener]);
} else {
self2[kSignal].removeListener("abort", self2[kListener]);
}
self2[kSignal] = null;
self2[kListener] = null;
}
__name(removeSignal, "removeSignal");
module3.exports = {
addSignal,
removeSignal
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-stream.js
var require_api_stream = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-stream.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { finished } = require("stream");
var { AsyncResource } = require("async_hooks");
var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
var util3 = require_util();
var { addSignal, removeSignal } = require_abort_signal();
function noop() {
}
__name(noop, "noop");
var StreamHandler = class extends AsyncResource {
static {
__name(this, "StreamHandler");
}
constructor(opts, factory, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
try {
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (typeof factory !== "function") {
throw new InvalidArgumentError("invalid factory");
}
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
if (method === "CONNECT") {
throw new InvalidArgumentError("invalid method");
}
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
super("UNDICI_STREAM");
} catch (err) {
if (util3.isStream(body)) {
util3.destroy(body.on("error", noop), err);
}
throw err;
}
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.factory = factory;
this.callback = callback;
this.res = null;
this.abort = null;
this.context = null;
this.trailers = null;
this.body = body;
this.onInfo = onInfo || null;
if (util3.isStream(body)) {
body.on("error", (err) => {
this.onError(err);
});
}
addSignal(this, signal);
}
onConnect(abort, context2) {
if (this.reason) {
abort(this.reason);
return;
}
assert44(this.callback);
this.abort = abort;
this.context = context2;
}
onHeaders(statusCode, rawHeaders, resume, statusMessage) {
const { factory, opaque, context: context2, responseHeaders } = this;
const headers = responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
if (statusCode < 200) {
if (this.onInfo) {
this.onInfo({ statusCode, headers });
}
return;
}
this.factory = null;
if (factory === null) {
return;
}
const res = this.runInAsyncScope(factory, null, {
statusCode,
headers,
opaque,
context: context2
});
if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") {
throw new InvalidReturnValueError("expected Writable");
}
finished(res, { readable: false }, (err) => {
const { callback, res: res2, opaque: opaque2, trailers, abort } = this;
this.res = null;
if (err || !res2?.readable) {
util3.destroy(res2, err);
}
this.callback = null;
this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
if (err) {
abort();
}
});
res.on("drain", resume);
this.res = res;
const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
return needDrain !== true;
}
onData(chunk) {
const { res } = this;
return res ? res.write(chunk) : true;
}
onComplete(trailers) {
const { res } = this;
removeSignal(this);
if (!res) {
return;
}
this.trailers = util3.parseHeaders(trailers);
res.end();
}
onError(err) {
const { res, callback, opaque, body } = this;
removeSignal(this);
this.factory = null;
if (res) {
this.res = null;
util3.destroy(res, err);
} else if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
if (body) {
this.body = null;
util3.destroy(body, err);
}
}
};
function stream2(opts, factory, callback) {
if (callback === void 0) {
return new Promise((resolve25, reject) => {
stream2.call(this, opts, factory, (err, data) => {
return err ? reject(err) : resolve25(data);
});
});
}
try {
const handler = new StreamHandler(opts, factory, callback);
this.dispatch(opts, handler);
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts?.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
__name(stream2, "stream");
module3.exports = stream2;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-pipeline.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
Readable: Readable8,
Duplex: Duplex2,
PassThrough: PassThrough3
} = require("stream");
var assert44 = require("assert");
var { AsyncResource } = require("async_hooks");
var {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = require_errors();
var util3 = require_util();
var { addSignal, removeSignal } = require_abort_signal();
function noop() {
}
__name(noop, "noop");
var kResume = Symbol("resume");
var PipelineRequest = class extends Readable8 {
static {
__name(this, "PipelineRequest");
}
constructor() {
super({ autoDestroy: true });
this[kResume] = null;
}
_read() {
const { [kResume]: resume } = this;
if (resume) {
this[kResume] = null;
resume();
}
}
_destroy(err, callback) {
this._read();
callback(err);
}
};
var PipelineResponse = class extends Readable8 {
static {
__name(this, "PipelineResponse");
}
constructor(resume) {
super({ autoDestroy: true });
this[kResume] = resume;
}
_read() {
this[kResume]();
}
_destroy(err, callback) {
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError();
}
callback(err);
}
};
var PipelineHandler = class extends AsyncResource {
static {
__name(this, "PipelineHandler");
}
constructor(opts, handler) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (typeof handler !== "function") {
throw new InvalidArgumentError("invalid handler");
}
const { signal, method, opaque, onInfo, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
if (method === "CONNECT") {
throw new InvalidArgumentError("invalid method");
}
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
super("UNDICI_PIPELINE");
this.opaque = opaque || null;
this.responseHeaders = responseHeaders || null;
this.handler = handler;
this.abort = null;
this.context = null;
this.onInfo = onInfo || null;
this.req = new PipelineRequest().on("error", noop);
this.ret = new Duplex2({
readableObjectMode: opts.objectMode,
autoDestroy: true,
read: /* @__PURE__ */ __name(() => {
const { body } = this;
if (body?.resume) {
body.resume();
}
}, "read"),
write: /* @__PURE__ */ __name((chunk, encoding, callback) => {
const { req } = this;
if (req.push(chunk, encoding) || req._readableState.destroyed) {
callback();
} else {
req[kResume] = callback;
}
}, "write"),
destroy: /* @__PURE__ */ __name((err, callback) => {
const { body, req, res, ret, abort } = this;
if (!err && !ret._readableState.endEmitted) {
err = new RequestAbortedError();
}
if (abort && err) {
abort();
}
util3.destroy(body, err);
util3.destroy(req, err);
util3.destroy(res, err);
removeSignal(this);
callback(err);
}, "destroy")
}).on("prefinish", () => {
const { req } = this;
req.push(null);
});
this.res = null;
addSignal(this, signal);
}
onConnect(abort, context2) {
const { res } = this;
if (this.reason) {
abort(this.reason);
return;
}
assert44(!res, "pipeline cannot be retried");
this.abort = abort;
this.context = context2;
}
onHeaders(statusCode, rawHeaders, resume) {
const { opaque, handler, context: context2 } = this;
if (statusCode < 200) {
if (this.onInfo) {
const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
this.onInfo({ statusCode, headers });
}
return;
}
this.res = new PipelineResponse(resume);
let body;
try {
this.handler = null;
const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
body = this.runInAsyncScope(handler, null, {
statusCode,
headers,
opaque,
body: this.res,
context: context2
});
} catch (err) {
this.res.on("error", noop);
throw err;
}
if (!body || typeof body.on !== "function") {
throw new InvalidReturnValueError("expected Readable");
}
body.on("data", (chunk) => {
const { ret, body: body2 } = this;
if (!ret.push(chunk) && body2.pause) {
body2.pause();
}
}).on("error", (err) => {
const { ret } = this;
util3.destroy(ret, err);
}).on("end", () => {
const { ret } = this;
ret.push(null);
}).on("close", () => {
const { ret } = this;
if (!ret._readableState.ended) {
util3.destroy(ret, new RequestAbortedError());
}
});
this.body = body;
}
onData(chunk) {
const { res } = this;
return res.push(chunk);
}
onComplete(trailers) {
const { res } = this;
res.push(null);
}
onError(err) {
const { ret } = this;
this.handler = null;
util3.destroy(ret, err);
}
};
function pipeline(opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler);
this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
return pipelineHandler.ret;
} catch (err) {
return new PassThrough3().destroy(err);
}
}
__name(pipeline, "pipeline");
module3.exports = pipeline;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-upgrade.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { InvalidArgumentError, SocketError } = require_errors();
var { AsyncResource } = require("async_hooks");
var assert44 = require("assert");
var util3 = require_util();
var { addSignal, removeSignal } = require_abort_signal();
var UpgradeHandler = class extends AsyncResource {
static {
__name(this, "UpgradeHandler");
}
constructor(opts, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
const { signal, opaque, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
super("UNDICI_UPGRADE");
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.callback = callback;
this.abort = null;
this.context = null;
addSignal(this, signal);
}
onConnect(abort, context2) {
if (this.reason) {
abort(this.reason);
return;
}
assert44(this.callback);
this.abort = abort;
this.context = null;
}
onHeaders() {
throw new SocketError("bad upgrade", null);
}
onUpgrade(statusCode, rawHeaders, socket) {
assert44(statusCode === 101);
const { callback, opaque, context: context2 } = this;
removeSignal(this);
this.callback = null;
const headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
this.runInAsyncScope(callback, null, null, {
headers,
socket,
opaque,
context: context2
});
}
onError(err) {
const { callback, opaque } = this;
removeSignal(this);
if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
}
};
function upgrade(opts, callback) {
if (callback === void 0) {
return new Promise((resolve25, reject) => {
upgrade.call(this, opts, (err, data) => {
return err ? reject(err) : resolve25(data);
});
});
}
try {
const upgradeHandler = new UpgradeHandler(opts, callback);
const upgradeOpts = {
...opts,
method: opts.method || "GET",
upgrade: opts.protocol || "Websocket"
};
this.dispatch(upgradeOpts, upgradeHandler);
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts?.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
__name(upgrade, "upgrade");
module3.exports = upgrade;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-connect.js
var require_api_connect = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/api-connect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { AsyncResource } = require("async_hooks");
var { InvalidArgumentError, SocketError } = require_errors();
var util3 = require_util();
var { addSignal, removeSignal } = require_abort_signal();
var ConnectHandler = class extends AsyncResource {
static {
__name(this, "ConnectHandler");
}
constructor(opts, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
const { signal, opaque, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
super("UNDICI_CONNECT");
this.opaque = opaque || null;
this.responseHeaders = responseHeaders || null;
this.callback = callback;
this.abort = null;
addSignal(this, signal);
}
onConnect(abort, context2) {
if (this.reason) {
abort(this.reason);
return;
}
assert44(this.callback);
this.abort = abort;
this.context = context2;
}
onHeaders() {
throw new SocketError("bad connect", null);
}
onUpgrade(statusCode, rawHeaders, socket) {
const { callback, opaque, context: context2 } = this;
removeSignal(this);
this.callback = null;
let headers = rawHeaders;
if (headers != null) {
headers = this.responseHeaders === "raw" ? util3.parseRawHeaders(rawHeaders) : util3.parseHeaders(rawHeaders);
}
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
socket,
opaque,
context: context2
});
}
onError(err) {
const { callback, opaque } = this;
removeSignal(this);
if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
}
};
function connect(opts, callback) {
if (callback === void 0) {
return new Promise((resolve25, reject) => {
connect.call(this, opts, (err, data) => {
return err ? reject(err) : resolve25(data);
});
});
}
try {
const connectHandler = new ConnectHandler(opts, callback);
const connectOptions = { ...opts, method: "CONNECT" };
this.dispatch(connectOptions, connectHandler);
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts?.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
__name(connect, "connect");
module3.exports = connect;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/index.js
var require_api = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/api/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports.request = require_api_request();
module3.exports.stream = require_api_stream();
module3.exports.pipeline = require_api_pipeline();
module3.exports.upgrade = require_api_upgrade();
module3.exports.connect = require_api_connect();
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-errors.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { UndiciError } = require_errors();
var MockNotMatchedError = class extends UndiciError {
static {
__name(this, "MockNotMatchedError");
}
constructor(message) {
super(message);
this.name = "MockNotMatchedError";
this.message = message || "The request does not match any registered mock dispatches";
this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
}
};
module3.exports = {
MockNotMatchedError
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-symbols.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
kAgent: Symbol("agent"),
kOptions: Symbol("options"),
kFactory: Symbol("factory"),
kDispatches: Symbol("dispatches"),
kDispatchKey: Symbol("dispatch key"),
kDefaultHeaders: Symbol("default headers"),
kDefaultTrailers: Symbol("default trailers"),
kContentLength: Symbol("content length"),
kMockAgent: Symbol("mock agent"),
kMockAgentSet: Symbol("mock agent set"),
kMockAgentGet: Symbol("mock agent get"),
kMockDispatch: Symbol("mock dispatch"),
kClose: Symbol("close"),
kOriginalClose: Symbol("original agent close"),
kOriginalDispatch: Symbol("original dispatch"),
kOrigin: Symbol("origin"),
kIsMockActive: Symbol("is mock active"),
kNetConnect: Symbol("net connect"),
kGetNetConnect: Symbol("get net connect"),
kConnected: Symbol("connected"),
kIgnoreTrailingSlash: Symbol("ignore trailing slash"),
kMockAgentMockCallHistoryInstance: Symbol("mock agent mock call history name"),
kMockAgentRegisterCallHistory: Symbol("mock agent register mock call history"),
kMockAgentAddCallHistoryLog: Symbol("mock agent add call history log"),
kMockAgentIsCallHistoryEnabled: Symbol("mock agent is call history enabled"),
kMockAgentAcceptsNonStandardSearchParameters: Symbol("mock agent accepts non standard search parameters"),
kMockCallHistoryAddLog: Symbol("mock call history add log")
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-utils.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { MockNotMatchedError } = require_mock_errors();
var {
kDispatches,
kMockAgent,
kOriginalDispatch,
kOrigin,
kGetNetConnect
} = require_mock_symbols();
var { serializePathWithQuery } = require_util();
var { STATUS_CODES } = require("http");
var {
types: {
isPromise: isPromise2
}
} = require("util");
var { InvalidArgumentError } = require_errors();
function matchValue(match2, value) {
if (typeof match2 === "string") {
return match2 === value;
}
if (match2 instanceof RegExp) {
return match2.test(value);
}
if (typeof match2 === "function") {
return match2(value) === true;
}
return false;
}
__name(matchValue, "matchValue");
function lowerCaseEntries(headers) {
return Object.fromEntries(
Object.entries(headers).map(([headerName, headerValue]) => {
return [headerName.toLocaleLowerCase(), headerValue];
})
);
}
__name(lowerCaseEntries, "lowerCaseEntries");
function getHeaderByName(headers, key) {
if (Array.isArray(headers)) {
for (let i5 = 0; i5 < headers.length; i5 += 2) {
if (headers[i5].toLocaleLowerCase() === key.toLocaleLowerCase()) {
return headers[i5 + 1];
}
}
return void 0;
} else if (typeof headers.get === "function") {
return headers.get(key);
} else {
return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
}
}
__name(getHeaderByName, "getHeaderByName");
function buildHeadersFromArray(headers) {
const clone = headers.slice();
const entries = [];
for (let index = 0; index < clone.length; index += 2) {
entries.push([clone[index], clone[index + 1]]);
}
return Object.fromEntries(entries);
}
__name(buildHeadersFromArray, "buildHeadersFromArray");
function matchHeaders(mockDispatch2, headers) {
if (typeof mockDispatch2.headers === "function") {
if (Array.isArray(headers)) {
headers = buildHeadersFromArray(headers);
}
return mockDispatch2.headers(headers ? lowerCaseEntries(headers) : {});
}
if (typeof mockDispatch2.headers === "undefined") {
return true;
}
if (typeof headers !== "object" || typeof mockDispatch2.headers !== "object") {
return false;
}
for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
const headerValue = getHeaderByName(headers, matchHeaderName);
if (!matchValue(matchHeaderValue, headerValue)) {
return false;
}
}
return true;
}
__name(matchHeaders, "matchHeaders");
function normalizeSearchParams(query) {
if (typeof query !== "string") {
return query;
}
const originalQp = new URLSearchParams(query);
const normalizedQp = new URLSearchParams();
for (let [key, value] of originalQp.entries()) {
key = key.replace("[]", "");
const valueRepresentsString = /^(['"]).*\1$/.test(value);
if (valueRepresentsString) {
normalizedQp.append(key, value);
continue;
}
if (value.includes(",")) {
const values = value.split(",");
for (const v7 of values) {
normalizedQp.append(key, v7);
}
continue;
}
normalizedQp.append(key, value);
}
return normalizedQp;
}
__name(normalizeSearchParams, "normalizeSearchParams");
function safeUrl(path72) {
if (typeof path72 !== "string") {
return path72;
}
const pathSegments = path72.split("?", 3);
if (pathSegments.length !== 2) {
return path72;
}
const qp = new URLSearchParams(pathSegments.pop());
qp.sort();
return [...pathSegments, qp.toString()].join("?");
}
__name(safeUrl, "safeUrl");
function matchKey(mockDispatch2, { path: path72, method, body, headers }) {
const pathMatch = matchValue(mockDispatch2.path, path72);
const methodMatch = matchValue(mockDispatch2.method, method);
const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
const headersMatch = matchHeaders(mockDispatch2, headers);
return pathMatch && methodMatch && bodyMatch && headersMatch;
}
__name(matchKey, "matchKey");
function getResponseData(data) {
if (Buffer.isBuffer(data)) {
return data;
} else if (data instanceof Uint8Array) {
return data;
} else if (data instanceof ArrayBuffer) {
return data;
} else if (typeof data === "object") {
return JSON.stringify(data);
} else if (data) {
return data.toString();
} else {
return "";
}
}
__name(getResponseData, "getResponseData");
function getMockDispatch(mockDispatches, key) {
const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
const resolvedPath2 = typeof basePath === "string" ? safeUrl(basePath) : basePath;
const resolvedPathWithoutTrailingSlash = removeTrailingSlash2(resolvedPath2);
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path72, ignoreTrailingSlash }) => {
return ignoreTrailingSlash ? matchValue(removeTrailingSlash2(safeUrl(path72)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path72), resolvedPath2);
});
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath2}'`);
}
matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method));
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath2}'`);
}
matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue(body, key.body) : true);
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath2}'`);
}
matchedMockDispatches = matchedMockDispatches.filter((mockDispatch2) => matchHeaders(mockDispatch2, key.headers));
if (matchedMockDispatches.length === 0) {
const headers = typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers;
throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath2}'`);
}
return matchedMockDispatches[0];
}
__name(getMockDispatch, "getMockDispatch");
function addMockDispatch(mockDispatches, key, data, opts) {
const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts };
const replyData = typeof data === "function" ? { callback: data } : { ...data };
const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
mockDispatches.push(newMockDispatch);
return newMockDispatch;
}
__name(addMockDispatch, "addMockDispatch");
function deleteMockDispatch(mockDispatches, key) {
const index = mockDispatches.findIndex((dispatch) => {
if (!dispatch.consumed) {
return false;
}
return matchKey(dispatch, key);
});
if (index !== -1) {
mockDispatches.splice(index, 1);
}
}
__name(deleteMockDispatch, "deleteMockDispatch");
function removeTrailingSlash2(path72) {
while (path72.endsWith("/")) {
path72 = path72.slice(0, -1);
}
if (path72.length === 0) {
path72 = "/";
}
return path72;
}
__name(removeTrailingSlash2, "removeTrailingSlash");
function buildKey(opts) {
const { path: path72, method, body, headers, query } = opts;
return {
path: path72,
method,
body,
headers,
query
};
}
__name(buildKey, "buildKey");
function generateKeyValues(data) {
const keys = Object.keys(data);
const result = [];
for (let i5 = 0; i5 < keys.length; ++i5) {
const key = keys[i5];
const value = data[key];
const name2 = Buffer.from(`${key}`);
if (Array.isArray(value)) {
for (let j6 = 0; j6 < value.length; ++j6) {
result.push(name2, Buffer.from(`${value[j6]}`));
}
} else {
result.push(name2, Buffer.from(`${value}`));
}
}
return result;
}
__name(generateKeyValues, "generateKeyValues");
function getStatusText(statusCode) {
return STATUS_CODES[statusCode] || "unknown";
}
__name(getStatusText, "getStatusText");
async function getResponse(body) {
const buffers = [];
for await (const data of body) {
buffers.push(data);
}
return Buffer.concat(buffers).toString("utf8");
}
__name(getResponse, "getResponse");
function mockDispatch(opts, handler) {
const key = buildKey(opts);
const mockDispatch2 = getMockDispatch(this[kDispatches], key);
mockDispatch2.timesInvoked++;
if (mockDispatch2.data.callback) {
mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
}
const { data: { statusCode, data, headers, trailers, error: error2 }, delay, persist } = mockDispatch2;
const { timesInvoked, times } = mockDispatch2;
mockDispatch2.consumed = !persist && timesInvoked >= times;
mockDispatch2.pending = timesInvoked < times;
if (error2 !== null) {
deleteMockDispatch(this[kDispatches], key);
handler.onError(error2);
return true;
}
if (typeof delay === "number" && delay > 0) {
setTimeout(() => {
handleReply(this[kDispatches]);
}, delay);
} else {
handleReply(this[kDispatches]);
}
function handleReply(mockDispatches, _data5 = data) {
const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
const body = typeof _data5 === "function" ? _data5({ ...opts, headers: optsHeaders }) : _data5;
if (isPromise2(body)) {
body.then((newData) => handleReply(mockDispatches, newData));
return;
}
const responseData = getResponseData(body);
const responseHeaders = generateKeyValues(headers);
const responseTrailers = generateKeyValues(trailers);
handler.onConnect?.((err) => handler.onError(err), null);
handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode));
handler.onData?.(Buffer.from(responseData));
handler.onComplete?.(responseTrailers);
deleteMockDispatch(mockDispatches, key);
}
__name(handleReply, "handleReply");
function resume() {
}
__name(resume, "resume");
return true;
}
__name(mockDispatch, "mockDispatch");
function buildMockDispatch() {
const agent = this[kMockAgent];
const origin = this[kOrigin];
const originalDispatch = this[kOriginalDispatch];
return /* @__PURE__ */ __name(function dispatch(opts, handler) {
if (agent.isMockActive) {
try {
mockDispatch.call(this, opts, handler);
} catch (error2) {
if (error2 instanceof MockNotMatchedError) {
const netConnect = agent[kGetNetConnect]();
if (netConnect === false) {
throw new MockNotMatchedError(`${error2.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`);
}
if (checkNetConnect(netConnect, origin)) {
originalDispatch.call(this, opts, handler);
} else {
throw new MockNotMatchedError(`${error2.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
}
} else {
throw error2;
}
}
} else {
originalDispatch.call(this, opts, handler);
}
}, "dispatch");
}
__name(buildMockDispatch, "buildMockDispatch");
function checkNetConnect(netConnect, origin) {
const url4 = new URL(origin);
if (netConnect === true) {
return true;
} else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url4.host))) {
return true;
}
return false;
}
__name(checkNetConnect, "checkNetConnect");
function buildAndValidateMockOptions(opts) {
if (opts) {
const { agent, ...mockOptions } = opts;
if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") {
throw new InvalidArgumentError("options.enableCallHistory must to be a boolean");
}
if ("acceptNonStandardSearchParameters" in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== "boolean") {
throw new InvalidArgumentError("options.acceptNonStandardSearchParameters must to be a boolean");
}
return mockOptions;
}
}
__name(buildAndValidateMockOptions, "buildAndValidateMockOptions");
module3.exports = {
getResponseData,
getMockDispatch,
addMockDispatch,
deleteMockDispatch,
buildKey,
generateKeyValues,
matchValue,
getResponse,
getStatusText,
mockDispatch,
buildMockDispatch,
checkNetConnect,
buildAndValidateMockOptions,
getHeaderByName,
buildHeadersFromArray,
normalizeSearchParams
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-interceptor.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
var {
kDispatches,
kDispatchKey,
kDefaultHeaders,
kDefaultTrailers,
kContentLength,
kMockDispatch,
kIgnoreTrailingSlash
} = require_mock_symbols();
var { InvalidArgumentError } = require_errors();
var { serializePathWithQuery } = require_util();
var MockScope = class {
static {
__name(this, "MockScope");
}
constructor(mockDispatch) {
this[kMockDispatch] = mockDispatch;
}
/**
* Delay a reply by a set amount in ms.
*/
delay(waitInMs) {
if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) {
throw new InvalidArgumentError("waitInMs must be a valid integer > 0");
}
this[kMockDispatch].delay = waitInMs;
return this;
}
/**
* For a defined reply, never mark as consumed.
*/
persist() {
this[kMockDispatch].persist = true;
return this;
}
/**
* Allow one to define a reply for a set amount of matching requests.
*/
times(repeatTimes) {
if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
throw new InvalidArgumentError("repeatTimes must be a valid integer > 0");
}
this[kMockDispatch].times = repeatTimes;
return this;
}
};
var MockInterceptor = class {
static {
__name(this, "MockInterceptor");
}
constructor(opts, mockDispatches) {
if (typeof opts !== "object") {
throw new InvalidArgumentError("opts must be an object");
}
if (typeof opts.path === "undefined") {
throw new InvalidArgumentError("opts.path must be defined");
}
if (typeof opts.method === "undefined") {
opts.method = "GET";
}
if (typeof opts.path === "string") {
if (opts.query) {
opts.path = serializePathWithQuery(opts.path, opts.query);
} else {
const parsedURL = new URL(opts.path, "data://");
opts.path = parsedURL.pathname + parsedURL.search;
}
}
if (typeof opts.method === "string") {
opts.method = opts.method.toUpperCase();
}
this[kDispatchKey] = buildKey(opts);
this[kDispatches] = mockDispatches;
this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
this[kDefaultHeaders] = {};
this[kDefaultTrailers] = {};
this[kContentLength] = false;
}
createMockScopeDispatchData({ statusCode, data, responseOptions }) {
const responseData = getResponseData(data);
const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
return { statusCode, data, headers, trailers };
}
validateReplyParameters(replyParameters) {
if (typeof replyParameters.statusCode === "undefined") {
throw new InvalidArgumentError("statusCode must be defined");
}
if (typeof replyParameters.responseOptions !== "object" || replyParameters.responseOptions === null) {
throw new InvalidArgumentError("responseOptions must be an object");
}
}
/**
* Mock an undici request with a defined reply.
*/
reply(replyOptionsCallbackOrStatusCode) {
if (typeof replyOptionsCallbackOrStatusCode === "function") {
const wrappedDefaultsCallback = /* @__PURE__ */ __name((opts) => {
const resolvedData = replyOptionsCallbackOrStatusCode(opts);
if (typeof resolvedData !== "object" || resolvedData === null) {
throw new InvalidArgumentError("reply options callback must return an object");
}
const replyParameters2 = { data: "", responseOptions: {}, ...resolvedData };
this.validateReplyParameters(replyParameters2);
return {
...this.createMockScopeDispatchData(replyParameters2)
};
}, "wrappedDefaultsCallback");
const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
return new MockScope(newMockDispatch2);
}
const replyParameters = {
statusCode: replyOptionsCallbackOrStatusCode,
data: arguments[1] === void 0 ? "" : arguments[1],
responseOptions: arguments[2] === void 0 ? {} : arguments[2]
};
this.validateReplyParameters(replyParameters);
const dispatchData = this.createMockScopeDispatchData(replyParameters);
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
return new MockScope(newMockDispatch);
}
/**
* Mock an undici request with a defined error.
*/
replyWithError(error2) {
if (typeof error2 === "undefined") {
throw new InvalidArgumentError("error must be defined");
}
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error2 }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
return new MockScope(newMockDispatch);
}
/**
* Set default reply headers on the interceptor for subsequent replies
*/
defaultReplyHeaders(headers) {
if (typeof headers === "undefined") {
throw new InvalidArgumentError("headers must be defined");
}
this[kDefaultHeaders] = headers;
return this;
}
/**
* Set default reply trailers on the interceptor for subsequent replies
*/
defaultReplyTrailers(trailers) {
if (typeof trailers === "undefined") {
throw new InvalidArgumentError("trailers must be defined");
}
this[kDefaultTrailers] = trailers;
return this;
}
/**
* Set reply content length header for replies on the interceptor
*/
replyContentLength() {
this[kContentLength] = true;
return this;
}
};
module3.exports.MockInterceptor = MockInterceptor;
module3.exports.MockScope = MockScope;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-client.js
var require_mock_client = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-client.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { promisify: promisify3 } = require("util");
var Client2 = require_client();
var { buildMockDispatch } = require_mock_utils();
var {
kDispatches,
kMockAgent,
kClose,
kOriginalClose,
kOrigin,
kOriginalDispatch,
kConnected,
kIgnoreTrailingSlash
} = require_mock_symbols();
var { MockInterceptor } = require_mock_interceptor();
var Symbols = require_symbols();
var { InvalidArgumentError } = require_errors();
var MockClient = class extends Client2 {
static {
__name(this, "MockClient");
}
constructor(origin, opts) {
if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument opts.agent must implement Agent");
}
super(origin, opts);
this[kMockAgent] = opts.agent;
this[kOrigin] = origin;
this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
this[kDispatches] = [];
this[kConnected] = 1;
this[kOriginalDispatch] = this.dispatch;
this[kOriginalClose] = this.close.bind(this);
this.dispatch = buildMockDispatch.call(this);
this.close = this[kClose];
}
get [Symbols.kConnected]() {
return this[kConnected];
}
/**
* Sets up the base interceptor for mocking replies from undici.
*/
intercept(opts) {
return new MockInterceptor(
opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
this[kDispatches]
);
}
cleanMocks() {
this[kDispatches] = [];
}
async [kClose]() {
await promisify3(this[kOriginalClose])();
this[kConnected] = 0;
this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
}
};
module3.exports = MockClient;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-call-history.js
var require_mock_call_history = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-call-history.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { kMockCallHistoryAddLog } = require_mock_symbols();
var { InvalidArgumentError } = require_errors();
function handleFilterCallsWithOptions(criteria, options, handler, store) {
switch (options.operator) {
case "OR":
store.push(...handler(criteria));
return store;
case "AND":
return handler.call({ logs: store }, criteria);
default:
throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
}
}
__name(handleFilterCallsWithOptions, "handleFilterCallsWithOptions");
function buildAndValidateFilterCallsOptions(options = {}) {
const finalOptions = {};
if ("operator" in options) {
if (typeof options.operator !== "string" || options.operator.toUpperCase() !== "OR" && options.operator.toUpperCase() !== "AND") {
throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
}
return {
...finalOptions,
operator: options.operator.toUpperCase()
};
}
return finalOptions;
}
__name(buildAndValidateFilterCallsOptions, "buildAndValidateFilterCallsOptions");
function makeFilterCalls(parameterName) {
return (parameterValue) => {
if (typeof parameterValue === "string" || parameterValue == null) {
return this.logs.filter((log2) => {
return log2[parameterName] === parameterValue;
});
}
if (parameterValue instanceof RegExp) {
return this.logs.filter((log2) => {
return parameterValue.test(log2[parameterName]);
});
}
throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`);
};
}
__name(makeFilterCalls, "makeFilterCalls");
function computeUrlWithMaybeSearchParameters(requestInit) {
try {
const url4 = new URL(requestInit.path, requestInit.origin);
if (url4.search.length !== 0) {
return url4;
}
url4.search = new URLSearchParams(requestInit.query).toString();
return url4;
} catch (error2) {
throw new InvalidArgumentError("An error occurred when computing MockCallHistoryLog.url", { cause: error2 });
}
}
__name(computeUrlWithMaybeSearchParameters, "computeUrlWithMaybeSearchParameters");
var MockCallHistoryLog = class {
static {
__name(this, "MockCallHistoryLog");
}
constructor(requestInit = {}) {
this.body = requestInit.body;
this.headers = requestInit.headers;
this.method = requestInit.method;
const url4 = computeUrlWithMaybeSearchParameters(requestInit);
this.fullUrl = url4.toString();
this.origin = url4.origin;
this.path = url4.pathname;
this.searchParams = Object.fromEntries(url4.searchParams);
this.protocol = url4.protocol;
this.host = url4.host;
this.port = url4.port;
this.hash = url4.hash;
}
toMap() {
return /* @__PURE__ */ new Map(
[
["protocol", this.protocol],
["host", this.host],
["port", this.port],
["origin", this.origin],
["path", this.path],
["hash", this.hash],
["searchParams", this.searchParams],
["fullUrl", this.fullUrl],
["method", this.method],
["body", this.body],
["headers", this.headers]
]
);
}
toString() {
const options = { betweenKeyValueSeparator: "->", betweenPairSeparator: "|" };
let result = "";
this.toMap().forEach((value, key) => {
if (typeof value === "string" || value === void 0 || value === null) {
result = `${result}${key}${options.betweenKeyValueSeparator}${value}${options.betweenPairSeparator}`;
}
if (typeof value === "object" && value !== null || Array.isArray(value)) {
result = `${result}${key}${options.betweenKeyValueSeparator}${JSON.stringify(value)}${options.betweenPairSeparator}`;
}
});
return result.slice(0, -1);
}
};
var MockCallHistory = class {
static {
__name(this, "MockCallHistory");
}
logs = [];
calls() {
return this.logs;
}
firstCall() {
return this.logs.at(0);
}
lastCall() {
return this.logs.at(-1);
}
nthCall(number) {
if (typeof number !== "number") {
throw new InvalidArgumentError("nthCall must be called with a number");
}
if (!Number.isInteger(number)) {
throw new InvalidArgumentError("nthCall must be called with an integer");
}
if (Math.sign(number) !== 1) {
throw new InvalidArgumentError("nthCall must be called with a positive value. use firstCall or lastCall instead");
}
return this.logs.at(number - 1);
}
filterCalls(criteria, options) {
if (this.logs.length === 0) {
return this.logs;
}
if (typeof criteria === "function") {
return this.logs.filter(criteria);
}
if (criteria instanceof RegExp) {
return this.logs.filter((log2) => {
return criteria.test(log2.toString());
});
}
if (typeof criteria === "object" && criteria !== null) {
if (Object.keys(criteria).length === 0) {
return this.logs;
}
const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) };
let maybeDuplicatedLogsFiltered = [];
if ("protocol" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered);
}
if ("host" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered);
}
if ("port" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered);
}
if ("origin" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered);
}
if ("path" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered);
}
if ("hash" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered);
}
if ("fullUrl" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered);
}
if ("method" in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered);
}
const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
return uniqLogsFiltered;
}
throw new InvalidArgumentError("criteria parameter should be one of function, regexp, or object");
}
filterCallsByProtocol = makeFilterCalls.call(this, "protocol");
filterCallsByHost = makeFilterCalls.call(this, "host");
filterCallsByPort = makeFilterCalls.call(this, "port");
filterCallsByOrigin = makeFilterCalls.call(this, "origin");
filterCallsByPath = makeFilterCalls.call(this, "path");
filterCallsByHash = makeFilterCalls.call(this, "hash");
filterCallsByFullUrl = makeFilterCalls.call(this, "fullUrl");
filterCallsByMethod = makeFilterCalls.call(this, "method");
clear() {
this.logs = [];
}
[kMockCallHistoryAddLog](requestInit) {
const log2 = new MockCallHistoryLog(requestInit);
this.logs.push(log2);
return log2;
}
*[Symbol.iterator]() {
for (const log2 of this.calls()) {
yield log2;
}
}
};
module3.exports.MockCallHistory = MockCallHistory;
module3.exports.MockCallHistoryLog = MockCallHistoryLog;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-pool.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { promisify: promisify3 } = require("util");
var Pool = require_pool();
var { buildMockDispatch } = require_mock_utils();
var {
kDispatches,
kMockAgent,
kClose,
kOriginalClose,
kOrigin,
kOriginalDispatch,
kConnected,
kIgnoreTrailingSlash
} = require_mock_symbols();
var { MockInterceptor } = require_mock_interceptor();
var Symbols = require_symbols();
var { InvalidArgumentError } = require_errors();
var MockPool = class extends Pool {
static {
__name(this, "MockPool");
}
constructor(origin, opts) {
if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument opts.agent must implement Agent");
}
super(origin, opts);
this[kMockAgent] = opts.agent;
this[kOrigin] = origin;
this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
this[kDispatches] = [];
this[kConnected] = 1;
this[kOriginalDispatch] = this.dispatch;
this[kOriginalClose] = this.close.bind(this);
this.dispatch = buildMockDispatch.call(this);
this.close = this[kClose];
}
get [Symbols.kConnected]() {
return this[kConnected];
}
/**
* Sets up the base interceptor for mocking replies from undici.
*/
intercept(opts) {
return new MockInterceptor(
opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
this[kDispatches]
);
}
cleanMocks() {
this[kDispatches] = [];
}
async [kClose]() {
await promisify3(this[kOriginalClose])();
this[kConnected] = 0;
this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
}
};
module3.exports = MockPool;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Transform: Transform2 } = require("stream");
var { Console: Console2 } = require("console");
var PERSISTENT = process.versions.icu ? "\u2705" : "Y ";
var NOT_PERSISTENT = process.versions.icu ? "\u274C" : "N ";
module3.exports = class PendingInterceptorsFormatter {
static {
__name(this, "PendingInterceptorsFormatter");
}
constructor({ disableColors } = {}) {
this.transform = new Transform2({
transform(chunk, _enc, cb2) {
cb2(null, chunk);
}
});
this.logger = new Console2({
stdout: this.transform,
inspectOptions: {
colors: !disableColors && !process.env.CI
}
});
}
format(pendingInterceptors) {
const withPrettyHeaders = pendingInterceptors.map(
({ method, path: path72, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
Method: method,
Origin: origin,
Path: path72,
"Status code": statusCode,
Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
Invocations: timesInvoked,
Remaining: persist ? Infinity : times - timesInvoked
})
);
this.logger.table(withPrettyHeaders);
return this.transform.read().toString();
}
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/mock/mock-agent.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { kClients } = require_symbols();
var Agent = require_agent();
var {
kAgent,
kMockAgentSet,
kMockAgentGet,
kDispatches,
kIsMockActive,
kNetConnect,
kGetNetConnect,
kOptions,
kFactory,
kMockAgentRegisterCallHistory,
kMockAgentIsCallHistoryEnabled,
kMockAgentAddCallHistoryLog,
kMockAgentMockCallHistoryInstance,
kMockAgentAcceptsNonStandardSearchParameters,
kMockCallHistoryAddLog
} = require_mock_symbols();
var MockClient = require_mock_client();
var MockPool = require_mock_pool();
var { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = require_mock_utils();
var { InvalidArgumentError, UndiciError } = require_errors();
var Dispatcher2 = require_dispatcher();
var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
var { MockCallHistory } = require_mock_call_history();
var MockAgent = class extends Dispatcher2 {
static {
__name(this, "MockAgent");
}
constructor(opts) {
super(opts);
const mockOptions = buildAndValidateMockOptions(opts);
this[kNetConnect] = true;
this[kIsMockActive] = true;
this[kMockAgentIsCallHistoryEnabled] = mockOptions?.enableCallHistory ?? false;
this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions?.acceptNonStandardSearchParameters ?? false;
if (opts?.agent && typeof opts.agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument opts.agent must implement Agent");
}
const agent = opts?.agent ? opts.agent : new Agent(opts);
this[kAgent] = agent;
this[kClients] = agent[kClients];
this[kOptions] = mockOptions;
if (this[kMockAgentIsCallHistoryEnabled]) {
this[kMockAgentRegisterCallHistory]();
}
}
get(origin) {
let dispatcher = this[kMockAgentGet](origin);
if (!dispatcher) {
dispatcher = this[kFactory](origin);
this[kMockAgentSet](origin, dispatcher);
}
return dispatcher;
}
dispatch(opts, handler) {
this.get(opts.origin);
this[kMockAgentAddCallHistoryLog](opts);
const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
const dispatchOpts = { ...opts };
if (acceptNonStandardSearchParameters && dispatchOpts.path) {
const [path72, searchParams] = dispatchOpts.path.split("?");
const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
dispatchOpts.path = `${path72}?${normalizedSearchParams}`;
}
return this[kAgent].dispatch(dispatchOpts, handler);
}
async close() {
this.clearCallHistory();
await this[kAgent].close();
this[kClients].clear();
}
deactivate() {
this[kIsMockActive] = false;
}
activate() {
this[kIsMockActive] = true;
}
enableNetConnect(matcher) {
if (typeof matcher === "string" || typeof matcher === "function" || matcher instanceof RegExp) {
if (Array.isArray(this[kNetConnect])) {
this[kNetConnect].push(matcher);
} else {
this[kNetConnect] = [matcher];
}
} else if (typeof matcher === "undefined") {
this[kNetConnect] = true;
} else {
throw new InvalidArgumentError("Unsupported matcher. Must be one of String|Function|RegExp.");
}
}
disableNetConnect() {
this[kNetConnect] = false;
}
enableCallHistory() {
this[kMockAgentIsCallHistoryEnabled] = true;
return this;
}
disableCallHistory() {
this[kMockAgentIsCallHistoryEnabled] = false;
return this;
}
getCallHistory() {
return this[kMockAgentMockCallHistoryInstance];
}
clearCallHistory() {
if (this[kMockAgentMockCallHistoryInstance] !== void 0) {
this[kMockAgentMockCallHistoryInstance].clear();
}
}
// This is required to bypass issues caused by using global symbols - see:
// https://github.com/nodejs/undici/issues/1447
get isMockActive() {
return this[kIsMockActive];
}
[kMockAgentRegisterCallHistory]() {
if (this[kMockAgentMockCallHistoryInstance] === void 0) {
this[kMockAgentMockCallHistoryInstance] = new MockCallHistory();
}
}
[kMockAgentAddCallHistoryLog](opts) {
if (this[kMockAgentIsCallHistoryEnabled]) {
this[kMockAgentRegisterCallHistory]();
this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts);
}
}
[kMockAgentSet](origin, dispatcher) {
this[kClients].set(origin, { count: 0, dispatcher });
}
[kFactory](origin) {
const mockOptions = Object.assign({ agent: this }, this[kOptions]);
return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions);
}
[kMockAgentGet](origin) {
const result = this[kClients].get(origin);
if (result?.dispatcher) {
return result.dispatcher;
}
if (typeof origin !== "string") {
const dispatcher = this[kFactory]("http://localhost:9999");
this[kMockAgentSet](origin, dispatcher);
return dispatcher;
}
for (const [keyMatcher, result2] of Array.from(this[kClients])) {
if (result2 && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
const dispatcher = this[kFactory](origin);
this[kMockAgentSet](origin, dispatcher);
dispatcher[kDispatches] = result2.dispatcher[kDispatches];
return dispatcher;
}
}
}
[kGetNetConnect]() {
return this[kNetConnect];
}
pendingInterceptors() {
const mockAgentClients = this[kClients];
return Array.from(mockAgentClients.entries()).flatMap(([origin, result]) => result.dispatcher[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
}
assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
const pending = this.pendingInterceptors();
if (pending.length === 0) {
return;
}
throw new UndiciError(
pending.length === 1 ? `1 interceptor is pending:
${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending:
${pendingInterceptorsFormatter.format(pending)}`.trim()
);
}
};
module3.exports = MockAgent;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/global.js
var require_global2 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/global.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var globalDispatcher = Symbol.for("undici.globalDispatcher.1");
var { InvalidArgumentError } = require_errors();
var Agent = require_agent();
if (getGlobalDispatcher2() === void 0) {
setGlobalDispatcher2(new Agent());
}
function setGlobalDispatcher2(agent) {
if (!agent || typeof agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument agent must implement Agent");
}
Object.defineProperty(globalThis, globalDispatcher, {
value: agent,
writable: true,
enumerable: false,
configurable: false
});
}
__name(setGlobalDispatcher2, "setGlobalDispatcher");
function getGlobalDispatcher2() {
return globalThis[globalDispatcher];
}
__name(getGlobalDispatcher2, "getGlobalDispatcher");
module3.exports = {
setGlobalDispatcher: setGlobalDispatcher2,
getGlobalDispatcher: getGlobalDispatcher2
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/decorator-handler.js
var require_decorator_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/decorator-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var WrapHandler = require_wrap_handler();
module3.exports = class DecoratorHandler {
static {
__name(this, "DecoratorHandler");
}
#handler;
#onCompleteCalled = false;
#onErrorCalled = false;
#onResponseStartCalled = false;
constructor(handler) {
if (typeof handler !== "object" || handler === null) {
throw new TypeError("handler must be an object");
}
this.#handler = WrapHandler.wrap(handler);
}
onRequestStart(...args) {
this.#handler.onRequestStart?.(...args);
}
onRequestUpgrade(...args) {
assert44(!this.#onCompleteCalled);
assert44(!this.#onErrorCalled);
return this.#handler.onRequestUpgrade?.(...args);
}
onResponseStart(...args) {
assert44(!this.#onCompleteCalled);
assert44(!this.#onErrorCalled);
assert44(!this.#onResponseStartCalled);
this.#onResponseStartCalled = true;
return this.#handler.onResponseStart?.(...args);
}
onResponseData(...args) {
assert44(!this.#onCompleteCalled);
assert44(!this.#onErrorCalled);
return this.#handler.onResponseData?.(...args);
}
onResponseEnd(...args) {
assert44(!this.#onCompleteCalled);
assert44(!this.#onErrorCalled);
this.#onCompleteCalled = true;
return this.#handler.onResponseEnd?.(...args);
}
onResponseError(...args) {
this.#onErrorCalled = true;
return this.#handler.onResponseError?.(...args);
}
/**
* @deprecated
*/
onBodySent() {
}
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/redirect-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var util3 = require_util();
var { kBodyUsed } = require_symbols();
var assert44 = require("assert");
var { InvalidArgumentError } = require_errors();
var EE = require("events");
var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
var kBody = Symbol("body");
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
var BodyAsyncIterable = class {
static {
__name(this, "BodyAsyncIterable");
}
constructor(body) {
this[kBody] = body;
this[kBodyUsed] = false;
}
async *[Symbol.asyncIterator]() {
assert44(!this[kBodyUsed], "disturbed");
this[kBodyUsed] = true;
yield* this[kBody];
}
};
var RedirectHandler = class _RedirectHandler {
static {
__name(this, "RedirectHandler");
}
static buildDispatch(dispatcher, maxRedirections) {
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
throw new InvalidArgumentError("maxRedirections must be a positive number");
}
const dispatch = dispatcher.dispatch.bind(dispatcher);
return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler));
}
constructor(dispatch, maxRedirections, opts, handler) {
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
throw new InvalidArgumentError("maxRedirections must be a positive number");
}
this.dispatch = dispatch;
this.location = null;
this.opts = { ...opts, maxRedirections: 0 };
this.maxRedirections = maxRedirections;
this.handler = handler;
this.history = [];
if (util3.isStream(this.opts.body)) {
if (util3.bodyLength(this.opts.body) === 0) {
this.opts.body.on("data", function() {
assert44(false);
});
}
if (typeof this.opts.body.readableDidRead !== "boolean") {
this.opts.body[kBodyUsed] = false;
EE.prototype.on.call(this.opts.body, "data", function() {
this[kBodyUsed] = true;
});
}
} else if (this.opts.body && typeof this.opts.body.pipeTo === "function") {
this.opts.body = new BodyAsyncIterable(this.opts.body);
} else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util3.isIterable(this.opts.body) && !util3.isFormDataLike(this.opts.body)) {
this.opts.body = new BodyAsyncIterable(this.opts.body);
}
}
onRequestStart(controller, context2) {
this.handler.onRequestStart?.(controller, { ...context2, history: this.history });
}
onRequestUpgrade(controller, statusCode, headers, socket) {
this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
throw new Error("max redirects");
}
if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
this.opts.method = "GET";
if (util3.isStream(this.opts.body)) {
util3.destroy(this.opts.body.on("error", noop));
}
this.opts.body = null;
}
if (statusCode === 303 && this.opts.method !== "HEAD") {
this.opts.method = "GET";
if (util3.isStream(this.opts.body)) {
util3.destroy(this.opts.body.on("error", noop));
}
this.opts.body = null;
}
this.location = this.history.length >= this.maxRedirections || util3.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location;
if (this.opts.origin) {
this.history.push(new URL(this.opts.path, this.opts.origin));
}
if (!this.location) {
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
return;
}
const { origin, pathname, search } = util3.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
const path72 = search ? `${pathname}${search}` : pathname;
this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
this.opts.path = path72;
this.opts.origin = origin;
this.opts.maxRedirections = 0;
this.opts.query = null;
}
onResponseData(controller, chunk) {
if (this.location) {
} else {
this.handler.onResponseData?.(controller, chunk);
}
}
onResponseEnd(controller, trailers) {
if (this.location) {
this.dispatch(this.opts, this);
} else {
this.handler.onResponseEnd(controller, trailers);
}
}
onResponseError(controller, error2) {
this.handler.onResponseError?.(controller, error2);
}
};
function shouldRemoveHeader(header, removeContent, unknownOrigin) {
if (header.length === 4) {
return util3.headerNameToString(header) === "host";
}
if (removeContent && util3.headerNameToString(header).startsWith("content-")) {
return true;
}
if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
const name2 = util3.headerNameToString(header);
return name2 === "authorization" || name2 === "cookie" || name2 === "proxy-authorization";
}
return false;
}
__name(shouldRemoveHeader, "shouldRemoveHeader");
function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
const ret = [];
if (Array.isArray(headers)) {
for (let i5 = 0; i5 < headers.length; i5 += 2) {
if (!shouldRemoveHeader(headers[i5], removeContent, unknownOrigin)) {
ret.push(headers[i5], headers[i5 + 1]);
}
}
} else if (headers && typeof headers === "object") {
const entries = typeof headers[Symbol.iterator] === "function" ? headers : Object.entries(headers);
for (const [key, value] of entries) {
if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
ret.push(key, value);
}
}
} else {
assert44(headers == null, "headers must be an object or an array");
}
return ret;
}
__name(cleanRequestHeaders, "cleanRequestHeaders");
module3.exports = RedirectHandler;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/redirect.js
var require_redirect = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/redirect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var RedirectHandler = require_redirect_handler();
function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections } = {}) {
return (dispatch) => {
return /* @__PURE__ */ __name(function Intercept(opts, handler) {
const { maxRedirections = defaultMaxRedirections, ...rest } = opts;
if (maxRedirections == null || maxRedirections === 0) {
return dispatch(opts, handler);
}
const dispatchOpts = { ...rest, maxRedirections: 0 };
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler);
return dispatch(dispatchOpts, redirectHandler);
}, "Intercept");
};
}
__name(createRedirectInterceptor, "createRedirectInterceptor");
module3.exports = createRedirectInterceptor;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/response-error.js
var require_response_error = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/response-error.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DecoratorHandler = require_decorator_handler();
var { ResponseError } = require_errors();
var ResponseErrorHandler = class extends DecoratorHandler {
static {
__name(this, "ResponseErrorHandler");
}
#statusCode;
#contentType;
#decoder;
#headers;
#body;
constructor(_opts, { handler }) {
super(handler);
}
#checkContentType(contentType) {
return (this.#contentType ?? "").indexOf(contentType) === 0;
}
onRequestStart(controller, context2) {
this.#statusCode = 0;
this.#contentType = null;
this.#decoder = null;
this.#headers = null;
this.#body = "";
return super.onRequestStart(controller, context2);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
this.#statusCode = statusCode;
this.#headers = headers;
this.#contentType = headers["content-type"];
if (this.#statusCode < 400) {
return super.onResponseStart(controller, statusCode, headers, statusMessage);
}
if (this.#checkContentType("application/json") || this.#checkContentType("text/plain")) {
this.#decoder = new TextDecoder("utf-8");
}
}
onResponseData(controller, chunk) {
if (this.#statusCode < 400) {
return super.onResponseData(controller, chunk);
}
this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? "";
}
onResponseEnd(controller, trailers) {
if (this.#statusCode >= 400) {
this.#body += this.#decoder?.decode(void 0, { stream: false }) ?? "";
if (this.#checkContentType("application/json")) {
try {
this.#body = JSON.parse(this.#body);
} catch {
}
}
let err;
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
try {
err = new ResponseError("Response Error", this.#statusCode, {
body: this.#body,
headers: this.#headers
});
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
super.onResponseError(controller, err);
} else {
super.onResponseEnd(controller, trailers);
}
}
onResponseError(controller, err) {
super.onResponseError(controller, err);
}
};
module3.exports = () => {
return (dispatch) => {
return /* @__PURE__ */ __name(function Intercept(opts, handler) {
return dispatch(opts, new ResponseErrorHandler(opts, { handler }));
}, "Intercept");
};
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/retry.js
var require_retry = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/retry.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var RetryHandler = require_retry_handler();
module3.exports = (globalOpts) => {
return (dispatch) => {
return /* @__PURE__ */ __name(function retryInterceptor(opts, handler) {
return dispatch(
opts,
new RetryHandler(
{ ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
{
handler,
dispatch
}
)
);
}, "retryInterceptor");
};
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/dump.js
var require_dump = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/dump.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { InvalidArgumentError, RequestAbortedError } = require_errors();
var DecoratorHandler = require_decorator_handler();
var DumpHandler = class extends DecoratorHandler {
static {
__name(this, "DumpHandler");
}
#maxSize = 1024 * 1024;
#dumped = false;
#size = 0;
#controller = null;
aborted = false;
reason = false;
constructor({ maxSize, signal }, handler) {
if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
throw new InvalidArgumentError("maxSize must be a number greater than 0");
}
super(handler);
this.#maxSize = maxSize ?? this.#maxSize;
}
#abort(reason) {
this.aborted = true;
this.reason = reason;
}
onRequestStart(controller, context2) {
controller.abort = this.#abort.bind(this);
this.#controller = controller;
return super.onRequestStart(controller, context2);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
const contentLength = headers["content-length"];
if (contentLength != null && contentLength > this.#maxSize) {
throw new RequestAbortedError(
`Response size (${contentLength}) larger than maxSize (${this.#maxSize})`
);
}
if (this.aborted === true) {
return true;
}
return super.onResponseStart(controller, statusCode, headers, statusMessage);
}
onResponseError(controller, err) {
if (this.#dumped) {
return;
}
err = this.#controller.reason ?? err;
super.onResponseError(controller, err);
}
onResponseData(controller, chunk) {
this.#size = this.#size + chunk.length;
if (this.#size >= this.#maxSize) {
this.#dumped = true;
if (this.aborted === true) {
super.onResponseError(controller, this.reason);
} else {
super.onResponseEnd(controller, {});
}
}
return true;
}
onResponseEnd(controller, trailers) {
if (this.#dumped) {
return;
}
if (this.#controller.aborted === true) {
super.onResponseError(controller, this.reason);
return;
}
super.onResponseEnd(controller, trailers);
}
};
function createDumpInterceptor({ maxSize: defaultMaxSize } = {
maxSize: 1024 * 1024
}) {
return (dispatch) => {
return /* @__PURE__ */ __name(function Intercept(opts, handler) {
const { dumpMaxSize = defaultMaxSize } = opts;
const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler);
return dispatch(opts, dumpHandler);
}, "Intercept");
};
}
__name(createDumpInterceptor, "createDumpInterceptor");
module3.exports = createDumpInterceptor;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/dns.js
var require_dns = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/dns.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { isIP } = require("net");
var { lookup } = require("dns");
var DecoratorHandler = require_decorator_handler();
var { InvalidArgumentError, InformationalError } = require_errors();
var maxInt = Math.pow(2, 31) - 1;
var DNSInstance = class {
static {
__name(this, "DNSInstance");
}
#maxTTL = 0;
#maxItems = 0;
#records = /* @__PURE__ */ new Map();
dualStack = true;
affinity = null;
lookup = null;
pick = null;
constructor(opts) {
this.#maxTTL = opts.maxTTL;
this.#maxItems = opts.maxItems;
this.dualStack = opts.dualStack;
this.affinity = opts.affinity;
this.lookup = opts.lookup ?? this.#defaultLookup;
this.pick = opts.pick ?? this.#defaultPick;
}
get full() {
return this.#records.size === this.#maxItems;
}
runLookup(origin, opts, cb2) {
const ips = this.#records.get(origin.hostname);
if (ips == null && this.full) {
cb2(null, origin);
return;
}
const newOpts = {
affinity: this.affinity,
dualStack: this.dualStack,
lookup: this.lookup,
pick: this.pick,
...opts.dns,
maxTTL: this.#maxTTL,
maxItems: this.#maxItems
};
if (ips == null) {
this.lookup(origin, newOpts, (err, addresses) => {
if (err || addresses == null || addresses.length === 0) {
cb2(err ?? new InformationalError("No DNS entries found"));
return;
}
this.setRecords(origin, addresses);
const records = this.#records.get(origin.hostname);
const ip = this.pick(
origin,
records,
newOpts.affinity
);
let port;
if (typeof ip.port === "number") {
port = `:${ip.port}`;
} else if (origin.port !== "") {
port = `:${origin.port}`;
} else {
port = "";
}
cb2(
null,
new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
);
});
} else {
const ip = this.pick(
origin,
ips,
newOpts.affinity
);
if (ip == null) {
this.#records.delete(origin.hostname);
this.runLookup(origin, opts, cb2);
return;
}
let port;
if (typeof ip.port === "number") {
port = `:${ip.port}`;
} else if (origin.port !== "") {
port = `:${origin.port}`;
} else {
port = "";
}
cb2(
null,
new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
);
}
}
#defaultLookup(origin, opts, cb2) {
lookup(
origin.hostname,
{
all: true,
family: this.dualStack === false ? this.affinity : 0,
order: "ipv4first"
},
(err, addresses) => {
if (err) {
return cb2(err);
}
const results = /* @__PURE__ */ new Map();
for (const addr of addresses) {
results.set(`${addr.address}:${addr.family}`, addr);
}
cb2(null, results.values());
}
);
}
#defaultPick(origin, hostnameRecords, affinity) {
let ip = null;
const { records, offset } = hostnameRecords;
let family;
if (this.dualStack) {
if (affinity == null) {
if (offset == null || offset === maxInt) {
hostnameRecords.offset = 0;
affinity = 4;
} else {
hostnameRecords.offset++;
affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4;
}
}
if (records[affinity] != null && records[affinity].ips.length > 0) {
family = records[affinity];
} else {
family = records[affinity === 4 ? 6 : 4];
}
} else {
family = records[affinity];
}
if (family == null || family.ips.length === 0) {
return ip;
}
if (family.offset == null || family.offset === maxInt) {
family.offset = 0;
} else {
family.offset++;
}
const position = family.offset % family.ips.length;
ip = family.ips[position] ?? null;
if (ip == null) {
return ip;
}
if (Date.now() - ip.timestamp > ip.ttl) {
family.ips.splice(position, 1);
return this.pick(origin, hostnameRecords, affinity);
}
return ip;
}
pickFamily(origin, ipFamily) {
const records = this.#records.get(origin.hostname)?.records;
if (!records) {
return null;
}
const family = records[ipFamily];
if (!family) {
return null;
}
if (family.offset == null || family.offset === maxInt) {
family.offset = 0;
} else {
family.offset++;
}
const position = family.offset % family.ips.length;
const ip = family.ips[position] ?? null;
if (ip == null) {
return ip;
}
if (Date.now() - ip.timestamp > ip.ttl) {
family.ips.splice(position, 1);
}
return ip;
}
setRecords(origin, addresses) {
const timestamp = Date.now();
const records = { records: { 4: null, 6: null } };
for (const record of addresses) {
record.timestamp = timestamp;
if (typeof record.ttl === "number") {
record.ttl = Math.min(record.ttl, this.#maxTTL);
} else {
record.ttl = this.#maxTTL;
}
const familyRecords = records.records[record.family] ?? { ips: [] };
familyRecords.ips.push(record);
records.records[record.family] = familyRecords;
}
this.#records.set(origin.hostname, records);
}
deleteRecords(origin) {
this.#records.delete(origin.hostname);
}
getHandler(meta, opts) {
return new DNSDispatchHandler(this, meta, opts);
}
};
var DNSDispatchHandler = class extends DecoratorHandler {
static {
__name(this, "DNSDispatchHandler");
}
#state = null;
#opts = null;
#dispatch = null;
#origin = null;
#controller = null;
#newOrigin = null;
#firstTry = true;
constructor(state2, { origin, handler, dispatch, newOrigin }, opts) {
super(handler);
this.#origin = origin;
this.#newOrigin = newOrigin;
this.#opts = { ...opts };
this.#state = state2;
this.#dispatch = dispatch;
}
onResponseError(controller, err) {
switch (err.code) {
case "ETIMEDOUT":
case "ECONNREFUSED": {
if (this.#state.dualStack) {
if (!this.#firstTry) {
super.onResponseError(controller, err);
return;
}
this.#firstTry = false;
const otherFamily = this.#newOrigin.hostname[0] === "[" ? 4 : 6;
const ip = this.#state.pickFamily(this.#origin, otherFamily);
if (ip == null) {
super.onResponseError(controller, err);
return;
}
let port;
if (typeof ip.port === "number") {
port = `:${ip.port}`;
} else if (this.#origin.port !== "") {
port = `:${this.#origin.port}`;
} else {
port = "";
}
const dispatchOpts = {
...this.#opts,
origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
};
this.#dispatch(dispatchOpts, this);
return;
}
super.onResponseError(controller, err);
break;
}
case "ENOTFOUND":
this.#state.deleteRecords(this.#origin);
super.onResponseError(controller, err);
break;
default:
super.onResponseError(controller, err);
break;
}
}
};
module3.exports = (interceptorOpts) => {
if (interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== "number" || interceptorOpts?.maxTTL < 0)) {
throw new InvalidArgumentError("Invalid maxTTL. Must be a positive number");
}
if (interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== "number" || interceptorOpts?.maxItems < 1)) {
throw new InvalidArgumentError(
"Invalid maxItems. Must be a positive number and greater than zero"
);
}
if (interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6) {
throw new InvalidArgumentError("Invalid affinity. Must be either 4 or 6");
}
if (interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== "boolean") {
throw new InvalidArgumentError("Invalid dualStack. Must be a boolean");
}
if (interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== "function") {
throw new InvalidArgumentError("Invalid lookup. Must be a function");
}
if (interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== "function") {
throw new InvalidArgumentError("Invalid pick. Must be a function");
}
const dualStack = interceptorOpts?.dualStack ?? true;
let affinity;
if (dualStack) {
affinity = interceptorOpts?.affinity ?? null;
} else {
affinity = interceptorOpts?.affinity ?? 4;
}
const opts = {
maxTTL: interceptorOpts?.maxTTL ?? 1e4,
// Expressed in ms
lookup: interceptorOpts?.lookup ?? null,
pick: interceptorOpts?.pick ?? null,
dualStack,
affinity,
maxItems: interceptorOpts?.maxItems ?? Infinity
};
const instance = new DNSInstance(opts);
return (dispatch) => {
return /* @__PURE__ */ __name(function dnsInterceptor(origDispatchOpts, handler) {
const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
if (isIP(origin.hostname) !== 0) {
return dispatch(origDispatchOpts, handler);
}
instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
if (err) {
return handler.onResponseError(null, err);
}
const dispatchOpts = {
...origDispatchOpts,
servername: origin.hostname,
// For SNI on TLS
origin: newOrigin.origin,
headers: {
host: origin.host,
...origDispatchOpts.headers
}
};
dispatch(
dispatchOpts,
instance.getHandler(
{ origin, dispatch, handler, newOrigin },
origDispatchOpts
)
);
});
return true;
}, "dnsInterceptor");
};
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/cache.js
var require_cache = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/cache.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
safeHTTPMethods
} = require_util();
var { serializePathWithQuery } = require_util();
function makeCacheKey(opts) {
if (!opts.origin) {
throw new Error("opts.origin is undefined");
}
let fullPath;
try {
fullPath = serializePathWithQuery(opts.path || "/", opts.query);
} catch (error2) {
fullPath = opts.path || "/";
}
return {
origin: opts.origin.toString(),
method: opts.method,
path: fullPath,
headers: opts.headers
};
}
__name(makeCacheKey, "makeCacheKey");
function normaliseHeaders2(opts) {
let headers;
if (opts.headers == null) {
headers = {};
} else if (typeof opts.headers[Symbol.iterator] === "function") {
headers = {};
for (const x6 of opts.headers) {
if (!Array.isArray(x6)) {
throw new Error("opts.headers is not a valid header map");
}
const [key, val2] = x6;
if (typeof key !== "string" || typeof val2 !== "string") {
throw new Error("opts.headers is not a valid header map");
}
headers[key.toLowerCase()] = val2;
}
} else if (typeof opts.headers === "object") {
headers = {};
for (const key of Object.keys(opts.headers)) {
headers[key.toLowerCase()] = opts.headers[key];
}
} else {
throw new Error("opts.headers is not an object");
}
return headers;
}
__name(normaliseHeaders2, "normaliseHeaders");
function assertCacheKey(key) {
if (typeof key !== "object") {
throw new TypeError(`expected key to be object, got ${typeof key}`);
}
for (const property of ["origin", "method", "path"]) {
if (typeof key[property] !== "string") {
throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`);
}
}
if (key.headers !== void 0 && typeof key.headers !== "object") {
throw new TypeError(`expected headers to be object, got ${typeof key}`);
}
}
__name(assertCacheKey, "assertCacheKey");
function assertCacheValue(value) {
if (typeof value !== "object") {
throw new TypeError(`expected value to be object, got ${typeof value}`);
}
for (const property of ["statusCode", "cachedAt", "staleAt", "deleteAt"]) {
if (typeof value[property] !== "number") {
throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`);
}
}
if (typeof value.statusMessage !== "string") {
throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`);
}
if (value.headers != null && typeof value.headers !== "object") {
throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`);
}
if (value.vary !== void 0 && typeof value.vary !== "object") {
throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`);
}
if (value.etag !== void 0 && typeof value.etag !== "string") {
throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`);
}
}
__name(assertCacheValue, "assertCacheValue");
function parseCacheControlHeader(header) {
const output = {};
let directives;
if (Array.isArray(header)) {
directives = [];
for (const directive of header) {
directives.push(...directive.split(","));
}
} else {
directives = header.split(",");
}
for (let i5 = 0; i5 < directives.length; i5++) {
const directive = directives[i5].toLowerCase();
const keyValueDelimiter = directive.indexOf("=");
let key;
let value;
if (keyValueDelimiter !== -1) {
key = directive.substring(0, keyValueDelimiter).trimStart();
value = directive.substring(keyValueDelimiter + 1);
} else {
key = directive.trim();
}
switch (key) {
case "min-fresh":
case "max-stale":
case "max-age":
case "s-maxage":
case "stale-while-revalidate":
case "stale-if-error": {
if (value === void 0 || value[0] === " ") {
continue;
}
if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
value = value.substring(1, value.length - 1);
}
const parsedValue = parseInt(value, 10);
if (parsedValue !== parsedValue) {
continue;
}
if (key === "max-age" && key in output && output[key] >= parsedValue) {
continue;
}
output[key] = parsedValue;
break;
}
case "private":
case "no-cache": {
if (value) {
if (value[0] === '"') {
const headers = [value.substring(1)];
let foundEndingQuote = value[value.length - 1] === '"';
if (!foundEndingQuote) {
for (let j6 = i5 + 1; j6 < directives.length; j6++) {
const nextPart = directives[j6];
const nextPartLength = nextPart.length;
headers.push(nextPart.trim());
if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
foundEndingQuote = true;
break;
}
}
}
if (foundEndingQuote) {
let lastHeader = headers[headers.length - 1];
if (lastHeader[lastHeader.length - 1] === '"') {
lastHeader = lastHeader.substring(0, lastHeader.length - 1);
headers[headers.length - 1] = lastHeader;
}
if (key in output) {
output[key] = output[key].concat(headers);
} else {
output[key] = headers;
}
}
} else {
if (key in output) {
output[key] = output[key].concat(value);
} else {
output[key] = [value];
}
}
break;
}
}
// eslint-disable-next-line no-fallthrough
case "public":
case "no-store":
case "must-revalidate":
case "proxy-revalidate":
case "immutable":
case "no-transform":
case "must-understand":
case "only-if-cached":
if (value) {
continue;
}
output[key] = true;
break;
default:
continue;
}
}
return output;
}
__name(parseCacheControlHeader, "parseCacheControlHeader");
function parseVaryHeader(varyHeader, headers) {
if (typeof varyHeader === "string" && varyHeader.includes("*")) {
return headers;
}
const output = (
/** @type {Record<string, string | string[] | null>} */
{}
);
const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
for (const header of varyingHeaders) {
const trimmedHeader = header.trim().toLowerCase();
output[trimmedHeader] = headers[trimmedHeader] ?? null;
}
return output;
}
__name(parseVaryHeader, "parseVaryHeader");
function isEtagUsable(etag) {
if (etag.length <= 2) {
return false;
}
if (etag[0] === '"' && etag[etag.length - 1] === '"') {
return !(etag[1] === '"' || etag.startsWith('"W/'));
}
if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') {
return etag.length !== 4;
}
return false;
}
__name(isEtagUsable, "isEtagUsable");
function assertCacheStore(store, name2 = "CacheStore") {
if (typeof store !== "object" || store === null) {
throw new TypeError(`expected type of ${name2} to be a CacheStore, got ${store === null ? "null" : typeof store}`);
}
for (const fn2 of ["get", "createWriteStream", "delete"]) {
if (typeof store[fn2] !== "function") {
throw new TypeError(`${name2} needs to have a \`${fn2}()\` function`);
}
}
}
__name(assertCacheStore, "assertCacheStore");
function assertCacheMethods(methods, name2 = "CacheMethods") {
if (!Array.isArray(methods)) {
throw new TypeError(`expected type of ${name2} needs to be an array, got ${methods === null ? "null" : typeof methods}`);
}
if (methods.length === 0) {
throw new TypeError(`${name2} needs to have at least one method`);
}
for (const method of methods) {
if (!safeHTTPMethods.includes(method)) {
throw new TypeError(`element of ${name2}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
}
}
}
__name(assertCacheMethods, "assertCacheMethods");
module3.exports = {
makeCacheKey,
normaliseHeaders: normaliseHeaders2,
assertCacheKey,
assertCacheValue,
parseCacheControlHeader,
parseVaryHeader,
isEtagUsable,
assertCacheMethods,
assertCacheStore
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/date.js
var require_date = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/util/date.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var IMF_DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
var IMF_SPACES = [4, 7, 11, 16, 25];
var IMF_MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
var IMF_COLONS = [19, 22];
var ASCTIME_SPACES = [3, 7, 10, 19];
var RFC850_DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
function parseHttpDate(date, now) {
date = date.toLowerCase();
switch (date[3]) {
case ",":
return parseImfDate(date);
case " ":
return parseAscTimeDate(date);
default:
return parseRfc850Date(date, now);
}
}
__name(parseHttpDate, "parseHttpDate");
function parseImfDate(date) {
if (date.length !== 29) {
return void 0;
}
if (!date.endsWith("gmt")) {
return void 0;
}
for (const spaceInx of IMF_SPACES) {
if (date[spaceInx] !== " ") {
return void 0;
}
}
for (const colonIdx of IMF_COLONS) {
if (date[colonIdx] !== ":") {
return void 0;
}
}
const dayName = date.substring(0, 3);
if (!IMF_DAYS.includes(dayName)) {
return void 0;
}
const dayString = date.substring(5, 7);
const day = Number.parseInt(dayString);
if (isNaN(day) || day < 10 && dayString[0] !== "0") {
return void 0;
}
const month = date.substring(8, 11);
const monthIdx = IMF_MONTHS.indexOf(month);
if (monthIdx === -1) {
return void 0;
}
const year = Number.parseInt(date.substring(12, 16));
if (isNaN(year)) {
return void 0;
}
const hourString = date.substring(17, 19);
const hour = Number.parseInt(hourString);
if (isNaN(hour) || hour < 10 && hourString[0] !== "0") {
return void 0;
}
const minuteString = date.substring(20, 22);
const minute = Number.parseInt(minuteString);
if (isNaN(minute) || minute < 10 && minuteString[0] !== "0") {
return void 0;
}
const secondString = date.substring(23, 25);
const second = Number.parseInt(secondString);
if (isNaN(second) || second < 10 && secondString[0] !== "0") {
return void 0;
}
return new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
}
__name(parseImfDate, "parseImfDate");
function parseAscTimeDate(date) {
if (date.length !== 24) {
return void 0;
}
for (const spaceIdx of ASCTIME_SPACES) {
if (date[spaceIdx] !== " ") {
return void 0;
}
}
const dayName = date.substring(0, 3);
if (!IMF_DAYS.includes(dayName)) {
return void 0;
}
const month = date.substring(4, 7);
const monthIdx = IMF_MONTHS.indexOf(month);
if (monthIdx === -1) {
return void 0;
}
const dayString = date.substring(8, 10);
const day = Number.parseInt(dayString);
if (isNaN(day) || day < 10 && dayString[0] !== " ") {
return void 0;
}
const hourString = date.substring(11, 13);
const hour = Number.parseInt(hourString);
if (isNaN(hour) || hour < 10 && hourString[0] !== "0") {
return void 0;
}
const minuteString = date.substring(14, 16);
const minute = Number.parseInt(minuteString);
if (isNaN(minute) || minute < 10 && minuteString[0] !== "0") {
return void 0;
}
const secondString = date.substring(17, 19);
const second = Number.parseInt(secondString);
if (isNaN(second) || second < 10 && secondString[0] !== "0") {
return void 0;
}
const year = Number.parseInt(date.substring(20, 24));
if (isNaN(year)) {
return void 0;
}
return new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
}
__name(parseAscTimeDate, "parseAscTimeDate");
function parseRfc850Date(date, now = /* @__PURE__ */ new Date()) {
if (!date.endsWith("gmt")) {
return void 0;
}
const commaIndex = date.indexOf(",");
if (commaIndex === -1) {
return void 0;
}
if (date.length - commaIndex - 1 !== 23) {
return void 0;
}
const dayName = date.substring(0, commaIndex);
if (!RFC850_DAYS.includes(dayName)) {
return void 0;
}
if (date[commaIndex + 1] !== " " || date[commaIndex + 4] !== "-" || date[commaIndex + 8] !== "-" || date[commaIndex + 11] !== " " || date[commaIndex + 14] !== ":" || date[commaIndex + 17] !== ":" || date[commaIndex + 20] !== " ") {
return void 0;
}
const dayString = date.substring(commaIndex + 2, commaIndex + 4);
const day = Number.parseInt(dayString);
if (isNaN(day) || day < 10 && dayString[0] !== "0") {
return void 0;
}
const month = date.substring(commaIndex + 5, commaIndex + 8);
const monthIdx = IMF_MONTHS.indexOf(month);
if (monthIdx === -1) {
return void 0;
}
let year = Number.parseInt(date.substring(commaIndex + 9, commaIndex + 11));
if (isNaN(year)) {
return void 0;
}
const currentYear = now.getUTCFullYear();
const currentDecade = currentYear % 100;
const currentCentury = Math.floor(currentYear / 100);
if (year > currentDecade && year - currentDecade >= 50) {
year += (currentCentury - 1) * 100;
} else {
year += currentCentury * 100;
}
const hourString = date.substring(commaIndex + 12, commaIndex + 14);
const hour = Number.parseInt(hourString);
if (isNaN(hour) || hour < 10 && hourString[0] !== "0") {
return void 0;
}
const minuteString = date.substring(commaIndex + 15, commaIndex + 17);
const minute = Number.parseInt(minuteString);
if (isNaN(minute) || minute < 10 && minuteString[0] !== "0") {
return void 0;
}
const secondString = date.substring(commaIndex + 18, commaIndex + 20);
const second = Number.parseInt(secondString);
if (isNaN(second) || second < 10 && secondString[0] !== "0") {
return void 0;
}
return new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
}
__name(parseRfc850Date, "parseRfc850Date");
module3.exports = {
parseHttpDate
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/cache-handler.js
var require_cache_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/cache-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var util3 = require_util();
var {
parseCacheControlHeader,
parseVaryHeader,
isEtagUsable
} = require_cache();
var { parseHttpDate } = require_date();
function noop() {
}
__name(noop, "noop");
var HEURISTICALLY_CACHEABLE_STATUS_CODES = [
200,
203,
204,
206,
300,
301,
308,
404,
405,
410,
414,
501
];
var MAX_RESPONSE_AGE = 2147483647e3;
var CacheHandler = class {
static {
__name(this, "CacheHandler");
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
#cacheKey;
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']}
*/
#cacheType;
/**
* @type {number | undefined}
*/
#cacheByDefault;
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheStore}
*/
#store;
/**
* @type {import('../../types/dispatcher.d.ts').default.DispatchHandler}
*/
#handler;
/**
* @type {import('node:stream').Writable | undefined}
*/
#writeStream;
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
*/
constructor({ store, type, cacheByDefault }, cacheKey, handler) {
this.#store = store;
this.#cacheType = type;
this.#cacheByDefault = cacheByDefault;
this.#cacheKey = cacheKey;
this.#handler = handler;
}
onRequestStart(controller, context2) {
this.#writeStream?.destroy();
this.#writeStream = void 0;
this.#handler.onRequestStart?.(controller, context2);
}
onRequestUpgrade(controller, statusCode, headers, socket) {
this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {string} statusMessage
*/
onResponseStart(controller, statusCode, resHeaders, statusMessage) {
const downstreamOnHeaders = /* @__PURE__ */ __name(() => this.#handler.onResponseStart?.(
controller,
statusCode,
resHeaders,
statusMessage
), "downstreamOnHeaders");
if (!util3.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
try {
this.#store.delete(this.#cacheKey)?.catch?.(noop);
} catch {
}
return downstreamOnHeaders();
}
const cacheControlHeader = resHeaders["cache-control"];
const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
return downstreamOnHeaders();
}
const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) {
return downstreamOnHeaders();
}
const now = Date.now();
const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
if (resAge && resAge >= MAX_RESPONSE_AGE) {
return downstreamOnHeaders();
}
const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
if (staleAt === void 0 || resAge && resAge > staleAt) {
return downstreamOnHeaders();
}
const baseTime = resDate ? resDate.getTime() : now;
const absoluteStaleAt = staleAt + baseTime;
if (now >= absoluteStaleAt) {
return downstreamOnHeaders();
}
let varyDirectives;
if (this.#cacheKey.headers && resHeaders.vary) {
varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers);
if (!varyDirectives) {
return downstreamOnHeaders();
}
}
const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
const value = {
statusCode,
statusMessage,
headers: strippedHeaders,
vary: varyDirectives,
cacheControlDirectives,
cachedAt: resAge ? now - resAge : now,
staleAt: absoluteStaleAt,
deleteAt
};
if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) {
value.etag = resHeaders.etag;
}
this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
if (!this.#writeStream) {
return downstreamOnHeaders();
}
const handler = this;
this.#writeStream.on("drain", () => controller.resume()).on("error", function() {
handler.#writeStream = void 0;
handler.#store.delete(handler.#cacheKey);
}).on("close", function() {
if (handler.#writeStream === this) {
handler.#writeStream = void 0;
}
controller.resume();
});
return downstreamOnHeaders();
}
onResponseData(controller, chunk) {
if (this.#writeStream?.write(chunk) === false) {
controller.pause();
}
this.#handler.onResponseData?.(controller, chunk);
}
onResponseEnd(controller, trailers) {
this.#writeStream?.end();
this.#handler.onResponseEnd?.(controller, trailers);
}
onResponseError(controller, err) {
this.#writeStream?.destroy(err);
this.#writeStream = void 0;
this.#handler.onResponseError?.(controller, err);
}
};
function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives) {
if (statusCode !== 200 && statusCode !== 307) {
return false;
}
if (cacheControlDirectives["no-store"]) {
return false;
}
if (cacheType === "shared" && cacheControlDirectives.private === true) {
return false;
}
if (resHeaders.vary?.includes("*")) {
return false;
}
if (resHeaders.authorization) {
if (!cacheControlDirectives.public || typeof resHeaders.authorization !== "string") {
return false;
}
if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
return false;
}
if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
return false;
}
}
return true;
}
__name(canCacheResponse, "canCacheResponse");
function getAge(ageHeader) {
const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
return isNaN(age) ? void 0 : age * 1e3;
}
__name(getAge, "getAge");
function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
if (cacheType === "shared") {
const sMaxAge = cacheControlDirectives["s-maxage"];
if (sMaxAge !== void 0) {
return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
}
}
const maxAge = cacheControlDirectives["max-age"];
if (maxAge !== void 0) {
return maxAge > 0 ? maxAge * 1e3 : void 0;
}
if (typeof resHeaders.expires === "string") {
const expiresDate = parseHttpDate(resHeaders.expires);
if (expiresDate) {
if (now >= expiresDate.getTime()) {
return void 0;
}
if (responseDate) {
if (responseDate >= expiresDate) {
return void 0;
}
if (age !== void 0 && age > expiresDate - responseDate) {
return void 0;
}
}
return expiresDate.getTime() - now;
}
}
if (typeof resHeaders["last-modified"] === "string") {
const lastModified = new Date(resHeaders["last-modified"]);
if (isValidDate2(lastModified)) {
if (lastModified.getTime() >= now) {
return void 0;
}
const responseAge = now - lastModified.getTime();
return responseAge * 0.1;
}
}
if (cacheControlDirectives.immutable) {
return 31536e3;
}
return void 0;
}
__name(determineStaleAt, "determineStaleAt");
function determineDeleteAt(now, cacheControlDirectives, staleAt) {
let staleWhileRevalidate = -Infinity;
let staleIfError = -Infinity;
let immutable = -Infinity;
if (cacheControlDirectives["stale-while-revalidate"]) {
staleWhileRevalidate = staleAt + cacheControlDirectives["stale-while-revalidate"] * 1e3;
}
if (cacheControlDirectives["stale-if-error"]) {
staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
}
if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
immutable = now + 31536e6;
}
return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
}
__name(determineDeleteAt, "determineDeleteAt");
function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
const headersToRemove = [
"connection",
"proxy-authenticate",
"proxy-authentication-info",
"proxy-authorization",
"proxy-connection",
"te",
"transfer-encoding",
"upgrade",
// We'll add age back when serving it
"age"
];
if (resHeaders["connection"]) {
if (Array.isArray(resHeaders["connection"])) {
headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
} else {
headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
}
}
if (Array.isArray(cacheControlDirectives["no-cache"])) {
headersToRemove.push(...cacheControlDirectives["no-cache"]);
}
if (Array.isArray(cacheControlDirectives["private"])) {
headersToRemove.push(...cacheControlDirectives["private"]);
}
let strippedHeaders;
for (const headerName of headersToRemove) {
if (resHeaders[headerName]) {
strippedHeaders ??= { ...resHeaders };
delete strippedHeaders[headerName];
}
}
return strippedHeaders ?? resHeaders;
}
__name(stripNecessaryHeaders, "stripNecessaryHeaders");
function isValidDate2(date) {
return date instanceof Date && Number.isFinite(date.valueOf());
}
__name(isValidDate2, "isValidDate");
module3.exports = CacheHandler;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/cache/memory-cache-store.js
var require_memory_cache_store = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/cache/memory-cache-store.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Writable: Writable5 } = require("stream");
var { EventEmitter: EventEmitter5 } = require("events");
var { assertCacheKey, assertCacheValue } = require_cache();
var MemoryCacheStore = class extends EventEmitter5 {
static {
__name(this, "MemoryCacheStore");
}
#maxCount = 1024;
#maxSize = 104857600;
// 100MB
#maxEntrySize = 5242880;
// 5MB
#size = 0;
#count = 0;
#entries = /* @__PURE__ */ new Map();
#hasEmittedMaxSizeEvent = false;
/**
* @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts]
*/
constructor(opts) {
super();
if (opts) {
if (typeof opts !== "object") {
throw new TypeError("MemoryCacheStore options must be an object");
}
if (opts.maxCount !== void 0) {
if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
throw new TypeError("MemoryCacheStore options.maxCount must be a non-negative integer");
}
this.#maxCount = opts.maxCount;
}
if (opts.maxSize !== void 0) {
if (typeof opts.maxSize !== "number" || !Number.isInteger(opts.maxSize) || opts.maxSize < 0) {
throw new TypeError("MemoryCacheStore options.maxSize must be a non-negative integer");
}
this.#maxSize = opts.maxSize;
}
if (opts.maxEntrySize !== void 0) {
if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
throw new TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer");
}
this.#maxEntrySize = opts.maxEntrySize;
}
}
}
/**
* Get the current size of the cache in bytes
* @returns {number} The current size of the cache in bytes
*/
get size() {
return this.#size;
}
/**
* Check if the cache is full (either max size or max count reached)
* @returns {boolean} True if the cache is full, false otherwise
*/
isFull() {
return this.#size >= this.#maxSize || this.#count >= this.#maxCount;
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req
* @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined}
*/
get(key) {
assertCacheKey(key);
const topLevelKey = `${key.origin}:${key.path}`;
const now = Date.now();
const entries = this.#entries.get(topLevelKey);
const entry = entries ? findEntry(key, entries, now) : null;
return entry == null ? void 0 : {
statusMessage: entry.statusMessage,
statusCode: entry.statusCode,
headers: entry.headers,
body: entry.body,
vary: entry.vary ? entry.vary : void 0,
etag: entry.etag,
cacheControlDirectives: entry.cacheControlDirectives,
cachedAt: entry.cachedAt,
staleAt: entry.staleAt,
deleteAt: entry.deleteAt
};
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val
* @returns {Writable | undefined}
*/
createWriteStream(key, val2) {
assertCacheKey(key);
assertCacheValue(val2);
const topLevelKey = `${key.origin}:${key.path}`;
const store = this;
const entry = { ...key, ...val2, body: [], size: 0 };
return new Writable5({
write(chunk, encoding, callback) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding);
}
entry.size += chunk.byteLength;
if (entry.size >= store.#maxEntrySize) {
this.destroy();
} else {
entry.body.push(chunk);
}
callback(null);
},
final(callback) {
let entries = store.#entries.get(topLevelKey);
if (!entries) {
entries = [];
store.#entries.set(topLevelKey, entries);
}
const previousEntry = findEntry(key, entries, Date.now());
if (previousEntry) {
const index = entries.indexOf(previousEntry);
entries.splice(index, 1, entry);
store.#size -= previousEntry.size;
} else {
entries.push(entry);
store.#count += 1;
}
store.#size += entry.size;
if (store.#size > store.#maxSize || store.#count > store.#maxCount) {
if (!store.#hasEmittedMaxSizeEvent) {
store.emit("maxSizeExceeded", {
size: store.#size,
maxSize: store.#maxSize,
count: store.#count,
maxCount: store.#maxCount
});
store.#hasEmittedMaxSizeEvent = true;
}
for (const [key2, entries2] of store.#entries) {
for (const entry2 of entries2.splice(0, entries2.length / 2)) {
store.#size -= entry2.size;
store.#count -= 1;
}
if (entries2.length === 0) {
store.#entries.delete(key2);
}
}
if (store.#size < store.#maxSize && store.#count < store.#maxCount) {
store.#hasEmittedMaxSizeEvent = false;
}
}
callback(null);
}
});
}
/**
* @param {CacheKey} key
*/
delete(key) {
if (typeof key !== "object") {
throw new TypeError(`expected key to be object, got ${typeof key}`);
}
const topLevelKey = `${key.origin}:${key.path}`;
for (const entry of this.#entries.get(topLevelKey) ?? []) {
this.#size -= entry.size;
this.#count -= 1;
}
this.#entries.delete(topLevelKey);
}
};
function findEntry(key, entries, now) {
return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
if (entry.vary[headerName] === null) {
return key.headers[headerName] === void 0;
}
return entry.vary[headerName] === key.headers[headerName];
})));
}
__name(findEntry, "findEntry");
module3.exports = MemoryCacheStore;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/cache-revalidation-handler.js
var require_cache_revalidation_handler = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/handler/cache-revalidation-handler.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var CacheRevalidationHandler = class {
static {
__name(this, "CacheRevalidationHandler");
}
#successful = false;
/**
* @type {((boolean, any) => void) | null}
*/
#callback;
/**
* @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)}
*/
#handler;
#context;
/**
* @type {boolean}
*/
#allowErrorStatusCodes;
/**
* @param {(boolean) => void} callback Function to call if the cached value is valid
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
* @param {boolean} allowErrorStatusCodes
*/
constructor(callback, handler, allowErrorStatusCodes) {
if (typeof callback !== "function") {
throw new TypeError("callback must be a function");
}
this.#callback = callback;
this.#handler = handler;
this.#allowErrorStatusCodes = allowErrorStatusCodes;
}
onRequestStart(_4, context2) {
this.#successful = false;
this.#context = context2;
}
onRequestUpgrade(controller, statusCode, headers, socket) {
this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
assert44(this.#callback != null);
this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
this.#callback(this.#successful, this.#context);
this.#callback = null;
if (this.#successful) {
return true;
}
this.#handler.onRequestStart?.(controller, this.#context);
this.#handler.onResponseStart?.(
controller,
statusCode,
headers,
statusMessage
);
}
onResponseData(controller, chunk) {
if (this.#successful) {
return;
}
return this.#handler.onResponseData?.(controller, chunk);
}
onResponseEnd(controller, trailers) {
if (this.#successful) {
return;
}
this.#handler.onResponseEnd?.(controller, trailers);
}
onResponseError(controller, err) {
if (this.#successful) {
return;
}
if (this.#callback) {
this.#callback(false);
this.#callback = null;
}
if (typeof this.#handler.onResponseError === "function") {
this.#handler.onResponseError(controller, err);
} else {
throw err;
}
}
};
module3.exports = CacheRevalidationHandler;
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/cache.js
var require_cache2 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/interceptor/cache.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { Readable: Readable8 } = require("stream");
var util3 = require_util();
var CacheHandler = require_cache_handler();
var MemoryCacheStore = require_memory_cache_store();
var CacheRevalidationHandler = require_cache_revalidation_handler();
var { assertCacheStore, assertCacheMethods, makeCacheKey, normaliseHeaders: normaliseHeaders2, parseCacheControlHeader } = require_cache();
var { AbortError: AbortError2 } = require_errors();
function needsRevalidation(result, cacheControlDirectives) {
if (cacheControlDirectives?.["no-cache"]) {
return true;
}
if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) {
return true;
}
const now = Date.now();
if (now > result.staleAt) {
if (cacheControlDirectives?.["max-stale"]) {
const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
return now > gracePeriod;
}
return true;
}
if (cacheControlDirectives?.["min-fresh"]) {
const timeLeftTillStale = result.staleAt - now;
const threshold = cacheControlDirectives["min-fresh"] * 1e3;
return timeLeftTillStale <= threshold;
}
return false;
}
__name(needsRevalidation, "needsRevalidation");
function handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) {
if (reqCacheControl?.["only-if-cached"]) {
let aborted = false;
try {
if (typeof handler.onConnect === "function") {
handler.onConnect(() => {
aborted = true;
});
if (aborted) {
return;
}
}
if (typeof handler.onHeaders === "function") {
handler.onHeaders(504, [], () => {
}, "Gateway Timeout");
if (aborted) {
return;
}
}
if (typeof handler.onComplete === "function") {
handler.onComplete([]);
}
} catch (err) {
if (typeof handler.onError === "function") {
handler.onError(err);
}
}
return true;
}
return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
}
__name(handleUncachedResponse, "handleUncachedResponse");
function sendCachedValue(handler, opts, result, age, context2, isStale) {
const stream2 = util3.isStream(result.body) ? result.body : Readable8.from(result.body ?? []);
assert44(!stream2.destroyed, "stream should not be destroyed");
assert44(!stream2.readableDidRead, "stream should not be readableDidRead");
const controller = {
resume() {
stream2.resume();
},
pause() {
stream2.pause();
},
get paused() {
return stream2.isPaused();
},
get aborted() {
return stream2.destroyed;
},
get reason() {
return stream2.errored;
},
abort(reason) {
stream2.destroy(reason ?? new AbortError2());
}
};
stream2.on("error", function(err) {
if (!this.readableEnded) {
if (typeof handler.onResponseError === "function") {
handler.onResponseError(controller, err);
} else {
throw err;
}
}
}).on("close", function() {
if (!this.errored) {
handler.onResponseEnd?.(controller, {});
}
});
handler.onRequestStart?.(controller, context2);
if (stream2.destroyed) {
return;
}
const headers = { ...result.headers, age: String(age) };
if (isStale) {
headers.warning = '110 - "response is stale"';
}
handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage);
if (opts.method === "HEAD") {
stream2.destroy();
} else {
stream2.on("data", function(chunk) {
handler.onResponseData?.(controller, chunk);
});
}
}
__name(sendCachedValue, "sendCachedValue");
function handleResult2(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result) {
if (!result) {
return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
}
const now = Date.now();
if (now > result.deleteAt) {
return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
}
const age = Math.round((now - result.cachedAt) / 1e3);
if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
return dispatch(opts, handler);
}
if (needsRevalidation(result, reqCacheControl)) {
if (util3.isStream(opts.body) && util3.bodyLength(opts.body) !== 0) {
return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
}
let withinStaleIfErrorThreshold = false;
const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
if (staleIfErrorExpiry) {
withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
}
let headers = {
...opts.headers,
"if-modified-since": new Date(result.cachedAt).toUTCString()
};
if (result.etag) {
headers["if-none-match"] = result.etag;
}
if (result.vary) {
headers = {
...headers,
...result.vary
};
}
return dispatch(
{
...opts,
headers
},
new CacheRevalidationHandler(
(success2, context2) => {
if (success2) {
sendCachedValue(handler, opts, result, age, context2, true);
} else if (util3.isStream(result.body)) {
result.body.on("error", () => {
}).destroy();
}
},
new CacheHandler(globalOpts, cacheKey, handler),
withinStaleIfErrorThreshold
)
);
}
if (util3.isStream(opts.body)) {
opts.body.on("error", () => {
}).destroy();
}
sendCachedValue(handler, opts, result, age, null, false);
}
__name(handleResult2, "handleResult");
module3.exports = (opts = {}) => {
const {
store = new MemoryCacheStore(),
methods = ["GET"],
cacheByDefault = void 0,
type = "shared"
} = opts;
if (typeof opts !== "object" || opts === null) {
throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
}
assertCacheStore(store, "opts.store");
assertCacheMethods(methods, "opts.methods");
if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
throw new TypeError(`exepcted opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
}
if (typeof type !== "undefined" && type !== "shared" && type !== "private") {
throw new TypeError(`exepcted opts.type to be shared, private, or undefined, got ${typeof type}`);
}
const globalOpts = {
store,
methods,
cacheByDefault,
type
};
const safeMethodsToNotCache = util3.safeHTTPMethods.filter((method) => methods.includes(method) === false);
return (dispatch) => {
return (opts2, handler) => {
if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
return dispatch(opts2, handler);
}
opts2 = {
...opts2,
headers: normaliseHeaders2(opts2)
};
const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
if (reqCacheControl?.["no-store"]) {
return dispatch(opts2, handler);
}
const cacheKey = makeCacheKey(opts2);
const result = store.get(cacheKey);
if (result && typeof result.then === "function") {
result.then((result2) => {
handleResult2(
dispatch,
globalOpts,
cacheKey,
handler,
opts2,
reqCacheControl,
result2
);
});
} else {
handleResult2(
dispatch,
globalOpts,
cacheKey,
handler,
opts2,
reqCacheControl,
result
);
}
return true;
};
};
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/cache/sqlite-cache-store.js
var require_sqlite_cache_store = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/cache/sqlite-cache-store.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Writable: Writable5 } = require("stream");
var { assertCacheKey, assertCacheValue } = require_cache();
var DatabaseSync;
var VERSION = 3;
var MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3;
module3.exports = class SqliteCacheStore {
static {
__name(this, "SqliteCacheStore");
}
#maxEntrySize = MAX_ENTRY_SIZE;
#maxCount = Infinity;
/**
* @type {import('node:sqlite').DatabaseSync}
*/
#db;
/**
* @type {import('node:sqlite').StatementSync}
*/
#getValuesQuery;
/**
* @type {import('node:sqlite').StatementSync}
*/
#updateValueQuery;
/**
* @type {import('node:sqlite').StatementSync}
*/
#insertValueQuery;
/**
* @type {import('node:sqlite').StatementSync}
*/
#deleteExpiredValuesQuery;
/**
* @type {import('node:sqlite').StatementSync}
*/
#deleteByUrlQuery;
/**
* @type {import('node:sqlite').StatementSync}
*/
#countEntriesQuery;
/**
* @type {import('node:sqlite').StatementSync | null}
*/
#deleteOldValuesQuery;
/**
* @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts
*/
constructor(opts) {
if (opts) {
if (typeof opts !== "object") {
throw new TypeError("SqliteCacheStore options must be an object");
}
if (opts.maxEntrySize !== void 0) {
if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer");
}
if (opts.maxEntrySize > MAX_ENTRY_SIZE) {
throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb");
}
this.#maxEntrySize = opts.maxEntrySize;
}
if (opts.maxCount !== void 0) {
if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");
}
this.#maxCount = opts.maxCount;
}
}
if (!DatabaseSync) {
DatabaseSync = require("sqlite").DatabaseSync;
}
this.#db = new DatabaseSync(opts?.location ?? ":memory:");
this.#db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA temp_store = memory;
PRAGMA optimize;
CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} (
-- Data specific to us
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
method TEXT NOT NULL,
-- Data returned to the interceptor
body BUF NULL,
deleteAt INTEGER NOT NULL,
statusCode INTEGER NOT NULL,
statusMessage TEXT NOT NULL,
headers TEXT NULL,
cacheControlDirectives TEXT NULL,
etag TEXT NULL,
vary TEXT NULL,
cachedAt INTEGER NOT NULL,
staleAt INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt);
CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt);
`);
this.#getValuesQuery = this.#db.prepare(`
SELECT
id,
body,
deleteAt,
statusCode,
statusMessage,
headers,
etag,
cacheControlDirectives,
vary,
cachedAt,
staleAt
FROM cacheInterceptorV${VERSION}
WHERE
url = ?
AND method = ?
ORDER BY
deleteAt ASC
`);
this.#updateValueQuery = this.#db.prepare(`
UPDATE cacheInterceptorV${VERSION} SET
body = ?,
deleteAt = ?,
statusCode = ?,
statusMessage = ?,
headers = ?,
etag = ?,
cacheControlDirectives = ?,
cachedAt = ?,
staleAt = ?
WHERE
id = ?
`);
this.#insertValueQuery = this.#db.prepare(`
INSERT INTO cacheInterceptorV${VERSION} (
url,
method,
body,
deleteAt,
statusCode,
statusMessage,
headers,
etag,
cacheControlDirectives,
vary,
cachedAt,
staleAt
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
this.#deleteByUrlQuery = this.#db.prepare(
`DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?`
);
this.#countEntriesQuery = this.#db.prepare(
`SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}`
);
this.#deleteExpiredValuesQuery = this.#db.prepare(
`DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?`
);
this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(`
DELETE FROM cacheInterceptorV${VERSION}
WHERE id IN (
SELECT
id
FROM cacheInterceptorV${VERSION}
ORDER BY cachedAt DESC
LIMIT ?
)
`);
}
close() {
this.#db.close();
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
* @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined}
*/
get(key) {
assertCacheKey(key);
const value = this.#findValue(key);
return value ? {
body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : void 0,
statusCode: value.statusCode,
statusMessage: value.statusMessage,
headers: value.headers ? JSON.parse(value.headers) : void 0,
etag: value.etag ? value.etag : void 0,
vary: value.vary ? JSON.parse(value.vary) : void 0,
cacheControlDirectives: value.cacheControlDirectives ? JSON.parse(value.cacheControlDirectives) : void 0,
cachedAt: value.cachedAt,
staleAt: value.staleAt,
deleteAt: value.deleteAt
} : void 0;
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array<Buffer>}} value
*/
set(key, value) {
assertCacheKey(key);
const url4 = this.#makeValueUrl(key);
const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body;
const size = body?.byteLength;
if (size && size > this.#maxEntrySize) {
return;
}
const existingValue = this.#findValue(key, true);
if (existingValue) {
this.#updateValueQuery.run(
body,
value.deleteAt,
value.statusCode,
value.statusMessage,
value.headers ? JSON.stringify(value.headers) : null,
value.etag ? value.etag : null,
value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
value.cachedAt,
value.staleAt,
existingValue.id
);
} else {
this.#prune();
this.#insertValueQuery.run(
url4,
key.method,
body,
value.deleteAt,
value.statusCode,
value.statusMessage,
value.headers ? JSON.stringify(value.headers) : null,
value.etag ? value.etag : null,
value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
value.vary ? JSON.stringify(value.vary) : null,
value.cachedAt,
value.staleAt
);
}
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value
* @returns {Writable | undefined}
*/
createWriteStream(key, value) {
assertCacheKey(key);
assertCacheValue(value);
let size = 0;
const body = [];
const store = this;
return new Writable5({
decodeStrings: true,
write(chunk, encoding, callback) {
size += chunk.byteLength;
if (size < store.#maxEntrySize) {
body.push(chunk);
} else {
this.destroy();
}
callback();
},
final(callback) {
store.set(key, { ...value, body });
callback();
}
});
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
*/
delete(key) {
if (typeof key !== "object") {
throw new TypeError(`expected key to be object, got ${typeof key}`);
}
this.#deleteByUrlQuery.run(this.#makeValueUrl(key));
}
#prune() {
if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) {
return 0;
}
{
const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes;
if (removed) {
return removed;
}
}
{
const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes;
if (removed) {
return removed;
}
}
return 0;
}
/**
* Counts the number of rows in the cache
* @returns {Number}
*/
get size() {
const { total } = this.#countEntriesQuery.get();
return total;
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
* @returns {string}
*/
#makeValueUrl(key) {
return `${key.origin}/${key.path}`;
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
* @param {boolean} [canBeExpired=false]
* @returns {SqliteStoreValue | undefined}
*/
#findValue(key, canBeExpired = false) {
const url4 = this.#makeValueUrl(key);
const { headers, method } = key;
const values = this.#getValuesQuery.all(url4, method);
if (values.length === 0) {
return void 0;
}
const now = Date.now();
for (const value of values) {
if (now >= value.deleteAt && !canBeExpired) {
return void 0;
}
let matches = true;
if (value.vary) {
const vary = JSON.parse(value.vary);
for (const header in vary) {
if (!headerValueEquals(headers[header], vary[header])) {
matches = false;
break;
}
}
}
if (matches) {
return value;
}
}
return void 0;
}
};
function headerValueEquals(lhs, rhs) {
if (lhs == null && rhs == null) {
return true;
}
if (lhs == null && rhs != null || lhs != null && rhs == null) {
return false;
}
if (Array.isArray(lhs) && Array.isArray(rhs)) {
if (lhs.length !== rhs.length) {
return false;
}
return lhs.every((x6, i5) => x6 === rhs[i5]);
}
return lhs === rhs;
}
__name(headerValueEquals, "headerValueEquals");
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/headers.js
var require_headers = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/headers.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { kConstruct } = require_symbols();
var { kEnumerableProperty } = require_util();
var {
iteratorMixin,
isValidHeaderName,
isValidHeaderValue
} = require_util2();
var { webidl } = require_webidl();
var assert44 = require("assert");
var util3 = require("util");
function isHTTPWhiteSpaceCharCode(code) {
return code === 10 || code === 13 || code === 9 || code === 32;
}
__name(isHTTPWhiteSpaceCharCode, "isHTTPWhiteSpaceCharCode");
function headerValueNormalize(potentialValue) {
let i5 = 0;
let j6 = potentialValue.length;
while (j6 > i5 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j6 - 1))) --j6;
while (j6 > i5 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i5))) ++i5;
return i5 === 0 && j6 === potentialValue.length ? potentialValue : potentialValue.substring(i5, j6);
}
__name(headerValueNormalize, "headerValueNormalize");
function fill2(headers, object) {
if (Array.isArray(object)) {
for (let i5 = 0; i5 < object.length; ++i5) {
const header = object[i5];
if (header.length !== 2) {
throw webidl.errors.exception({
header: "Headers constructor",
message: `expected name/value pair to be length 2, found ${header.length}.`
});
}
appendHeader(headers, header[0], header[1]);
}
} else if (typeof object === "object" && object !== null) {
const keys = Object.keys(object);
for (let i5 = 0; i5 < keys.length; ++i5) {
appendHeader(headers, keys[i5], object[keys[i5]]);
}
} else {
throw webidl.errors.conversionFailed({
prefix: "Headers constructor",
argument: "Argument 1",
types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
});
}
}
__name(fill2, "fill");
function appendHeader(headers, name2, value) {
value = headerValueNormalize(value);
if (!isValidHeaderName(name2)) {
throw webidl.errors.invalidArgument({
prefix: "Headers.append",
value: name2,
type: "header name"
});
} else if (!isValidHeaderValue(value)) {
throw webidl.errors.invalidArgument({
prefix: "Headers.append",
value,
type: "header value"
});
}
if (getHeadersGuard(headers) === "immutable") {
throw new TypeError("immutable");
}
return getHeadersList(headers).append(name2, value, false);
}
__name(appendHeader, "appendHeader");
function headersListSortAndCombine(target) {
const headersList = getHeadersList(target);
if (!headersList) {
return [];
}
if (headersList.sortedMap) {
return headersList.sortedMap;
}
const headers = [];
const names = headersList.toSortedArray();
const cookies = headersList.cookies;
if (cookies === null || cookies.length === 1) {
return headersList.sortedMap = names;
}
for (let i5 = 0; i5 < names.length; ++i5) {
const { 0: name2, 1: value } = names[i5];
if (name2 === "set-cookie") {
for (let j6 = 0; j6 < cookies.length; ++j6) {
headers.push([name2, cookies[j6]]);
}
} else {
headers.push([name2, value]);
}
}
return headersList.sortedMap = headers;
}
__name(headersListSortAndCombine, "headersListSortAndCombine");
function compareHeaderName(a5, b6) {
return a5[0] < b6[0] ? -1 : 1;
}
__name(compareHeaderName, "compareHeaderName");
var HeadersList = class _HeadersList {
static {
__name(this, "HeadersList");
}
/** @type {[string, string][]|null} */
cookies = null;
sortedMap;
headersMap;
constructor(init3) {
if (init3 instanceof _HeadersList) {
this.headersMap = new Map(init3.headersMap);
this.sortedMap = init3.sortedMap;
this.cookies = init3.cookies === null ? null : [...init3.cookies];
} else {
this.headersMap = new Map(init3);
this.sortedMap = null;
}
}
/**
* @see https://fetch.spec.whatwg.org/#header-list-contains
* @param {string} name
* @param {boolean} isLowerCase
*/
contains(name2, isLowerCase) {
return this.headersMap.has(isLowerCase ? name2 : name2.toLowerCase());
}
clear() {
this.headersMap.clear();
this.sortedMap = null;
this.cookies = null;
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-append
* @param {string} name
* @param {string} value
* @param {boolean} isLowerCase
*/
append(name2, value, isLowerCase) {
this.sortedMap = null;
const lowercaseName = isLowerCase ? name2 : name2.toLowerCase();
const exists = this.headersMap.get(lowercaseName);
if (exists) {
const delimiter = lowercaseName === "cookie" ? "; " : ", ";
this.headersMap.set(lowercaseName, {
name: exists.name,
value: `${exists.value}${delimiter}${value}`
});
} else {
this.headersMap.set(lowercaseName, { name: name2, value });
}
if (lowercaseName === "set-cookie") {
(this.cookies ??= []).push(value);
}
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-set
* @param {string} name
* @param {string} value
* @param {boolean} isLowerCase
*/
set(name2, value, isLowerCase) {
this.sortedMap = null;
const lowercaseName = isLowerCase ? name2 : name2.toLowerCase();
if (lowercaseName === "set-cookie") {
this.cookies = [value];
}
this.headersMap.set(lowercaseName, { name: name2, value });
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-delete
* @param {string} name
* @param {boolean} isLowerCase
*/
delete(name2, isLowerCase) {
this.sortedMap = null;
if (!isLowerCase) name2 = name2.toLowerCase();
if (name2 === "set-cookie") {
this.cookies = null;
}
this.headersMap.delete(name2);
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-get
* @param {string} name
* @param {boolean} isLowerCase
* @returns {string | null}
*/
get(name2, isLowerCase) {
return this.headersMap.get(isLowerCase ? name2 : name2.toLowerCase())?.value ?? null;
}
*[Symbol.iterator]() {
for (const { 0: name2, 1: { value } } of this.headersMap) {
yield [name2, value];
}
}
get entries() {
const headers = {};
if (this.headersMap.size !== 0) {
for (const { name: name2, value } of this.headersMap.values()) {
headers[name2] = value;
}
}
return headers;
}
rawValues() {
return this.headersMap.values();
}
get entriesList() {
const headers = [];
if (this.headersMap.size !== 0) {
for (const { 0: lowerName, 1: { name: name2, value } } of this.headersMap) {
if (lowerName === "set-cookie") {
for (const cookie of this.cookies) {
headers.push([name2, cookie]);
}
} else {
headers.push([name2, value]);
}
}
}
return headers;
}
// https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
toSortedArray() {
const size = this.headersMap.size;
const array = new Array(size);
if (size <= 32) {
if (size === 0) {
return array;
}
const iterator = this.headersMap[Symbol.iterator]();
const firstValue = iterator.next().value;
array[0] = [firstValue[0], firstValue[1].value];
assert44(firstValue[1].value !== null);
for (let i5 = 1, j6 = 0, right2 = 0, left2 = 0, pivot = 0, x6, value; i5 < size; ++i5) {
value = iterator.next().value;
x6 = array[i5] = [value[0], value[1].value];
assert44(x6[1] !== null);
left2 = 0;
right2 = i5;
while (left2 < right2) {
pivot = left2 + (right2 - left2 >> 1);
if (array[pivot][0] <= x6[0]) {
left2 = pivot + 1;
} else {
right2 = pivot;
}
}
if (i5 !== pivot) {
j6 = i5;
while (j6 > left2) {
array[j6] = array[--j6];
}
array[left2] = x6;
}
}
if (!iterator.next().done) {
throw new TypeError("Unreachable");
}
return array;
} else {
let i5 = 0;
for (const { 0: name2, 1: { value } } of this.headersMap) {
array[i5++] = [name2, value];
assert44(value !== null);
}
return array.sort(compareHeaderName);
}
}
};
var Headers5 = class _Headers {
static {
__name(this, "Headers");
}
#guard;
/**
* @type {HeadersList}
*/
#headersList;
/**
* @param {HeadersInit|Symbol} [init]
* @returns
*/
constructor(init3 = void 0) {
webidl.util.markAsUncloneable(this);
if (init3 === kConstruct) {
return;
}
this.#headersList = new HeadersList();
this.#guard = "none";
if (init3 !== void 0) {
init3 = webidl.converters.HeadersInit(init3, "Headers constructor", "init");
fill2(this, init3);
}
}
// https://fetch.spec.whatwg.org/#dom-headers-append
append(name2, value) {
webidl.brandCheck(this, _Headers);
webidl.argumentLengthCheck(arguments, 2, "Headers.append");
const prefix = "Headers.append";
name2 = webidl.converters.ByteString(name2, prefix, "name");
value = webidl.converters.ByteString(value, prefix, "value");
return appendHeader(this, name2, value);
}
// https://fetch.spec.whatwg.org/#dom-headers-delete
delete(name2) {
webidl.brandCheck(this, _Headers);
webidl.argumentLengthCheck(arguments, 1, "Headers.delete");
const prefix = "Headers.delete";
name2 = webidl.converters.ByteString(name2, prefix, "name");
if (!isValidHeaderName(name2)) {
throw webidl.errors.invalidArgument({
prefix: "Headers.delete",
value: name2,
type: "header name"
});
}
if (this.#guard === "immutable") {
throw new TypeError("immutable");
}
if (!this.#headersList.contains(name2, false)) {
return;
}
this.#headersList.delete(name2, false);
}
// https://fetch.spec.whatwg.org/#dom-headers-get
get(name2) {
webidl.brandCheck(this, _Headers);
webidl.argumentLengthCheck(arguments, 1, "Headers.get");
const prefix = "Headers.get";
name2 = webidl.converters.ByteString(name2, prefix, "name");
if (!isValidHeaderName(name2)) {
throw webidl.errors.invalidArgument({
prefix,
value: name2,
type: "header name"
});
}
return this.#headersList.get(name2, false);
}
// https://fetch.spec.whatwg.org/#dom-headers-has
has(name2) {
webidl.brandCheck(this, _Headers);
webidl.argumentLengthCheck(arguments, 1, "Headers.has");
const prefix = "Headers.has";
name2 = webidl.converters.ByteString(name2, prefix, "name");
if (!isValidHeaderName(name2)) {
throw webidl.errors.invalidArgument({
prefix,
value: name2,
type: "header name"
});
}
return this.#headersList.contains(name2, false);
}
// https://fetch.spec.whatwg.org/#dom-headers-set
set(name2, value) {
webidl.brandCheck(this, _Headers);
webidl.argumentLengthCheck(arguments, 2, "Headers.set");
const prefix = "Headers.set";
name2 = webidl.converters.ByteString(name2, prefix, "name");
value = webidl.converters.ByteString(value, prefix, "value");
value = headerValueNormalize(value);
if (!isValidHeaderName(name2)) {
throw webidl.errors.invalidArgument({
prefix,
value: name2,
type: "header name"
});
} else if (!isValidHeaderValue(value)) {
throw webidl.errors.invalidArgument({
prefix,
value,
type: "header value"
});
}
if (this.#guard === "immutable") {
throw new TypeError("immutable");
}
this.#headersList.set(name2, value, false);
}
// https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
getSetCookie() {
webidl.brandCheck(this, _Headers);
const list = this.#headersList.cookies;
if (list) {
return [...list];
}
return [];
}
[util3.inspect.custom](depth, options) {
options.depth ??= depth;
return `Headers ${util3.formatWithOptions(options, this.#headersList.entries)}`;
}
static getHeadersGuard(o5) {
return o5.#guard;
}
static setHeadersGuard(o5, guard) {
o5.#guard = guard;
}
/**
* @param {Headers} o
*/
static getHeadersList(o5) {
return o5.#headersList;
}
/**
* @param {Headers} target
* @param {HeadersList} list
*/
static setHeadersList(target, list) {
target.#headersList = list;
}
};
var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers5;
Reflect.deleteProperty(Headers5, "getHeadersGuard");
Reflect.deleteProperty(Headers5, "setHeadersGuard");
Reflect.deleteProperty(Headers5, "getHeadersList");
Reflect.deleteProperty(Headers5, "setHeadersList");
iteratorMixin("Headers", Headers5, headersListSortAndCombine, 0, 1);
Object.defineProperties(Headers5.prototype, {
append: kEnumerableProperty,
delete: kEnumerableProperty,
get: kEnumerableProperty,
has: kEnumerableProperty,
set: kEnumerableProperty,
getSetCookie: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "Headers",
configurable: true
},
[util3.inspect.custom]: {
enumerable: false
}
});
webidl.converters.HeadersInit = function(V3, prefix, argument) {
if (webidl.util.Type(V3) === webidl.util.Types.OBJECT) {
const iterator = Reflect.get(V3, Symbol.iterator);
if (!util3.types.isProxy(V3) && iterator === Headers5.prototype.entries) {
try {
return getHeadersList(V3).entriesList;
} catch {
}
}
if (typeof iterator === "function") {
return webidl.converters["sequence<sequence<ByteString>>"](V3, prefix, argument, iterator.bind(V3));
}
return webidl.converters["record<ByteString, ByteString>"](V3, prefix, argument);
}
throw webidl.errors.conversionFailed({
prefix: "Headers constructor",
argument: "Argument 1",
types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
});
};
module3.exports = {
fill: fill2,
// for test.
compareHeaderName,
Headers: Headers5,
HeadersList,
getHeadersGuard,
setHeadersGuard,
setHeadersList,
getHeadersList
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/response.js
var require_response = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/response.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Headers: Headers5, HeadersList, fill: fill2, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers();
var { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require_body();
var util3 = require_util();
var nodeUtil = require("util");
var { kEnumerableProperty } = util3;
var {
isValidReasonPhrase,
isCancelled,
isAborted: isAborted2,
serializeJavascriptValueToJSONString,
isErrorLike,
isomorphicEncode,
environmentSettingsObject: relevantRealm
} = require_util2();
var {
redirectStatusSet,
nullBodyStatus
} = require_constants3();
var { webidl } = require_webidl();
var { URLSerializer } = require_data_url();
var { kConstruct } = require_symbols();
var assert44 = require("assert");
var { types: types3 } = require("util");
var textEncoder = new TextEncoder("utf-8");
var Response12 = class _Response {
static {
__name(this, "Response");
}
/** @type {Headers} */
#headers;
#state;
// Creates network error Response.
static error() {
const responseObject = fromInnerResponse(makeNetworkError(), "immutable");
return responseObject;
}
// https://fetch.spec.whatwg.org/#dom-response-json
static json(data, init3 = void 0) {
webidl.argumentLengthCheck(arguments, 1, "Response.json");
if (init3 !== null) {
init3 = webidl.converters.ResponseInit(init3);
}
const bytes = textEncoder.encode(
serializeJavascriptValueToJSONString(data)
);
const body = extractBody(bytes);
const responseObject = fromInnerResponse(makeResponse({}), "response");
initializeResponse(responseObject, init3, { body: body[0], type: "application/json" });
return responseObject;
}
// Creates a redirect Response that redirects to url with status status.
static redirect(url4, status2 = 302) {
webidl.argumentLengthCheck(arguments, 1, "Response.redirect");
url4 = webidl.converters.USVString(url4);
status2 = webidl.converters["unsigned short"](status2);
let parsedURL;
try {
parsedURL = new URL(url4, relevantRealm.settingsObject.baseUrl);
} catch (err) {
throw new TypeError(`Failed to parse URL from ${url4}`, { cause: err });
}
if (!redirectStatusSet.has(status2)) {
throw new RangeError(`Invalid status code ${status2}`);
}
const responseObject = fromInnerResponse(makeResponse({}), "immutable");
responseObject.#state.status = status2;
const value = isomorphicEncode(URLSerializer(parsedURL));
responseObject.#state.headersList.append("location", value, true);
return responseObject;
}
// https://fetch.spec.whatwg.org/#dom-response
constructor(body = null, init3 = void 0) {
webidl.util.markAsUncloneable(this);
if (body === kConstruct) {
return;
}
if (body !== null) {
body = webidl.converters.BodyInit(body);
}
init3 = webidl.converters.ResponseInit(init3);
this.#state = makeResponse({});
this.#headers = new Headers5(kConstruct);
setHeadersGuard(this.#headers, "response");
setHeadersList(this.#headers, this.#state.headersList);
let bodyWithType = null;
if (body != null) {
const [extractedBody, type] = extractBody(body);
bodyWithType = { body: extractedBody, type };
}
initializeResponse(this, init3, bodyWithType);
}
// Returns response’s type, e.g., "cors".
get type() {
webidl.brandCheck(this, _Response);
return this.#state.type;
}
// Returns response’s URL, if it has one; otherwise the empty string.
get url() {
webidl.brandCheck(this, _Response);
const urlList = this.#state.urlList;
const url4 = urlList[urlList.length - 1] ?? null;
if (url4 === null) {
return "";
}
return URLSerializer(url4, true);
}
// Returns whether response was obtained through a redirect.
get redirected() {
webidl.brandCheck(this, _Response);
return this.#state.urlList.length > 1;
}
// Returns response’s status.
get status() {
webidl.brandCheck(this, _Response);
return this.#state.status;
}
// Returns whether response’s status is an ok status.
get ok() {
webidl.brandCheck(this, _Response);
return this.#state.status >= 200 && this.#state.status <= 299;
}
// Returns response’s status message.
get statusText() {
webidl.brandCheck(this, _Response);
return this.#state.statusText;
}
// Returns response’s headers as Headers.
get headers() {
webidl.brandCheck(this, _Response);
return this.#headers;
}
get body() {
webidl.brandCheck(this, _Response);
return this.#state.body ? this.#state.body.stream : null;
}
get bodyUsed() {
webidl.brandCheck(this, _Response);
return !!this.#state.body && util3.isDisturbed(this.#state.body.stream);
}
// Returns a clone of response.
clone() {
webidl.brandCheck(this, _Response);
if (bodyUnusable(this.#state)) {
throw webidl.errors.exception({
header: "Response.clone",
message: "Body has already been consumed."
});
}
const clonedResponse = cloneResponse(this.#state);
return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers));
}
[nodeUtil.inspect.custom](depth, options) {
if (options.depth === null) {
options.depth = 2;
}
options.colors ??= true;
const properties = {
status: this.status,
statusText: this.statusText,
headers: this.headers,
body: this.body,
bodyUsed: this.bodyUsed,
ok: this.ok,
redirected: this.redirected,
type: this.type,
url: this.url
};
return `Response ${nodeUtil.formatWithOptions(options, properties)}`;
}
/**
* @param {Response} response
*/
static getResponseHeaders(response) {
return response.#headers;
}
/**
* @param {Response} response
* @param {Headers} newHeaders
*/
static setResponseHeaders(response, newHeaders) {
response.#headers = newHeaders;
}
/**
* @param {Response} response
*/
static getResponseState(response) {
return response.#state;
}
/**
* @param {Response} response
* @param {any} newState
*/
static setResponseState(response, newState) {
response.#state = newState;
}
};
var { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response12;
Reflect.deleteProperty(Response12, "getResponseHeaders");
Reflect.deleteProperty(Response12, "setResponseHeaders");
Reflect.deleteProperty(Response12, "getResponseState");
Reflect.deleteProperty(Response12, "setResponseState");
mixinBody(Response12, getResponseState);
Object.defineProperties(Response12.prototype, {
type: kEnumerableProperty,
url: kEnumerableProperty,
status: kEnumerableProperty,
ok: kEnumerableProperty,
redirected: kEnumerableProperty,
statusText: kEnumerableProperty,
headers: kEnumerableProperty,
clone: kEnumerableProperty,
body: kEnumerableProperty,
bodyUsed: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "Response",
configurable: true
}
});
Object.defineProperties(Response12, {
json: kEnumerableProperty,
redirect: kEnumerableProperty,
error: kEnumerableProperty
});
function cloneResponse(response) {
if (response.internalResponse) {
return filterResponse(
cloneResponse(response.internalResponse),
response.type
);
}
const newResponse = makeResponse({ ...response, body: null });
if (response.body != null) {
newResponse.body = cloneBody(newResponse, response.body);
}
return newResponse;
}
__name(cloneResponse, "cloneResponse");
function makeResponse(init3) {
return {
aborted: false,
rangeRequested: false,
timingAllowPassed: false,
requestIncludesCredentials: false,
type: "default",
status: 200,
timingInfo: null,
cacheState: "",
statusText: "",
...init3,
headersList: init3?.headersList ? new HeadersList(init3?.headersList) : new HeadersList(),
urlList: init3?.urlList ? [...init3.urlList] : []
};
}
__name(makeResponse, "makeResponse");
function makeNetworkError(reason) {
const isError2 = isErrorLike(reason);
return makeResponse({
type: "error",
status: 0,
error: isError2 ? reason : new Error(reason ? String(reason) : reason),
aborted: reason && reason.name === "AbortError"
});
}
__name(makeNetworkError, "makeNetworkError");
function isNetworkError(response) {
return (
// A network error is a response whose type is "error",
response.type === "error" && // status is 0
response.status === 0
);
}
__name(isNetworkError, "isNetworkError");
function makeFilteredResponse(response, state2) {
state2 = {
internalResponse: response,
...state2
};
return new Proxy(response, {
get(target, p6) {
return p6 in state2 ? state2[p6] : target[p6];
},
set(target, p6, value) {
assert44(!(p6 in state2));
target[p6] = value;
return true;
}
});
}
__name(makeFilteredResponse, "makeFilteredResponse");
function filterResponse(response, type) {
if (type === "basic") {
return makeFilteredResponse(response, {
type: "basic",
headersList: response.headersList
});
} else if (type === "cors") {
return makeFilteredResponse(response, {
type: "cors",
headersList: response.headersList
});
} else if (type === "opaque") {
return makeFilteredResponse(response, {
type: "opaque",
urlList: Object.freeze([]),
status: 0,
statusText: "",
body: null
});
} else if (type === "opaqueredirect") {
return makeFilteredResponse(response, {
type: "opaqueredirect",
status: 0,
statusText: "",
headersList: [],
body: null
});
} else {
assert44(false);
}
}
__name(filterResponse, "filterResponse");
function makeAppropriateNetworkError(fetchParams, err = null) {
assert44(isCancelled(fetchParams));
return isAborted2(fetchParams) ? makeNetworkError(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err })) : makeNetworkError(Object.assign(new DOMException("Request was cancelled."), { cause: err }));
}
__name(makeAppropriateNetworkError, "makeAppropriateNetworkError");
function initializeResponse(response, init3, body) {
if (init3.status !== null && (init3.status < 200 || init3.status > 599)) {
throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
}
if ("statusText" in init3 && init3.statusText != null) {
if (!isValidReasonPhrase(String(init3.statusText))) {
throw new TypeError("Invalid statusText");
}
}
if ("status" in init3 && init3.status != null) {
getResponseState(response).status = init3.status;
}
if ("statusText" in init3 && init3.statusText != null) {
getResponseState(response).statusText = init3.statusText;
}
if ("headers" in init3 && init3.headers != null) {
fill2(getResponseHeaders(response), init3.headers);
}
if (body) {
if (nullBodyStatus.includes(response.status)) {
throw webidl.errors.exception({
header: "Response constructor",
message: `Invalid response status code ${response.status}`
});
}
getResponseState(response).body = body.body;
if (body.type != null && !getResponseState(response).headersList.contains("content-type", true)) {
getResponseState(response).headersList.append("content-type", body.type, true);
}
}
}
__name(initializeResponse, "initializeResponse");
function fromInnerResponse(innerResponse, guard) {
const response = new Response12(kConstruct);
setResponseState(response, innerResponse);
const headers = new Headers5(kConstruct);
setResponseHeaders(response, headers);
setHeadersList(headers, innerResponse.headersList);
setHeadersGuard(headers, guard);
if (hasFinalizationRegistry && innerResponse.body?.stream) {
streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
}
return response;
}
__name(fromInnerResponse, "fromInnerResponse");
webidl.converters.XMLHttpRequestBodyInit = function(V3, prefix, name2) {
if (typeof V3 === "string") {
return webidl.converters.USVString(V3, prefix, name2);
}
if (webidl.is.Blob(V3)) {
return V3;
}
if (ArrayBuffer.isView(V3) || types3.isArrayBuffer(V3)) {
return V3;
}
if (webidl.is.FormData(V3)) {
return V3;
}
if (webidl.is.URLSearchParams(V3)) {
return V3;
}
return webidl.converters.DOMString(V3, prefix, name2);
};
webidl.converters.BodyInit = function(V3, prefix, argument) {
if (webidl.is.ReadableStream(V3)) {
return V3;
}
if (V3?.[Symbol.asyncIterator]) {
return V3;
}
return webidl.converters.XMLHttpRequestBodyInit(V3, prefix, argument);
};
webidl.converters.ResponseInit = webidl.dictionaryConverter([
{
key: "status",
converter: webidl.converters["unsigned short"],
defaultValue: /* @__PURE__ */ __name(() => 200, "defaultValue")
},
{
key: "statusText",
converter: webidl.converters.ByteString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
},
{
key: "headers",
converter: webidl.converters.HeadersInit
}
]);
webidl.is.Response = webidl.util.MakeTypeAssertion(Response12);
module3.exports = {
isNetworkError,
makeNetworkError,
makeResponse,
makeAppropriateNetworkError,
filterResponse,
Response: Response12,
cloneResponse,
fromInnerResponse,
getResponseState
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/dispatcher-weakref.js
var require_dispatcher_weakref = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/dispatcher-weakref.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = function() {
return { WeakRef, FinalizationRegistry };
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/request.js
var require_request2 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/request.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body();
var { Headers: Headers5, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers();
var { FinalizationRegistry: FinalizationRegistry2 } = require_dispatcher_weakref()();
var util3 = require_util();
var nodeUtil = require("util");
var {
isValidHTTPToken,
sameOrigin,
environmentSettingsObject
} = require_util2();
var {
forbiddenMethodsSet,
corsSafeListedMethodsSet,
referrerPolicy,
requestRedirect,
requestMode,
requestCredentials,
requestCache,
requestDuplex
} = require_constants3();
var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util3;
var { webidl } = require_webidl();
var { URLSerializer } = require_data_url();
var { kConstruct } = require_symbols();
var assert44 = require("assert");
var { getMaxListeners, setMaxListeners, defaultMaxListeners } = require("events");
var kAbortController = Symbol("abortController");
var requestFinalizer = new FinalizationRegistry2(({ signal, abort }) => {
signal.removeEventListener("abort", abort);
});
var dependentControllerMap = /* @__PURE__ */ new WeakMap();
var abortSignalHasEventHandlerLeakWarning;
try {
abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0;
} catch {
abortSignalHasEventHandlerLeakWarning = false;
}
function buildAbort(acRef) {
return abort;
function abort() {
const ac2 = acRef.deref();
if (ac2 !== void 0) {
requestFinalizer.unregister(abort);
this.removeEventListener("abort", abort);
ac2.abort(this.reason);
const controllerList = dependentControllerMap.get(ac2.signal);
if (controllerList !== void 0) {
if (controllerList.size !== 0) {
for (const ref of controllerList) {
const ctrl = ref.deref();
if (ctrl !== void 0) {
ctrl.abort(this.reason);
}
}
controllerList.clear();
}
dependentControllerMap.delete(ac2.signal);
}
}
}
__name(abort, "abort");
}
__name(buildAbort, "buildAbort");
var patchMethodWarning = false;
var Request4 = class _Request {
static {
__name(this, "Request");
}
/** @type {AbortSignal} */
#signal;
/** @type {import('../../dispatcher/dispatcher')} */
#dispatcher;
/** @type {Headers} */
#headers;
#state;
// https://fetch.spec.whatwg.org/#dom-request
constructor(input, init3 = void 0) {
webidl.util.markAsUncloneable(this);
if (input === kConstruct) {
return;
}
const prefix = "Request constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
input = webidl.converters.RequestInfo(input, prefix, "input");
init3 = webidl.converters.RequestInit(init3, prefix, "init");
let request4 = null;
let fallbackMode = null;
const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
let signal = null;
if (typeof input === "string") {
this.#dispatcher = init3.dispatcher;
let parsedURL;
try {
parsedURL = new URL(input, baseUrl);
} catch (err) {
throw new TypeError("Failed to parse URL from " + input, { cause: err });
}
if (parsedURL.username || parsedURL.password) {
throw new TypeError(
"Request cannot be constructed from a URL that includes credentials: " + input
);
}
request4 = makeRequest({ urlList: [parsedURL] });
fallbackMode = "cors";
} else {
assert44(webidl.is.Request(input));
request4 = input.#state;
signal = input.#signal;
this.#dispatcher = init3.dispatcher || input.#dispatcher;
}
const origin = environmentSettingsObject.settingsObject.origin;
let window2 = "client";
if (request4.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request4.window, origin)) {
window2 = request4.window;
}
if (init3.window != null) {
throw new TypeError(`'window' option '${window2}' must be null`);
}
if ("window" in init3) {
window2 = "no-window";
}
request4 = makeRequest({
// URL request’s URL.
// undici implementation note: this is set as the first item in request's urlList in makeRequest
// method request’s method.
method: request4.method,
// header list A copy of request’s header list.
// undici implementation note: headersList is cloned in makeRequest
headersList: request4.headersList,
// unsafe-request flag Set.
unsafeRequest: request4.unsafeRequest,
// client This’s relevant settings object.
client: environmentSettingsObject.settingsObject,
// window window.
window: window2,
// priority request’s priority.
priority: request4.priority,
// origin request’s origin. The propagation of the origin is only significant for navigation requests
// being handled by a service worker. In this scenario a request can have an origin that is different
// from the current client.
origin: request4.origin,
// referrer request’s referrer.
referrer: request4.referrer,
// referrer policy request’s referrer policy.
referrerPolicy: request4.referrerPolicy,
// mode request’s mode.
mode: request4.mode,
// credentials mode request’s credentials mode.
credentials: request4.credentials,
// cache mode request’s cache mode.
cache: request4.cache,
// redirect mode request’s redirect mode.
redirect: request4.redirect,
// integrity metadata request’s integrity metadata.
integrity: request4.integrity,
// keepalive request’s keepalive.
keepalive: request4.keepalive,
// reload-navigation flag request’s reload-navigation flag.
reloadNavigation: request4.reloadNavigation,
// history-navigation flag request’s history-navigation flag.
historyNavigation: request4.historyNavigation,
// URL list A clone of request’s URL list.
urlList: [...request4.urlList]
});
const initHasKey = Object.keys(init3).length !== 0;
if (initHasKey) {
if (request4.mode === "navigate") {
request4.mode = "same-origin";
}
request4.reloadNavigation = false;
request4.historyNavigation = false;
request4.origin = "client";
request4.referrer = "client";
request4.referrerPolicy = "";
request4.url = request4.urlList[request4.urlList.length - 1];
request4.urlList = [request4.url];
}
if (init3.referrer !== void 0) {
const referrer = init3.referrer;
if (referrer === "") {
request4.referrer = "no-referrer";
} else {
let parsedReferrer;
try {
parsedReferrer = new URL(referrer, baseUrl);
} catch (err) {
throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err });
}
if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) {
request4.referrer = "client";
} else {
request4.referrer = parsedReferrer;
}
}
}
if (init3.referrerPolicy !== void 0) {
request4.referrerPolicy = init3.referrerPolicy;
}
let mode;
if (init3.mode !== void 0) {
mode = init3.mode;
} else {
mode = fallbackMode;
}
if (mode === "navigate") {
throw webidl.errors.exception({
header: "Request constructor",
message: "invalid request mode navigate."
});
}
if (mode != null) {
request4.mode = mode;
}
if (init3.credentials !== void 0) {
request4.credentials = init3.credentials;
}
if (init3.cache !== void 0) {
request4.cache = init3.cache;
}
if (request4.cache === "only-if-cached" && request4.mode !== "same-origin") {
throw new TypeError(
"'only-if-cached' can be set only with 'same-origin' mode"
);
}
if (init3.redirect !== void 0) {
request4.redirect = init3.redirect;
}
if (init3.integrity != null) {
request4.integrity = String(init3.integrity);
}
if (init3.keepalive !== void 0) {
request4.keepalive = Boolean(init3.keepalive);
}
if (init3.method !== void 0) {
let method = init3.method;
const mayBeNormalized = normalizedMethodRecords[method];
if (mayBeNormalized !== void 0) {
request4.method = mayBeNormalized;
} else {
if (!isValidHTTPToken(method)) {
throw new TypeError(`'${method}' is not a valid HTTP method.`);
}
const upperCase = method.toUpperCase();
if (forbiddenMethodsSet.has(upperCase)) {
throw new TypeError(`'${method}' HTTP method is unsupported.`);
}
method = normalizedMethodRecordsBase[upperCase] ?? method;
request4.method = method;
}
if (!patchMethodWarning && request4.method === "patch") {
process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.", {
code: "UNDICI-FETCH-patch"
});
patchMethodWarning = true;
}
}
if (init3.signal !== void 0) {
signal = init3.signal;
}
this.#state = request4;
const ac2 = new AbortController();
this.#signal = ac2.signal;
if (signal != null) {
if (signal.aborted) {
ac2.abort(signal.reason);
} else {
this[kAbortController] = ac2;
const acRef = new WeakRef(ac2);
const abort = buildAbort(acRef);
if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) {
setMaxListeners(1500, signal);
}
util3.addAbortListener(signal, abort);
requestFinalizer.register(ac2, { signal, abort }, abort);
}
}
this.#headers = new Headers5(kConstruct);
setHeadersList(this.#headers, request4.headersList);
setHeadersGuard(this.#headers, "request");
if (mode === "no-cors") {
if (!corsSafeListedMethodsSet.has(request4.method)) {
throw new TypeError(
`'${request4.method} is unsupported in no-cors mode.`
);
}
setHeadersGuard(this.#headers, "request-no-cors");
}
if (initHasKey) {
const headersList = getHeadersList(this.#headers);
const headers = init3.headers !== void 0 ? init3.headers : new HeadersList(headersList);
headersList.clear();
if (headers instanceof HeadersList) {
for (const { name: name2, value } of headers.rawValues()) {
headersList.append(name2, value, false);
}
headersList.cookies = headers.cookies;
} else {
fillHeaders(this.#headers, headers);
}
}
const inputBody = webidl.is.Request(input) ? input.#state.body : null;
if ((init3.body != null || inputBody != null) && (request4.method === "GET" || request4.method === "HEAD")) {
throw new TypeError("Request with GET/HEAD method cannot have body.");
}
let initBody = null;
if (init3.body != null) {
const [extractedBody, contentType] = extractBody(
init3.body,
request4.keepalive
);
initBody = extractedBody;
if (contentType && !getHeadersList(this.#headers).contains("content-type", true)) {
this.#headers.append("content-type", contentType, true);
}
}
const inputOrInitBody = initBody ?? inputBody;
if (inputOrInitBody != null && inputOrInitBody.source == null) {
if (initBody != null && init3.duplex == null) {
throw new TypeError("RequestInit: duplex option is required when sending a body.");
}
if (request4.mode !== "same-origin" && request4.mode !== "cors") {
throw new TypeError(
'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
);
}
request4.useCORSPreflightFlag = true;
}
let finalBody = inputOrInitBody;
if (initBody == null && inputBody != null) {
if (bodyUnusable(input.#state)) {
throw new TypeError(
"Cannot construct a Request with a Request object that has already been used."
);
}
const identityTransform = new TransformStream();
inputBody.stream.pipeThrough(identityTransform);
finalBody = {
source: inputBody.source,
length: inputBody.length,
stream: identityTransform.readable
};
}
this.#state.body = finalBody;
}
// Returns request’s HTTP method, which is "GET" by default.
get method() {
webidl.brandCheck(this, _Request);
return this.#state.method;
}
// Returns the URL of request as a string.
get url() {
webidl.brandCheck(this, _Request);
return URLSerializer(this.#state.url);
}
// Returns a Headers object consisting of the headers associated with request.
// Note that headers added in the network layer by the user agent will not
// be accounted for in this object, e.g., the "Host" header.
get headers() {
webidl.brandCheck(this, _Request);
return this.#headers;
}
// Returns the kind of resource requested by request, e.g., "document"
// or "script".
get destination() {
webidl.brandCheck(this, _Request);
return this.#state.destination;
}
// Returns the referrer of request. Its value can be a same-origin URL if
// explicitly set in init, the empty string to indicate no referrer, and
// "about:client" when defaulting to the global’s default. This is used
// during fetching to determine the value of the `Referer` header of the
// request being made.
get referrer() {
webidl.brandCheck(this, _Request);
if (this.#state.referrer === "no-referrer") {
return "";
}
if (this.#state.referrer === "client") {
return "about:client";
}
return this.#state.referrer.toString();
}
// Returns the referrer policy associated with request.
// This is used during fetching to compute the value of the request’s
// referrer.
get referrerPolicy() {
webidl.brandCheck(this, _Request);
return this.#state.referrerPolicy;
}
// Returns the mode associated with request, which is a string indicating
// whether the request will use CORS, or will be restricted to same-origin
// URLs.
get mode() {
webidl.brandCheck(this, _Request);
return this.#state.mode;
}
// Returns the credentials mode associated with request,
// which is a string indicating whether credentials will be sent with the
// request always, never, or only when sent to a same-origin URL.
get credentials() {
webidl.brandCheck(this, _Request);
return this.#state.credentials;
}
// Returns the cache mode associated with request,
// which is a string indicating how the request will
// interact with the browser’s cache when fetching.
get cache() {
webidl.brandCheck(this, _Request);
return this.#state.cache;
}
// Returns the redirect mode associated with request,
// which is a string indicating how redirects for the
// request will be handled during fetching. A request
// will follow redirects by default.
get redirect() {
webidl.brandCheck(this, _Request);
return this.#state.redirect;
}
// Returns request’s subresource integrity metadata, which is a
// cryptographic hash of the resource being fetched. Its value
// consists of multiple hashes separated by whitespace. [SRI]
get integrity() {
webidl.brandCheck(this, _Request);
return this.#state.integrity;
}
// Returns a boolean indicating whether or not request can outlive the
// global in which it was created.
get keepalive() {
webidl.brandCheck(this, _Request);
return this.#state.keepalive;
}
// Returns a boolean indicating whether or not request is for a reload
// navigation.
get isReloadNavigation() {
webidl.brandCheck(this, _Request);
return this.#state.reloadNavigation;
}
// Returns a boolean indicating whether or not request is for a history
// navigation (a.k.a. back-forward navigation).
get isHistoryNavigation() {
webidl.brandCheck(this, _Request);
return this.#state.historyNavigation;
}
// Returns the signal associated with request, which is an AbortSignal
// object indicating whether or not request has been aborted, and its
// abort event handler.
get signal() {
webidl.brandCheck(this, _Request);
return this.#signal;
}
get body() {
webidl.brandCheck(this, _Request);
return this.#state.body ? this.#state.body.stream : null;
}
get bodyUsed() {
webidl.brandCheck(this, _Request);
return !!this.#state.body && util3.isDisturbed(this.#state.body.stream);
}
get duplex() {
webidl.brandCheck(this, _Request);
return "half";
}
// Returns a clone of request.
clone() {
webidl.brandCheck(this, _Request);
if (bodyUnusable(this.#state)) {
throw new TypeError("unusable");
}
const clonedRequest = cloneRequest(this.#state);
const ac2 = new AbortController();
if (this.signal.aborted) {
ac2.abort(this.signal.reason);
} else {
let list = dependentControllerMap.get(this.signal);
if (list === void 0) {
list = /* @__PURE__ */ new Set();
dependentControllerMap.set(this.signal, list);
}
const acRef = new WeakRef(ac2);
list.add(acRef);
util3.addAbortListener(
ac2.signal,
buildAbort(acRef)
);
}
return fromInnerRequest(clonedRequest, this.#dispatcher, ac2.signal, getHeadersGuard(this.#headers));
}
[nodeUtil.inspect.custom](depth, options) {
if (options.depth === null) {
options.depth = 2;
}
options.colors ??= true;
const properties = {
method: this.method,
url: this.url,
headers: this.headers,
destination: this.destination,
referrer: this.referrer,
referrerPolicy: this.referrerPolicy,
mode: this.mode,
credentials: this.credentials,
cache: this.cache,
redirect: this.redirect,
integrity: this.integrity,
keepalive: this.keepalive,
isReloadNavigation: this.isReloadNavigation,
isHistoryNavigation: this.isHistoryNavigation,
signal: this.signal
};
return `Request ${nodeUtil.formatWithOptions(options, properties)}`;
}
/**
* @param {Request} request
* @param {AbortSignal} newSignal
*/
static setRequestSignal(request4, newSignal) {
request4.#signal = newSignal;
return request4;
}
/**
* @param {Request} request
*/
static getRequestDispatcher(request4) {
return request4.#dispatcher;
}
/**
* @param {Request} request
* @param {import('../../dispatcher/dispatcher')} newDispatcher
*/
static setRequestDispatcher(request4, newDispatcher) {
request4.#dispatcher = newDispatcher;
}
/**
* @param {Request} request
* @param {Headers} newHeaders
*/
static setRequestHeaders(request4, newHeaders) {
request4.#headers = newHeaders;
}
/**
* @param {Request} request
*/
static getRequestState(request4) {
return request4.#state;
}
/**
* @param {Request} request
* @param {any} newState
*/
static setRequestState(request4, newState) {
request4.#state = newState;
}
};
var { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request4;
Reflect.deleteProperty(Request4, "setRequestSignal");
Reflect.deleteProperty(Request4, "getRequestDispatcher");
Reflect.deleteProperty(Request4, "setRequestDispatcher");
Reflect.deleteProperty(Request4, "setRequestHeaders");
Reflect.deleteProperty(Request4, "getRequestState");
Reflect.deleteProperty(Request4, "setRequestState");
mixinBody(Request4, getRequestState);
function makeRequest(init3) {
return {
method: init3.method ?? "GET",
localURLsOnly: init3.localURLsOnly ?? false,
unsafeRequest: init3.unsafeRequest ?? false,
body: init3.body ?? null,
client: init3.client ?? null,
reservedClient: init3.reservedClient ?? null,
replacesClientId: init3.replacesClientId ?? "",
window: init3.window ?? "client",
keepalive: init3.keepalive ?? false,
serviceWorkers: init3.serviceWorkers ?? "all",
initiator: init3.initiator ?? "",
destination: init3.destination ?? "",
priority: init3.priority ?? null,
origin: init3.origin ?? "client",
policyContainer: init3.policyContainer ?? "client",
referrer: init3.referrer ?? "client",
referrerPolicy: init3.referrerPolicy ?? "",
mode: init3.mode ?? "no-cors",
useCORSPreflightFlag: init3.useCORSPreflightFlag ?? false,
credentials: init3.credentials ?? "same-origin",
useCredentials: init3.useCredentials ?? false,
cache: init3.cache ?? "default",
redirect: init3.redirect ?? "follow",
integrity: init3.integrity ?? "",
cryptoGraphicsNonceMetadata: init3.cryptoGraphicsNonceMetadata ?? "",
parserMetadata: init3.parserMetadata ?? "",
reloadNavigation: init3.reloadNavigation ?? false,
historyNavigation: init3.historyNavigation ?? false,
userActivation: init3.userActivation ?? false,
taintedOrigin: init3.taintedOrigin ?? false,
redirectCount: init3.redirectCount ?? 0,
responseTainting: init3.responseTainting ?? "basic",
preventNoCacheCacheControlHeaderModification: init3.preventNoCacheCacheControlHeaderModification ?? false,
done: init3.done ?? false,
timingAllowFailed: init3.timingAllowFailed ?? false,
urlList: init3.urlList,
url: init3.urlList[0],
headersList: init3.headersList ? new HeadersList(init3.headersList) : new HeadersList()
};
}
__name(makeRequest, "makeRequest");
function cloneRequest(request4) {
const newRequest = makeRequest({ ...request4, body: null });
if (request4.body != null) {
newRequest.body = cloneBody(newRequest, request4.body);
}
return newRequest;
}
__name(cloneRequest, "cloneRequest");
function fromInnerRequest(innerRequest, dispatcher, signal, guard) {
const request4 = new Request4(kConstruct);
setRequestState(request4, innerRequest);
setRequestDispatcher(request4, dispatcher);
setRequestSignal(request4, signal);
const headers = new Headers5(kConstruct);
setRequestHeaders(request4, headers);
setHeadersList(headers, innerRequest.headersList);
setHeadersGuard(headers, guard);
return request4;
}
__name(fromInnerRequest, "fromInnerRequest");
Object.defineProperties(Request4.prototype, {
method: kEnumerableProperty,
url: kEnumerableProperty,
headers: kEnumerableProperty,
redirect: kEnumerableProperty,
clone: kEnumerableProperty,
signal: kEnumerableProperty,
duplex: kEnumerableProperty,
destination: kEnumerableProperty,
body: kEnumerableProperty,
bodyUsed: kEnumerableProperty,
isHistoryNavigation: kEnumerableProperty,
isReloadNavigation: kEnumerableProperty,
keepalive: kEnumerableProperty,
integrity: kEnumerableProperty,
cache: kEnumerableProperty,
credentials: kEnumerableProperty,
attribute: kEnumerableProperty,
referrerPolicy: kEnumerableProperty,
referrer: kEnumerableProperty,
mode: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "Request",
configurable: true
}
});
webidl.is.Request = webidl.util.MakeTypeAssertion(Request4);
webidl.converters.RequestInfo = function(V3, prefix, argument) {
if (typeof V3 === "string") {
return webidl.converters.USVString(V3);
}
if (webidl.is.Request(V3)) {
return V3;
}
return webidl.converters.USVString(V3);
};
webidl.converters.RequestInit = webidl.dictionaryConverter([
{
key: "method",
converter: webidl.converters.ByteString
},
{
key: "headers",
converter: webidl.converters.HeadersInit
},
{
key: "body",
converter: webidl.nullableConverter(
webidl.converters.BodyInit
)
},
{
key: "referrer",
converter: webidl.converters.USVString
},
{
key: "referrerPolicy",
converter: webidl.converters.DOMString,
// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
allowedValues: referrerPolicy
},
{
key: "mode",
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#concept-request-mode
allowedValues: requestMode
},
{
key: "credentials",
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#requestcredentials
allowedValues: requestCredentials
},
{
key: "cache",
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#requestcache
allowedValues: requestCache
},
{
key: "redirect",
converter: webidl.converters.DOMString,
// https://fetch.spec.whatwg.org/#requestredirect
allowedValues: requestRedirect
},
{
key: "integrity",
converter: webidl.converters.DOMString
},
{
key: "keepalive",
converter: webidl.converters.boolean
},
{
key: "signal",
converter: webidl.nullableConverter(
(signal) => webidl.converters.AbortSignal(
signal,
"RequestInit",
"signal"
)
)
},
{
key: "window",
converter: webidl.converters.any
},
{
key: "duplex",
converter: webidl.converters.DOMString,
allowedValues: requestDuplex
},
{
key: "dispatcher",
// undici specific option
converter: webidl.converters.any
}
]);
module3.exports = {
Request: Request4,
makeRequest,
fromInnerRequest,
cloneRequest,
getRequestDispatcher,
getRequestState
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/index.js
var require_fetch = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/fetch/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var {
makeNetworkError,
makeAppropriateNetworkError,
filterResponse,
makeResponse,
fromInnerResponse,
getResponseState
} = require_response();
var { HeadersList } = require_headers();
var { Request: Request4, cloneRequest, getRequestDispatcher, getRequestState } = require_request2();
var zlib2 = require("zlib");
var {
bytesMatch,
makePolicyContainer,
clonePolicyContainer,
requestBadPort,
TAOCheck,
appendRequestOriginHeader,
responseLocationURL,
requestCurrentURL,
setRequestReferrerPolicyOnRedirect,
tryUpgradeRequestToAPotentiallyTrustworthyURL,
createOpaqueTimingInfo,
appendFetchMetadata,
corsCheck,
crossOriginResourcePolicyCheck,
determineRequestsReferrer,
coarsenedSharedCurrentTime,
createDeferredPromise,
sameOrigin,
isCancelled,
isAborted: isAborted2,
isErrorLike,
fullyReadBody,
readableStreamClose,
isomorphicEncode,
urlIsLocal,
urlIsHttpHttpsScheme,
urlHasHttpsScheme,
clampAndCoarsenConnectionTimingInfo,
simpleRangeHeaderValue,
buildContentRange,
createInflate,
extractMimeType
} = require_util2();
var assert44 = require("assert");
var { safelyExtractBody, extractBody } = require_body();
var {
redirectStatusSet,
nullBodyStatus,
safeMethodsSet,
requestBodyHeader,
subresourceSet
} = require_constants3();
var EE = require("events");
var { Readable: Readable8, pipeline, finished, isErrored, isReadable } = require("stream");
var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
var { getGlobalDispatcher: getGlobalDispatcher2 } = require_global2();
var { webidl } = require_webidl();
var { STATUS_CODES } = require("http");
var GET_OR_HEAD = ["GET", "HEAD"];
var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici";
var resolveObjectURL;
var Fetch = class extends EE {
static {
__name(this, "Fetch");
}
constructor(dispatcher) {
super();
this.dispatcher = dispatcher;
this.connection = null;
this.dump = false;
this.state = "ongoing";
}
terminate(reason) {
if (this.state !== "ongoing") {
return;
}
this.state = "terminated";
this.connection?.destroy(reason);
this.emit("terminated", reason);
}
// https://fetch.spec.whatwg.org/#fetch-controller-abort
abort(error2) {
if (this.state !== "ongoing") {
return;
}
this.state = "aborted";
if (!error2) {
error2 = new DOMException("The operation was aborted.", "AbortError");
}
this.serializedAbortReason = error2;
this.connection?.destroy(error2);
this.emit("terminated", error2);
}
};
function handleFetchDone(response) {
finalizeAndReportTiming(response, "fetch");
}
__name(handleFetchDone, "handleFetchDone");
function fetch13(input, init3 = void 0) {
webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
let p6 = createDeferredPromise();
let requestObject;
try {
requestObject = new Request4(input, init3);
} catch (e7) {
p6.reject(e7);
return p6.promise;
}
const request4 = getRequestState(requestObject);
if (requestObject.signal.aborted) {
abortFetch(p6, request4, null, requestObject.signal.reason);
return p6.promise;
}
const globalObject = request4.client.globalObject;
if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
request4.serviceWorkers = "none";
}
let responseObject = null;
let locallyAborted = false;
let controller = null;
addAbortListener(
requestObject.signal,
() => {
locallyAborted = true;
assert44(controller != null);
controller.abort(requestObject.signal.reason);
const realResponse = responseObject?.deref();
abortFetch(p6, request4, realResponse, requestObject.signal.reason);
}
);
const processResponse = /* @__PURE__ */ __name((response) => {
if (locallyAborted) {
return;
}
if (response.aborted) {
abortFetch(p6, request4, responseObject, controller.serializedAbortReason);
return;
}
if (response.type === "error") {
p6.reject(new TypeError("fetch failed", { cause: response.error }));
return;
}
responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
p6.resolve(responseObject.deref());
p6 = null;
}, "processResponse");
controller = fetching({
request: request4,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: getRequestDispatcher(requestObject)
// undici
});
return p6.promise;
}
__name(fetch13, "fetch");
function finalizeAndReportTiming(response, initiatorType = "other") {
if (response.type === "error" && response.aborted) {
return;
}
if (!response.urlList?.length) {
return;
}
const originalURL = response.urlList[0];
let timingInfo = response.timingInfo;
let cacheState = response.cacheState;
if (!urlIsHttpHttpsScheme(originalURL)) {
return;
}
if (timingInfo === null) {
return;
}
if (!response.timingAllowPassed) {
timingInfo = createOpaqueTimingInfo({
startTime: timingInfo.startTime
});
cacheState = "";
}
timingInfo.endTime = coarsenedSharedCurrentTime();
response.timingInfo = timingInfo;
markResourceTiming(
timingInfo,
originalURL.href,
initiatorType,
globalThis,
cacheState,
"",
// bodyType
response.status
);
}
__name(finalizeAndReportTiming, "finalizeAndReportTiming");
var markResourceTiming = performance.markResourceTiming;
function abortFetch(p6, request4, responseObject, error2) {
if (p6) {
p6.reject(error2);
}
if (request4.body?.stream != null && isReadable(request4.body.stream)) {
request4.body.stream.cancel(error2).catch((err) => {
if (err.code === "ERR_INVALID_STATE") {
return;
}
throw err;
});
}
if (responseObject == null) {
return;
}
const response = getResponseState(responseObject);
if (response.body?.stream != null && isReadable(response.body.stream)) {
response.body.stream.cancel(error2).catch((err) => {
if (err.code === "ERR_INVALID_STATE") {
return;
}
throw err;
});
}
}
__name(abortFetch, "abortFetch");
function fetching({
request: request4,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseEndOfBody,
processResponseConsumeBody,
useParallelQueue = false,
dispatcher = getGlobalDispatcher2()
// undici
}) {
assert44(dispatcher);
let taskDestination = null;
let crossOriginIsolatedCapability = false;
if (request4.client != null) {
taskDestination = request4.client.globalObject;
crossOriginIsolatedCapability = request4.client.crossOriginIsolatedCapability;
}
const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability);
const timingInfo = createOpaqueTimingInfo({
startTime: currentTime
});
const fetchParams = {
controller: new Fetch(dispatcher),
request: request4,
timingInfo,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseConsumeBody,
processResponseEndOfBody,
taskDestination,
crossOriginIsolatedCapability
};
assert44(!request4.body || request4.body.stream);
if (request4.window === "client") {
request4.window = request4.client?.globalObject?.constructor?.name === "Window" ? request4.client : "no-window";
}
if (request4.origin === "client") {
request4.origin = request4.client.origin;
}
if (request4.policyContainer === "client") {
if (request4.client != null) {
request4.policyContainer = clonePolicyContainer(
request4.client.policyContainer
);
} else {
request4.policyContainer = makePolicyContainer();
}
}
if (!request4.headersList.contains("accept", true)) {
const value = "*/*";
request4.headersList.append("accept", value, true);
}
if (!request4.headersList.contains("accept-language", true)) {
request4.headersList.append("accept-language", "*", true);
}
if (request4.priority === null) {
}
if (subresourceSet.has(request4.destination)) {
}
mainFetch(fetchParams).catch((err) => {
fetchParams.controller.terminate(err);
});
return fetchParams.controller;
}
__name(fetching, "fetching");
async function mainFetch(fetchParams, recursive = false) {
const request4 = fetchParams.request;
let response = null;
if (request4.localURLsOnly && !urlIsLocal(requestCurrentURL(request4))) {
response = makeNetworkError("local URLs only");
}
tryUpgradeRequestToAPotentiallyTrustworthyURL(request4);
if (requestBadPort(request4) === "blocked") {
response = makeNetworkError("bad port");
}
if (request4.referrerPolicy === "") {
request4.referrerPolicy = request4.policyContainer.referrerPolicy;
}
if (request4.referrer !== "no-referrer") {
request4.referrer = determineRequestsReferrer(request4);
}
if (response === null) {
const currentURL = requestCurrentURL(request4);
if (
// - request’s current URL’s origin is same origin with request’s origin,
// and request’s response tainting is "basic"
sameOrigin(currentURL, request4.url) && request4.responseTainting === "basic" || // request’s current URL’s scheme is "data"
currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket"
(request4.mode === "navigate" || request4.mode === "websocket")
) {
request4.responseTainting = "basic";
response = await schemeFetch(fetchParams);
} else if (request4.mode === "same-origin") {
response = makeNetworkError('request mode cannot be "same-origin"');
} else if (request4.mode === "no-cors") {
if (request4.redirect !== "follow") {
response = makeNetworkError(
'redirect mode cannot be "follow" for "no-cors" request'
);
} else {
request4.responseTainting = "opaque";
response = await schemeFetch(fetchParams);
}
} else if (!urlIsHttpHttpsScheme(requestCurrentURL(request4))) {
response = makeNetworkError("URL scheme must be a HTTP(S) scheme");
} else {
request4.responseTainting = "cors";
response = await httpFetch(fetchParams);
}
}
if (recursive) {
return response;
}
if (response.status !== 0 && !response.internalResponse) {
if (request4.responseTainting === "cors") {
}
if (request4.responseTainting === "basic") {
response = filterResponse(response, "basic");
} else if (request4.responseTainting === "cors") {
response = filterResponse(response, "cors");
} else if (request4.responseTainting === "opaque") {
response = filterResponse(response, "opaque");
} else {
assert44(false);
}
}
let internalResponse = response.status === 0 ? response : response.internalResponse;
if (internalResponse.urlList.length === 0) {
internalResponse.urlList.push(...request4.urlList);
}
if (!request4.timingAllowFailed) {
response.timingAllowPassed = true;
}
if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request4.headers.contains("range", true)) {
response = internalResponse = makeNetworkError();
}
if (response.status !== 0 && (request4.method === "HEAD" || request4.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
internalResponse.body = null;
fetchParams.controller.dump = true;
}
if (request4.integrity) {
const processBodyError = /* @__PURE__ */ __name((reason) => fetchFinale(fetchParams, makeNetworkError(reason)), "processBodyError");
if (request4.responseTainting === "opaque" || response.body == null) {
processBodyError(response.error);
return;
}
const processBody = /* @__PURE__ */ __name((bytes) => {
if (!bytesMatch(bytes, request4.integrity)) {
processBodyError("integrity mismatch");
return;
}
response.body = safelyExtractBody(bytes)[0];
fetchFinale(fetchParams, response);
}, "processBody");
await fullyReadBody(response.body, processBody, processBodyError);
} else {
fetchFinale(fetchParams, response);
}
}
__name(mainFetch, "mainFetch");
function schemeFetch(fetchParams) {
if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
return Promise.resolve(makeAppropriateNetworkError(fetchParams));
}
const { request: request4 } = fetchParams;
const { protocol: scheme } = requestCurrentURL(request4);
switch (scheme) {
case "about:": {
return Promise.resolve(makeNetworkError("about scheme is not supported"));
}
case "blob:": {
if (!resolveObjectURL) {
resolveObjectURL = require("buffer").resolveObjectURL;
}
const blobURLEntry = requestCurrentURL(request4);
if (blobURLEntry.search.length !== 0) {
return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."));
}
const blob = resolveObjectURL(blobURLEntry.toString());
if (request4.method !== "GET" || !webidl.is.Blob(blob)) {
return Promise.resolve(makeNetworkError("invalid method"));
}
const response = makeResponse();
const fullLength = blob.size;
const serializedFullLength = isomorphicEncode(`${fullLength}`);
const type = blob.type;
if (!request4.headersList.contains("range", true)) {
const bodyWithType = extractBody(blob);
response.statusText = "OK";
response.body = bodyWithType[0];
response.headersList.set("content-length", serializedFullLength, true);
response.headersList.set("content-type", type, true);
} else {
response.rangeRequested = true;
const rangeHeader = request4.headersList.get("range", true);
const rangeValue = simpleRangeHeaderValue(rangeHeader, true);
if (rangeValue === "failure") {
return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
}
let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue;
if (rangeStart === null) {
rangeStart = fullLength - rangeEnd;
rangeEnd = rangeStart + rangeEnd - 1;
} else {
if (rangeStart >= fullLength) {
return Promise.resolve(makeNetworkError("Range start is greater than the blob's size."));
}
if (rangeEnd === null || rangeEnd >= fullLength) {
rangeEnd = fullLength - 1;
}
}
const slicedBlob = blob.slice(rangeStart, rangeEnd, type);
const slicedBodyWithType = extractBody(slicedBlob);
response.body = slicedBodyWithType[0];
const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`);
const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength);
response.status = 206;
response.statusText = "Partial Content";
response.headersList.set("content-length", serializedSlicedLength, true);
response.headersList.set("content-type", type, true);
response.headersList.set("content-range", contentRange, true);
}
return Promise.resolve(response);
}
case "data:": {
const currentURL = requestCurrentURL(request4);
const dataURLStruct = dataURLProcessor(currentURL);
if (dataURLStruct === "failure") {
return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
}
const mimeType = serializeAMimeType(dataURLStruct.mimeType);
return Promise.resolve(makeResponse({
statusText: "OK",
headersList: [
["content-type", { name: "Content-Type", value: mimeType }]
],
body: safelyExtractBody(dataURLStruct.body)[0]
}));
}
case "file:": {
return Promise.resolve(makeNetworkError("not implemented... yet..."));
}
case "http:":
case "https:": {
return httpFetch(fetchParams).catch((err) => makeNetworkError(err));
}
default: {
return Promise.resolve(makeNetworkError("unknown scheme"));
}
}
}
__name(schemeFetch, "schemeFetch");
function finalizeResponse(fetchParams, response) {
fetchParams.request.done = true;
if (fetchParams.processResponseDone != null) {
queueMicrotask(() => fetchParams.processResponseDone(response));
}
}
__name(finalizeResponse, "finalizeResponse");
function fetchFinale(fetchParams, response) {
let timingInfo = fetchParams.timingInfo;
const processResponseEndOfBody = /* @__PURE__ */ __name(() => {
const unsafeEndTime = Date.now();
if (fetchParams.request.destination === "document") {
fetchParams.controller.fullTimingInfo = timingInfo;
}
fetchParams.controller.reportTimingSteps = () => {
if (!urlIsHttpHttpsScheme(fetchParams.request.url)) {
return;
}
timingInfo.endTime = unsafeEndTime;
let cacheState = response.cacheState;
const bodyInfo = response.bodyInfo;
if (!response.timingAllowPassed) {
timingInfo = createOpaqueTimingInfo(timingInfo);
cacheState = "";
}
let responseStatus = 0;
if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) {
responseStatus = response.status;
const mimeType = extractMimeType(response.headersList);
if (mimeType !== "failure") {
bodyInfo.contentType = minimizeSupportedMimeType(mimeType);
}
}
if (fetchParams.request.initiatorType != null) {
markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus);
}
};
const processResponseEndOfBodyTask = /* @__PURE__ */ __name(() => {
fetchParams.request.done = true;
if (fetchParams.processResponseEndOfBody != null) {
queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
}
if (fetchParams.request.initiatorType != null) {
fetchParams.controller.reportTimingSteps();
}
}, "processResponseEndOfBodyTask");
queueMicrotask(() => processResponseEndOfBodyTask());
}, "processResponseEndOfBody");
if (fetchParams.processResponse != null) {
queueMicrotask(() => {
fetchParams.processResponse(response);
fetchParams.processResponse = null;
});
}
const internalResponse = response.type === "error" ? response : response.internalResponse ?? response;
if (internalResponse.body == null) {
processResponseEndOfBody();
} else {
finished(internalResponse.body.stream, () => {
processResponseEndOfBody();
});
}
}
__name(fetchFinale, "fetchFinale");
async function httpFetch(fetchParams) {
const request4 = fetchParams.request;
let response = null;
let actualResponse = null;
const timingInfo = fetchParams.timingInfo;
if (request4.serviceWorkers === "all") {
}
if (response === null) {
if (request4.redirect === "follow") {
request4.serviceWorkers = "none";
}
actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
if (request4.responseTainting === "cors" && corsCheck(request4, response) === "failure") {
return makeNetworkError("cors failure");
}
if (TAOCheck(request4, response) === "failure") {
request4.timingAllowFailed = true;
}
}
if ((request4.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(
request4.origin,
request4.client,
request4.destination,
actualResponse
) === "blocked") {
return makeNetworkError("blocked");
}
if (redirectStatusSet.has(actualResponse.status)) {
if (request4.redirect !== "manual") {
fetchParams.controller.connection.destroy(void 0, false);
}
if (request4.redirect === "error") {
response = makeNetworkError("unexpected redirect");
} else if (request4.redirect === "manual") {
response = actualResponse;
} else if (request4.redirect === "follow") {
response = await httpRedirectFetch(fetchParams, response);
} else {
assert44(false);
}
}
response.timingInfo = timingInfo;
return response;
}
__name(httpFetch, "httpFetch");
function httpRedirectFetch(fetchParams, response) {
const request4 = fetchParams.request;
const actualResponse = response.internalResponse ? response.internalResponse : response;
let locationURL;
try {
locationURL = responseLocationURL(
actualResponse,
requestCurrentURL(request4).hash
);
if (locationURL == null) {
return response;
}
} catch (err) {
return Promise.resolve(makeNetworkError(err));
}
if (!urlIsHttpHttpsScheme(locationURL)) {
return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"));
}
if (request4.redirectCount === 20) {
return Promise.resolve(makeNetworkError("redirect count exceeded"));
}
request4.redirectCount += 1;
if (request4.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request4, locationURL)) {
return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'));
}
if (request4.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
return Promise.resolve(makeNetworkError(
'URL cannot contain credentials for request mode "cors"'
));
}
if (actualResponse.status !== 303 && request4.body != null && request4.body.source == null) {
return Promise.resolve(makeNetworkError());
}
if ([301, 302].includes(actualResponse.status) && request4.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request4.method)) {
request4.method = "GET";
request4.body = null;
for (const headerName of requestBodyHeader) {
request4.headersList.delete(headerName);
}
}
if (!sameOrigin(requestCurrentURL(request4), locationURL)) {
request4.headersList.delete("authorization", true);
request4.headersList.delete("proxy-authorization", true);
request4.headersList.delete("cookie", true);
request4.headersList.delete("host", true);
}
if (request4.body != null) {
assert44(request4.body.source != null);
request4.body = safelyExtractBody(request4.body.source)[0];
}
const timingInfo = fetchParams.timingInfo;
timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
if (timingInfo.redirectStartTime === 0) {
timingInfo.redirectStartTime = timingInfo.startTime;
}
request4.urlList.push(locationURL);
setRequestReferrerPolicyOnRedirect(request4, actualResponse);
return mainFetch(fetchParams, true);
}
__name(httpRedirectFetch, "httpRedirectFetch");
async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
const request4 = fetchParams.request;
let httpFetchParams = null;
let httpRequest2 = null;
let response = null;
const httpCache = null;
const revalidatingFlag = false;
if (request4.window === "no-window" && request4.redirect === "error") {
httpFetchParams = fetchParams;
httpRequest2 = request4;
} else {
httpRequest2 = cloneRequest(request4);
httpFetchParams = { ...fetchParams };
httpFetchParams.request = httpRequest2;
}
const includeCredentials = request4.credentials === "include" || request4.credentials === "same-origin" && request4.responseTainting === "basic";
const contentLength = httpRequest2.body ? httpRequest2.body.length : null;
let contentLengthHeaderValue = null;
if (httpRequest2.body == null && ["POST", "PUT"].includes(httpRequest2.method)) {
contentLengthHeaderValue = "0";
}
if (contentLength != null) {
contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
}
if (contentLengthHeaderValue != null) {
httpRequest2.headersList.append("content-length", contentLengthHeaderValue, true);
}
if (contentLength != null && httpRequest2.keepalive) {
}
if (webidl.is.URL(httpRequest2.referrer)) {
httpRequest2.headersList.append("referer", isomorphicEncode(httpRequest2.referrer.href), true);
}
appendRequestOriginHeader(httpRequest2);
appendFetchMetadata(httpRequest2);
if (!httpRequest2.headersList.contains("user-agent", true)) {
httpRequest2.headersList.append("user-agent", defaultUserAgent, true);
}
if (httpRequest2.cache === "default" && (httpRequest2.headersList.contains("if-modified-since", true) || httpRequest2.headersList.contains("if-none-match", true) || httpRequest2.headersList.contains("if-unmodified-since", true) || httpRequest2.headersList.contains("if-match", true) || httpRequest2.headersList.contains("if-range", true))) {
httpRequest2.cache = "no-store";
}
if (httpRequest2.cache === "no-cache" && !httpRequest2.preventNoCacheCacheControlHeaderModification && !httpRequest2.headersList.contains("cache-control", true)) {
httpRequest2.headersList.append("cache-control", "max-age=0", true);
}
if (httpRequest2.cache === "no-store" || httpRequest2.cache === "reload") {
if (!httpRequest2.headersList.contains("pragma", true)) {
httpRequest2.headersList.append("pragma", "no-cache", true);
}
if (!httpRequest2.headersList.contains("cache-control", true)) {
httpRequest2.headersList.append("cache-control", "no-cache", true);
}
}
if (httpRequest2.headersList.contains("range", true)) {
httpRequest2.headersList.append("accept-encoding", "identity", true);
}
if (!httpRequest2.headersList.contains("accept-encoding", true)) {
if (urlHasHttpsScheme(requestCurrentURL(httpRequest2))) {
httpRequest2.headersList.append("accept-encoding", "br, gzip, deflate", true);
} else {
httpRequest2.headersList.append("accept-encoding", "gzip, deflate", true);
}
}
httpRequest2.headersList.delete("host", true);
if (includeCredentials) {
}
if (httpCache == null) {
httpRequest2.cache = "no-store";
}
if (httpRequest2.cache !== "no-store" && httpRequest2.cache !== "reload") {
}
if (response == null) {
if (httpRequest2.cache === "only-if-cached") {
return makeNetworkError("only if cached");
}
const forwardResponse = await httpNetworkFetch(
httpFetchParams,
includeCredentials,
isNewConnectionFetch
);
if (!safeMethodsSet.has(httpRequest2.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
}
if (revalidatingFlag && forwardResponse.status === 304) {
}
if (response == null) {
response = forwardResponse;
}
}
response.urlList = [...httpRequest2.urlList];
if (httpRequest2.headersList.contains("range", true)) {
response.rangeRequested = true;
}
response.requestIncludesCredentials = includeCredentials;
if (response.status === 407) {
if (request4.window === "no-window") {
return makeNetworkError();
}
if (isCancelled(fetchParams)) {
return makeAppropriateNetworkError(fetchParams);
}
return makeNetworkError("proxy authentication required");
}
if (
// response’s status is 421
response.status === 421 && // isNewConnectionFetch is false
!isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
(request4.body == null || request4.body.source != null)
) {
if (isCancelled(fetchParams)) {
return makeAppropriateNetworkError(fetchParams);
}
fetchParams.controller.connection.destroy();
response = await httpNetworkOrCacheFetch(
fetchParams,
isAuthenticationFetch,
true
);
}
if (isAuthenticationFetch) {
}
return response;
}
__name(httpNetworkOrCacheFetch, "httpNetworkOrCacheFetch");
async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
assert44(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
fetchParams.controller.connection = {
abort: null,
destroyed: false,
destroy(err, abort = true) {
if (!this.destroyed) {
this.destroyed = true;
if (abort) {
this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
}
}
}
};
const request4 = fetchParams.request;
let response = null;
const timingInfo = fetchParams.timingInfo;
const httpCache = null;
if (httpCache == null) {
request4.cache = "no-store";
}
const newConnection = forceNewConnection ? "yes" : "no";
if (request4.mode === "websocket") {
} else {
}
let requestBody = null;
if (request4.body == null && fetchParams.processRequestEndOfBody) {
queueMicrotask(() => fetchParams.processRequestEndOfBody());
} else if (request4.body != null) {
const processBodyChunk = /* @__PURE__ */ __name(async function* (bytes) {
if (isCancelled(fetchParams)) {
return;
}
yield bytes;
fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
}, "processBodyChunk");
const processEndOfBody = /* @__PURE__ */ __name(() => {
if (isCancelled(fetchParams)) {
return;
}
if (fetchParams.processRequestEndOfBody) {
fetchParams.processRequestEndOfBody();
}
}, "processEndOfBody");
const processBodyError = /* @__PURE__ */ __name((e7) => {
if (isCancelled(fetchParams)) {
return;
}
if (e7.name === "AbortError") {
fetchParams.controller.abort();
} else {
fetchParams.controller.terminate(e7);
}
}, "processBodyError");
requestBody = async function* () {
try {
for await (const bytes of request4.body.stream) {
yield* processBodyChunk(bytes);
}
processEndOfBody();
} catch (err) {
processBodyError(err);
}
}();
}
try {
const { body, status: status2, statusText, headersList, socket } = await dispatch({ body: requestBody });
if (socket) {
response = makeResponse({ status: status2, statusText, headersList, socket });
} else {
const iterator = body[Symbol.asyncIterator]();
fetchParams.controller.next = () => iterator.next();
response = makeResponse({ status: status2, statusText, headersList });
}
} catch (err) {
if (err.name === "AbortError") {
fetchParams.controller.connection.destroy();
return makeAppropriateNetworkError(fetchParams, err);
}
return makeNetworkError(err);
}
const pullAlgorithm = /* @__PURE__ */ __name(() => {
return fetchParams.controller.resume();
}, "pullAlgorithm");
const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
if (!isCancelled(fetchParams)) {
fetchParams.controller.abort(reason);
}
}, "cancelAlgorithm");
const stream2 = new ReadableStream(
{
async start(controller) {
fetchParams.controller.controller = controller;
},
async pull(controller) {
await pullAlgorithm(controller);
},
async cancel(reason) {
await cancelAlgorithm(reason);
},
type: "bytes"
}
);
response.body = { stream: stream2, source: null, length: null };
if (!fetchParams.controller.resume) {
fetchParams.controller.on("terminated", onAborted);
}
fetchParams.controller.resume = async () => {
while (true) {
let bytes;
let isFailure;
try {
const { done, value } = await fetchParams.controller.next();
if (isAborted2(fetchParams)) {
break;
}
bytes = done ? void 0 : value;
} catch (err) {
if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
bytes = void 0;
} else {
bytes = err;
isFailure = true;
}
}
if (bytes === void 0) {
readableStreamClose(fetchParams.controller.controller);
finalizeResponse(fetchParams, response);
return;
}
timingInfo.decodedBodySize += bytes?.byteLength ?? 0;
if (isFailure) {
fetchParams.controller.terminate(bytes);
return;
}
const buffer = new Uint8Array(bytes);
if (buffer.byteLength) {
fetchParams.controller.controller.enqueue(buffer);
}
if (isErrored(stream2)) {
fetchParams.controller.terminate();
return;
}
if (fetchParams.controller.controller.desiredSize <= 0) {
return;
}
}
};
function onAborted(reason) {
if (isAborted2(fetchParams)) {
response.aborted = true;
if (isReadable(stream2)) {
fetchParams.controller.controller.error(
fetchParams.controller.serializedAbortReason
);
}
} else {
if (isReadable(stream2)) {
fetchParams.controller.controller.error(new TypeError("terminated", {
cause: isErrorLike(reason) ? reason : void 0
}));
}
}
fetchParams.controller.connection.destroy();
}
__name(onAborted, "onAborted");
return response;
function dispatch({ body }) {
const url4 = requestCurrentURL(request4);
const agent = fetchParams.controller.dispatcher;
return new Promise((resolve25, reject) => agent.dispatch(
{
path: url4.pathname + url4.search,
origin: url4.origin,
method: request4.method,
body: agent.isMockActive ? request4.body && (request4.body.source || request4.body.stream) : body,
headers: request4.headersList.entries,
maxRedirections: 0,
upgrade: request4.mode === "websocket" ? "websocket" : void 0
},
{
body: null,
abort: null,
onConnect(abort) {
const { connection } = fetchParams.controller;
timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
if (connection.destroyed) {
abort(new DOMException("The operation was aborted.", "AbortError"));
} else {
fetchParams.controller.on("terminated", abort);
this.abort = connection.abort = abort;
}
timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
},
onResponseStarted() {
timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
},
onHeaders(status2, rawHeaders, resume, statusText) {
if (status2 < 200) {
return;
}
let codings = [];
let location = "";
const headersList = new HeadersList();
for (let i5 = 0; i5 < rawHeaders.length; i5 += 2) {
headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i5]), rawHeaders[i5 + 1].toString("latin1"), true);
}
const contentEncoding = headersList.get("content-encoding", true);
if (contentEncoding) {
codings = contentEncoding.toLowerCase().split(",").map((x6) => x6.trim());
}
location = headersList.get("location", true);
this.body = new Readable8({ read: resume });
const decoders = [];
const willFollow = location && request4.redirect === "follow" && redirectStatusSet.has(status2);
if (codings.length !== 0 && request4.method !== "HEAD" && request4.method !== "CONNECT" && !nullBodyStatus.includes(status2) && !willFollow) {
for (let i5 = codings.length - 1; i5 >= 0; --i5) {
const coding = codings[i5];
if (coding === "x-gzip" || coding === "gzip") {
decoders.push(zlib2.createGunzip({
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
flush: zlib2.constants.Z_SYNC_FLUSH,
finishFlush: zlib2.constants.Z_SYNC_FLUSH
}));
} else if (coding === "deflate") {
decoders.push(createInflate({
flush: zlib2.constants.Z_SYNC_FLUSH,
finishFlush: zlib2.constants.Z_SYNC_FLUSH
}));
} else if (coding === "br") {
decoders.push(zlib2.createBrotliDecompress({
flush: zlib2.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib2.constants.BROTLI_OPERATION_FLUSH
}));
} else if (coding === "zstd" && typeof zlib2.createZstdDecompress === "function") {
decoders.push(zlib2.createZstdDecompress({
flush: zlib2.constants.ZSTD_e_continue,
finishFlush: zlib2.constants.ZSTD_e_end
}));
} else {
decoders.length = 0;
break;
}
}
}
const onError = this.onError.bind(this);
resolve25({
status: status2,
statusText,
headersList,
body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
if (err) {
this.onError(err);
}
}).on("error", onError) : this.body.on("error", onError)
});
return true;
},
onData(chunk) {
if (fetchParams.controller.dump) {
return;
}
const bytes = chunk;
timingInfo.encodedBodySize += bytes.byteLength;
return this.body.push(bytes);
},
onComplete() {
if (this.abort) {
fetchParams.controller.off("terminated", this.abort);
}
fetchParams.controller.ended = true;
this.body.push(null);
},
onError(error2) {
if (this.abort) {
fetchParams.controller.off("terminated", this.abort);
}
this.body?.destroy(error2);
fetchParams.controller.terminate(error2);
reject(error2);
},
onUpgrade(status2, rawHeaders, socket) {
if (status2 !== 101) {
return;
}
const headersList = new HeadersList();
for (let i5 = 0; i5 < rawHeaders.length; i5 += 2) {
headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i5]), rawHeaders[i5 + 1].toString("latin1"), true);
}
resolve25({
status: status2,
statusText: STATUS_CODES[status2],
headersList,
socket
});
return true;
}
}
));
}
__name(dispatch, "dispatch");
}
__name(httpNetworkFetch, "httpNetworkFetch");
module3.exports = {
fetch: fetch13,
Fetch,
fetching,
finalizeAndReportTiming
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cache/util.js
var require_util3 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cache/util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var assert44 = require("assert");
var { URLSerializer } = require_data_url();
var { isValidHeaderName } = require_util2();
function urlEquals(A3, B3, excludeFragment = false) {
const serializedA = URLSerializer(A3, excludeFragment);
const serializedB = URLSerializer(B3, excludeFragment);
return serializedA === serializedB;
}
__name(urlEquals, "urlEquals");
function getFieldValues(header) {
assert44(header !== null);
const values = [];
for (let value of header.split(",")) {
value = value.trim();
if (isValidHeaderName(value)) {
values.push(value);
}
}
return values;
}
__name(getFieldValues, "getFieldValues");
module3.exports = {
urlEquals,
getFieldValues
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cache/cache.js
var require_cache3 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cache/cache.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { kConstruct } = require_symbols();
var { urlEquals, getFieldValues } = require_util3();
var { kEnumerableProperty, isDisturbed } = require_util();
var { webidl } = require_webidl();
var { cloneResponse, fromInnerResponse, getResponseState } = require_response();
var { Request: Request4, fromInnerRequest, getRequestState } = require_request2();
var { fetching } = require_fetch();
var { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require_util2();
var assert44 = require("assert");
var Cache2 = class _Cache {
static {
__name(this, "Cache");
}
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
* @type {requestResponseList}
*/
#relevantRequestResponseList;
constructor() {
if (arguments[0] !== kConstruct) {
webidl.illegalConstructor();
}
webidl.util.markAsUncloneable(this);
this.#relevantRequestResponseList = arguments[1];
}
async match(request4, options = {}) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.match";
webidl.argumentLengthCheck(arguments, 1, prefix);
request4 = webidl.converters.RequestInfo(request4, prefix, "request");
options = webidl.converters.CacheQueryOptions(options, prefix, "options");
const p6 = this.#internalMatchAll(request4, options, 1);
if (p6.length === 0) {
return;
}
return p6[0];
}
async matchAll(request4 = void 0, options = {}) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.matchAll";
if (request4 !== void 0) request4 = webidl.converters.RequestInfo(request4, prefix, "request");
options = webidl.converters.CacheQueryOptions(options, prefix, "options");
return this.#internalMatchAll(request4, options);
}
async add(request4) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.add";
webidl.argumentLengthCheck(arguments, 1, prefix);
request4 = webidl.converters.RequestInfo(request4, prefix, "request");
const requests = [request4];
const responseArrayPromise = this.addAll(requests);
return await responseArrayPromise;
}
async addAll(requests) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.addAll";
webidl.argumentLengthCheck(arguments, 1, prefix);
const responsePromises = [];
const requestList = [];
for (let request4 of requests) {
if (request4 === void 0) {
throw webidl.errors.conversionFailed({
prefix,
argument: "Argument 1",
types: ["undefined is not allowed"]
});
}
request4 = webidl.converters.RequestInfo(request4);
if (typeof request4 === "string") {
continue;
}
const r7 = getRequestState(request4);
if (!urlIsHttpHttpsScheme(r7.url) || r7.method !== "GET") {
throw webidl.errors.exception({
header: prefix,
message: "Expected http/s scheme when method is not GET."
});
}
}
const fetchControllers = [];
for (const request4 of requests) {
const r7 = getRequestState(new Request4(request4));
if (!urlIsHttpHttpsScheme(r7.url)) {
throw webidl.errors.exception({
header: prefix,
message: "Expected http/s scheme."
});
}
r7.initiator = "fetch";
r7.destination = "subresource";
requestList.push(r7);
const responsePromise = createDeferredPromise();
fetchControllers.push(fetching({
request: r7,
processResponse(response) {
if (response.type === "error" || response.status === 206 || response.status < 200 || response.status > 299) {
responsePromise.reject(webidl.errors.exception({
header: "Cache.addAll",
message: "Received an invalid status code or the request failed."
}));
} else if (response.headersList.contains("vary")) {
const fieldValues = getFieldValues(response.headersList.get("vary"));
for (const fieldValue of fieldValues) {
if (fieldValue === "*") {
responsePromise.reject(webidl.errors.exception({
header: "Cache.addAll",
message: "invalid vary field value"
}));
for (const controller of fetchControllers) {
controller.abort();
}
return;
}
}
}
},
processResponseEndOfBody(response) {
if (response.aborted) {
responsePromise.reject(new DOMException("aborted", "AbortError"));
return;
}
responsePromise.resolve(response);
}
}));
responsePromises.push(responsePromise.promise);
}
const p6 = Promise.all(responsePromises);
const responses = await p6;
const operations = [];
let index = 0;
for (const response of responses) {
const operation = {
type: "put",
// 7.3.2
request: requestList[index],
// 7.3.3
response
// 7.3.4
};
operations.push(operation);
index++;
}
const cacheJobPromise = createDeferredPromise();
let errorData = null;
try {
this.#batchCacheOperations(operations);
} catch (e7) {
errorData = e7;
}
queueMicrotask(() => {
if (errorData === null) {
cacheJobPromise.resolve(void 0);
} else {
cacheJobPromise.reject(errorData);
}
});
return cacheJobPromise.promise;
}
async put(request4, response) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.put";
webidl.argumentLengthCheck(arguments, 2, prefix);
request4 = webidl.converters.RequestInfo(request4, prefix, "request");
response = webidl.converters.Response(response, prefix, "response");
let innerRequest = null;
if (webidl.is.Request(request4)) {
innerRequest = getRequestState(request4);
} else {
innerRequest = getRequestState(new Request4(request4));
}
if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") {
throw webidl.errors.exception({
header: prefix,
message: "Expected an http/s scheme when method is not GET"
});
}
const innerResponse = getResponseState(response);
if (innerResponse.status === 206) {
throw webidl.errors.exception({
header: prefix,
message: "Got 206 status"
});
}
if (innerResponse.headersList.contains("vary")) {
const fieldValues = getFieldValues(innerResponse.headersList.get("vary"));
for (const fieldValue of fieldValues) {
if (fieldValue === "*") {
throw webidl.errors.exception({
header: prefix,
message: "Got * vary field value"
});
}
}
}
if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
throw webidl.errors.exception({
header: prefix,
message: "Response body is locked or disturbed"
});
}
const clonedResponse = cloneResponse(innerResponse);
const bodyReadPromise = createDeferredPromise();
if (innerResponse.body != null) {
const stream2 = innerResponse.body.stream;
const reader = stream2.getReader();
readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject);
} else {
bodyReadPromise.resolve(void 0);
}
const operations = [];
const operation = {
type: "put",
// 14.
request: innerRequest,
// 15.
response: clonedResponse
// 16.
};
operations.push(operation);
const bytes = await bodyReadPromise.promise;
if (clonedResponse.body != null) {
clonedResponse.body.source = bytes;
}
const cacheJobPromise = createDeferredPromise();
let errorData = null;
try {
this.#batchCacheOperations(operations);
} catch (e7) {
errorData = e7;
}
queueMicrotask(() => {
if (errorData === null) {
cacheJobPromise.resolve();
} else {
cacheJobPromise.reject(errorData);
}
});
return cacheJobPromise.promise;
}
async delete(request4, options = {}) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.delete";
webidl.argumentLengthCheck(arguments, 1, prefix);
request4 = webidl.converters.RequestInfo(request4, prefix, "request");
options = webidl.converters.CacheQueryOptions(options, prefix, "options");
let r7 = null;
if (webidl.is.Request(request4)) {
r7 = getRequestState(request4);
if (r7.method !== "GET" && !options.ignoreMethod) {
return false;
}
} else {
assert44(typeof request4 === "string");
r7 = getRequestState(new Request4(request4));
}
const operations = [];
const operation = {
type: "delete",
request: r7,
options
};
operations.push(operation);
const cacheJobPromise = createDeferredPromise();
let errorData = null;
let requestResponses;
try {
requestResponses = this.#batchCacheOperations(operations);
} catch (e7) {
errorData = e7;
}
queueMicrotask(() => {
if (errorData === null) {
cacheJobPromise.resolve(!!requestResponses?.length);
} else {
cacheJobPromise.reject(errorData);
}
});
return cacheJobPromise.promise;
}
/**
* @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
* @param {any} request
* @param {import('../../types/cache').CacheQueryOptions} options
* @returns {Promise<readonly Request[]>}
*/
async keys(request4 = void 0, options = {}) {
webidl.brandCheck(this, _Cache);
const prefix = "Cache.keys";
if (request4 !== void 0) request4 = webidl.converters.RequestInfo(request4, prefix, "request");
options = webidl.converters.CacheQueryOptions(options, prefix, "options");
let r7 = null;
if (request4 !== void 0) {
if (webidl.is.Request(request4)) {
r7 = getRequestState(request4);
if (r7.method !== "GET" && !options.ignoreMethod) {
return [];
}
} else if (typeof request4 === "string") {
r7 = getRequestState(new Request4(request4));
}
}
const promise = createDeferredPromise();
const requests = [];
if (request4 === void 0) {
for (const requestResponse of this.#relevantRequestResponseList) {
requests.push(requestResponse[0]);
}
} else {
const requestResponses = this.#queryCache(r7, options);
for (const requestResponse of requestResponses) {
requests.push(requestResponse[0]);
}
}
queueMicrotask(() => {
const requestList = [];
for (const request5 of requests) {
const requestObject = fromInnerRequest(
request5,
void 0,
new AbortController().signal,
"immutable"
);
requestList.push(requestObject);
}
promise.resolve(Object.freeze(requestList));
});
return promise.promise;
}
/**
* @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
* @param {CacheBatchOperation[]} operations
* @returns {requestResponseList}
*/
#batchCacheOperations(operations) {
const cache6 = this.#relevantRequestResponseList;
const backupCache = [...cache6];
const addedItems = [];
const resultList = [];
try {
for (const operation of operations) {
if (operation.type !== "delete" && operation.type !== "put") {
throw webidl.errors.exception({
header: "Cache.#batchCacheOperations",
message: 'operation type does not match "delete" or "put"'
});
}
if (operation.type === "delete" && operation.response != null) {
throw webidl.errors.exception({
header: "Cache.#batchCacheOperations",
message: "delete operation should not have an associated response"
});
}
if (this.#queryCache(operation.request, operation.options, addedItems).length) {
throw new DOMException("???", "InvalidStateError");
}
let requestResponses;
if (operation.type === "delete") {
requestResponses = this.#queryCache(operation.request, operation.options);
if (requestResponses.length === 0) {
return [];
}
for (const requestResponse of requestResponses) {
const idx = cache6.indexOf(requestResponse);
assert44(idx !== -1);
cache6.splice(idx, 1);
}
} else if (operation.type === "put") {
if (operation.response == null) {
throw webidl.errors.exception({
header: "Cache.#batchCacheOperations",
message: "put operation should have an associated response"
});
}
const r7 = operation.request;
if (!urlIsHttpHttpsScheme(r7.url)) {
throw webidl.errors.exception({
header: "Cache.#batchCacheOperations",
message: "expected http or https scheme"
});
}
if (r7.method !== "GET") {
throw webidl.errors.exception({
header: "Cache.#batchCacheOperations",
message: "not get method"
});
}
if (operation.options != null) {
throw webidl.errors.exception({
header: "Cache.#batchCacheOperations",
message: "options must not be defined"
});
}
requestResponses = this.#queryCache(operation.request);
for (const requestResponse of requestResponses) {
const idx = cache6.indexOf(requestResponse);
assert44(idx !== -1);
cache6.splice(idx, 1);
}
cache6.push([operation.request, operation.response]);
addedItems.push([operation.request, operation.response]);
}
resultList.push([operation.request, operation.response]);
}
return resultList;
} catch (e7) {
this.#relevantRequestResponseList.length = 0;
this.#relevantRequestResponseList = backupCache;
throw e7;
}
}
/**
* @see https://w3c.github.io/ServiceWorker/#query-cache
* @param {any} requestQuery
* @param {import('../../types/cache').CacheQueryOptions} options
* @param {requestResponseList} targetStorage
* @returns {requestResponseList}
*/
#queryCache(requestQuery, options, targetStorage) {
const resultList = [];
const storage = targetStorage ?? this.#relevantRequestResponseList;
for (const requestResponse of storage) {
const [cachedRequest, cachedResponse] = requestResponse;
if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
resultList.push(requestResponse);
}
}
return resultList;
}
/**
* @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
* @param {any} requestQuery
* @param {any} request
* @param {any | null} response
* @param {import('../../types/cache').CacheQueryOptions | undefined} options
* @returns {boolean}
*/
#requestMatchesCachedItem(requestQuery, request4, response = null, options) {
const queryURL = new URL(requestQuery.url);
const cachedURL = new URL(request4.url);
if (options?.ignoreSearch) {
cachedURL.search = "";
queryURL.search = "";
}
if (!urlEquals(queryURL, cachedURL, true)) {
return false;
}
if (response == null || options?.ignoreVary || !response.headersList.contains("vary")) {
return true;
}
const fieldValues = getFieldValues(response.headersList.get("vary"));
for (const fieldValue of fieldValues) {
if (fieldValue === "*") {
return false;
}
const requestValue = request4.headersList.get(fieldValue);
const queryValue = requestQuery.headersList.get(fieldValue);
if (requestValue !== queryValue) {
return false;
}
}
return true;
}
#internalMatchAll(request4, options, maxResponses = Infinity) {
let r7 = null;
if (request4 !== void 0) {
if (webidl.is.Request(request4)) {
r7 = getRequestState(request4);
if (r7.method !== "GET" && !options.ignoreMethod) {
return [];
}
} else if (typeof request4 === "string") {
r7 = getRequestState(new Request4(request4));
}
}
const responses = [];
if (request4 === void 0) {
for (const requestResponse of this.#relevantRequestResponseList) {
responses.push(requestResponse[1]);
}
} else {
const requestResponses = this.#queryCache(r7, options);
for (const requestResponse of requestResponses) {
responses.push(requestResponse[1]);
}
}
const responseList = [];
for (const response of responses) {
const responseObject = fromInnerResponse(response, "immutable");
responseList.push(responseObject.clone());
if (responseList.length >= maxResponses) {
break;
}
}
return Object.freeze(responseList);
}
};
Object.defineProperties(Cache2.prototype, {
[Symbol.toStringTag]: {
value: "Cache",
configurable: true
},
match: kEnumerableProperty,
matchAll: kEnumerableProperty,
add: kEnumerableProperty,
addAll: kEnumerableProperty,
put: kEnumerableProperty,
delete: kEnumerableProperty,
keys: kEnumerableProperty
});
var cacheQueryOptionConverters = [
{
key: "ignoreSearch",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
},
{
key: "ignoreMethod",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
},
{
key: "ignoreVary",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
}
];
webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters);
webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
...cacheQueryOptionConverters,
{
key: "cacheName",
converter: webidl.converters.DOMString
}
]);
webidl.converters.Response = webidl.interfaceConverter(
webidl.is.Response,
"Response"
);
webidl.converters["sequence<RequestInfo>"] = webidl.sequenceConverter(
webidl.converters.RequestInfo
);
module3.exports = {
Cache: Cache2
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Cache: Cache2 } = require_cache3();
var { webidl } = require_webidl();
var { kEnumerableProperty } = require_util();
var { kConstruct } = require_symbols();
var CacheStorage2 = class _CacheStorage {
static {
__name(this, "CacheStorage");
}
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
* @type {Map<string, import('./cache').requestResponseList}
*/
#caches = /* @__PURE__ */ new Map();
constructor() {
if (arguments[0] !== kConstruct) {
webidl.illegalConstructor();
}
webidl.util.markAsUncloneable(this);
}
async match(request4, options = {}) {
webidl.brandCheck(this, _CacheStorage);
webidl.argumentLengthCheck(arguments, 1, "CacheStorage.match");
request4 = webidl.converters.RequestInfo(request4);
options = webidl.converters.MultiCacheQueryOptions(options);
if (options.cacheName != null) {
if (this.#caches.has(options.cacheName)) {
const cacheList = this.#caches.get(options.cacheName);
const cache6 = new Cache2(kConstruct, cacheList);
return await cache6.match(request4, options);
}
} else {
for (const cacheList of this.#caches.values()) {
const cache6 = new Cache2(kConstruct, cacheList);
const response = await cache6.match(request4, options);
if (response !== void 0) {
return response;
}
}
}
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-has
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async has(cacheName) {
webidl.brandCheck(this, _CacheStorage);
const prefix = "CacheStorage.has";
webidl.argumentLengthCheck(arguments, 1, prefix);
cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
return this.#caches.has(cacheName);
}
/**
* @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
* @param {string} cacheName
* @returns {Promise<Cache>}
*/
async open(cacheName) {
webidl.brandCheck(this, _CacheStorage);
const prefix = "CacheStorage.open";
webidl.argumentLengthCheck(arguments, 1, prefix);
cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
if (this.#caches.has(cacheName)) {
const cache7 = this.#caches.get(cacheName);
return new Cache2(kConstruct, cache7);
}
const cache6 = [];
this.#caches.set(cacheName, cache6);
return new Cache2(kConstruct, cache6);
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async delete(cacheName) {
webidl.brandCheck(this, _CacheStorage);
const prefix = "CacheStorage.delete";
webidl.argumentLengthCheck(arguments, 1, prefix);
cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
return this.#caches.delete(cacheName);
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
* @returns {Promise<string[]>}
*/
async keys() {
webidl.brandCheck(this, _CacheStorage);
const keys = this.#caches.keys();
return [...keys];
}
};
Object.defineProperties(CacheStorage2.prototype, {
[Symbol.toStringTag]: {
value: "CacheStorage",
configurable: true
},
match: kEnumerableProperty,
has: kEnumerableProperty,
open: kEnumerableProperty,
delete: kEnumerableProperty,
keys: kEnumerableProperty
});
module3.exports = {
CacheStorage: CacheStorage2
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/constants.js
var require_constants4 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/constants.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var maxAttributeValueSize = 1024;
var maxNameValuePairSize = 4096;
module3.exports = {
maxAttributeValueSize,
maxNameValuePairSize
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/util.js
var require_util4 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function isCTLExcludingHtab(value) {
for (let i5 = 0; i5 < value.length; ++i5) {
const code = value.charCodeAt(i5);
if (code >= 0 && code <= 8 || code >= 10 && code <= 31 || code === 127) {
return true;
}
}
return false;
}
__name(isCTLExcludingHtab, "isCTLExcludingHtab");
function validateCookieName(name2) {
for (let i5 = 0; i5 < name2.length; ++i5) {
const code = name2.charCodeAt(i5);
if (code < 33 || // exclude CTLs (0-31), SP and HT
code > 126 || // exclude non-ascii and DEL
code === 34 || // "
code === 40 || // (
code === 41 || // )
code === 60 || // <
code === 62 || // >
code === 64 || // @
code === 44 || // ,
code === 59 || // ;
code === 58 || // :
code === 92 || // \
code === 47 || // /
code === 91 || // [
code === 93 || // ]
code === 63 || // ?
code === 61 || // =
code === 123 || // {
code === 125) {
throw new Error("Invalid cookie name");
}
}
}
__name(validateCookieName, "validateCookieName");
function validateCookieValue(value) {
let len = value.length;
let i5 = 0;
if (value[0] === '"') {
if (len === 1 || value[len - 1] !== '"') {
throw new Error("Invalid cookie value");
}
--len;
++i5;
}
while (i5 < len) {
const code = value.charCodeAt(i5++);
if (code < 33 || // exclude CTLs (0-31)
code > 126 || // non-ascii and DEL (127)
code === 34 || // "
code === 44 || // ,
code === 59 || // ;
code === 92) {
throw new Error("Invalid cookie value");
}
}
}
__name(validateCookieValue, "validateCookieValue");
function validateCookiePath(path72) {
for (let i5 = 0; i5 < path72.length; ++i5) {
const code = path72.charCodeAt(i5);
if (code < 32 || // exclude CTLs (0-31)
code === 127 || // DEL
code === 59) {
throw new Error("Invalid cookie path");
}
}
}
__name(validateCookiePath, "validateCookiePath");
function validateCookieDomain(domain2) {
if (domain2.startsWith("-") || domain2.endsWith(".") || domain2.endsWith("-")) {
throw new Error("Invalid cookie domain");
}
}
__name(validateCookieDomain, "validateCookieDomain");
var IMFDays = [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
];
var IMFMonths = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
var IMFPaddedNumbers = Array(61).fill(0).map((_4, i5) => i5.toString().padStart(2, "0"));
function toIMFDate(date) {
if (typeof date === "number") {
date = new Date(date);
}
return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`;
}
__name(toIMFDate, "toIMFDate");
function validateCookieMaxAge(maxAge) {
if (maxAge < 0) {
throw new Error("Invalid cookie max-age");
}
}
__name(validateCookieMaxAge, "validateCookieMaxAge");
function stringify(cookie) {
if (cookie.name.length === 0) {
return null;
}
validateCookieName(cookie.name);
validateCookieValue(cookie.value);
const out = [`${cookie.name}=${cookie.value}`];
if (cookie.name.startsWith("__Secure-")) {
cookie.secure = true;
}
if (cookie.name.startsWith("__Host-")) {
cookie.secure = true;
cookie.domain = null;
cookie.path = "/";
}
if (cookie.secure) {
out.push("Secure");
}
if (cookie.httpOnly) {
out.push("HttpOnly");
}
if (typeof cookie.maxAge === "number") {
validateCookieMaxAge(cookie.maxAge);
out.push(`Max-Age=${cookie.maxAge}`);
}
if (cookie.domain) {
validateCookieDomain(cookie.domain);
out.push(`Domain=${cookie.domain}`);
}
if (cookie.path) {
validateCookiePath(cookie.path);
out.push(`Path=${cookie.path}`);
}
if (cookie.expires && cookie.expires.toString() !== "Invalid Date") {
out.push(`Expires=${toIMFDate(cookie.expires)}`);
}
if (cookie.sameSite) {
out.push(`SameSite=${cookie.sameSite}`);
}
for (const part of cookie.unparsed) {
if (!part.includes("=")) {
throw new Error("Invalid unparsed");
}
const [key, ...value] = part.split("=");
out.push(`${key.trim()}=${value.join("=")}`);
}
return out.join("; ");
}
__name(stringify, "stringify");
module3.exports = {
isCTLExcludingHtab,
validateCookieName,
validateCookiePath,
validateCookieValue,
toIMFDate,
stringify
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/parse.js
var require_parse = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/parse.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
var { isCTLExcludingHtab } = require_util4();
var { collectASequenceOfCodePointsFast } = require_data_url();
var assert44 = require("assert");
var { unescape: unescape2 } = require("querystring");
function parseSetCookie(header) {
if (isCTLExcludingHtab(header)) {
return null;
}
let nameValuePair = "";
let unparsedAttributes = "";
let name2 = "";
let value = "";
if (header.includes(";")) {
const position = { position: 0 };
nameValuePair = collectASequenceOfCodePointsFast(";", header, position);
unparsedAttributes = header.slice(position.position);
} else {
nameValuePair = header;
}
if (!nameValuePair.includes("=")) {
value = nameValuePair;
} else {
const position = { position: 0 };
name2 = collectASequenceOfCodePointsFast(
"=",
nameValuePair,
position
);
value = nameValuePair.slice(position.position + 1);
}
name2 = name2.trim();
value = value.trim();
if (name2.length + value.length > maxNameValuePairSize) {
return null;
}
return {
name: name2,
value: unescape2(value),
...parseUnparsedAttributes(unparsedAttributes)
};
}
__name(parseSetCookie, "parseSetCookie");
function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
if (unparsedAttributes.length === 0) {
return cookieAttributeList;
}
assert44(unparsedAttributes[0] === ";");
unparsedAttributes = unparsedAttributes.slice(1);
let cookieAv = "";
if (unparsedAttributes.includes(";")) {
cookieAv = collectASequenceOfCodePointsFast(
";",
unparsedAttributes,
{ position: 0 }
);
unparsedAttributes = unparsedAttributes.slice(cookieAv.length);
} else {
cookieAv = unparsedAttributes;
unparsedAttributes = "";
}
let attributeName = "";
let attributeValue = "";
if (cookieAv.includes("=")) {
const position = { position: 0 };
attributeName = collectASequenceOfCodePointsFast(
"=",
cookieAv,
position
);
attributeValue = cookieAv.slice(position.position + 1);
} else {
attributeName = cookieAv;
}
attributeName = attributeName.trim();
attributeValue = attributeValue.trim();
if (attributeValue.length > maxAttributeValueSize) {
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
}
const attributeNameLowercase = attributeName.toLowerCase();
if (attributeNameLowercase === "expires") {
const expiryTime = new Date(attributeValue);
cookieAttributeList.expires = expiryTime;
} else if (attributeNameLowercase === "max-age") {
const charCode = attributeValue.charCodeAt(0);
if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") {
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
}
if (!/^\d+$/.test(attributeValue)) {
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
}
const deltaSeconds = Number(attributeValue);
cookieAttributeList.maxAge = deltaSeconds;
} else if (attributeNameLowercase === "domain") {
let cookieDomain = attributeValue;
if (cookieDomain[0] === ".") {
cookieDomain = cookieDomain.slice(1);
}
cookieDomain = cookieDomain.toLowerCase();
cookieAttributeList.domain = cookieDomain;
} else if (attributeNameLowercase === "path") {
let cookiePath = "";
if (attributeValue.length === 0 || attributeValue[0] !== "/") {
cookiePath = "/";
} else {
cookiePath = attributeValue;
}
cookieAttributeList.path = cookiePath;
} else if (attributeNameLowercase === "secure") {
cookieAttributeList.secure = true;
} else if (attributeNameLowercase === "httponly") {
cookieAttributeList.httpOnly = true;
} else if (attributeNameLowercase === "samesite") {
let enforcement = "Default";
const attributeValueLowercase = attributeValue.toLowerCase();
if (attributeValueLowercase.includes("none")) {
enforcement = "None";
}
if (attributeValueLowercase.includes("strict")) {
enforcement = "Strict";
}
if (attributeValueLowercase.includes("lax")) {
enforcement = "Lax";
}
cookieAttributeList.sameSite = enforcement;
} else {
cookieAttributeList.unparsed ??= [];
cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
}
return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
}
__name(parseUnparsedAttributes, "parseUnparsedAttributes");
module3.exports = {
parseSetCookie,
parseUnparsedAttributes
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/index.js
var require_cookies = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/cookies/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { parseSetCookie } = require_parse();
var { stringify } = require_util4();
var { webidl } = require_webidl();
var { Headers: Headers5 } = require_headers();
var brandChecks = webidl.brandCheckMultiple([Headers5, globalThis.Headers].filter(Boolean));
function getCookies(headers) {
webidl.argumentLengthCheck(arguments, 1, "getCookies");
brandChecks(headers);
const cookie = headers.get("cookie");
const out = {};
if (!cookie) {
return out;
}
for (const piece of cookie.split(";")) {
const [name2, ...value] = piece.split("=");
out[name2.trim()] = value.join("=");
}
return out;
}
__name(getCookies, "getCookies");
function deleteCookie(headers, name2, attributes) {
brandChecks(headers);
const prefix = "deleteCookie";
webidl.argumentLengthCheck(arguments, 2, prefix);
name2 = webidl.converters.DOMString(name2, prefix, "name");
attributes = webidl.converters.DeleteCookieAttributes(attributes);
setCookie(headers, {
name: name2,
value: "",
expires: /* @__PURE__ */ new Date(0),
...attributes
});
}
__name(deleteCookie, "deleteCookie");
function getSetCookies(headers) {
webidl.argumentLengthCheck(arguments, 1, "getSetCookies");
brandChecks(headers);
const cookies = headers.getSetCookie();
if (!cookies) {
return [];
}
return cookies.map((pair) => parseSetCookie(pair));
}
__name(getSetCookies, "getSetCookies");
function parseCookie2(cookie) {
cookie = webidl.converters.DOMString(cookie);
return parseSetCookie(cookie);
}
__name(parseCookie2, "parseCookie");
function setCookie(headers, cookie) {
webidl.argumentLengthCheck(arguments, 2, "setCookie");
brandChecks(headers);
cookie = webidl.converters.Cookie(cookie);
const str = stringify(cookie);
if (str) {
headers.append("set-cookie", str, true);
}
}
__name(setCookie, "setCookie");
webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: "path",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: "domain",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
}
]);
webidl.converters.Cookie = webidl.dictionaryConverter([
{
converter: webidl.converters.DOMString,
key: "name"
},
{
converter: webidl.converters.DOMString,
key: "value"
},
{
converter: webidl.nullableConverter((value) => {
if (typeof value === "number") {
return webidl.converters["unsigned long long"](value);
}
return new Date(value);
}),
key: "expires",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.nullableConverter(webidl.converters["long long"]),
key: "maxAge",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: "domain",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.nullableConverter(webidl.converters.DOMString),
key: "path",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.nullableConverter(webidl.converters.boolean),
key: "secure",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.nullableConverter(webidl.converters.boolean),
key: "httpOnly",
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
converter: webidl.converters.USVString,
key: "sameSite",
allowedValues: ["Strict", "Lax", "None"]
},
{
converter: webidl.sequenceConverter(webidl.converters.DOMString),
key: "unparsed",
defaultValue: /* @__PURE__ */ __name(() => new Array(0), "defaultValue")
}
]);
module3.exports = {
getCookies,
deleteCookie,
getSetCookies,
setCookie,
parseCookie: parseCookie2
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/events.js
var require_events = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/events.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { webidl } = require_webidl();
var { kEnumerableProperty } = require_util();
var { kConstruct } = require_symbols();
var MessageEvent = class _MessageEvent extends Event {
static {
__name(this, "MessageEvent");
}
#eventInit;
constructor(type, eventInitDict = {}) {
if (type === kConstruct) {
super(arguments[1], arguments[2]);
webidl.util.markAsUncloneable(this);
return;
}
const prefix = "MessageEvent constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
type = webidl.converters.DOMString(type, prefix, "type");
eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, "eventInitDict");
super(type, eventInitDict);
this.#eventInit = eventInitDict;
webidl.util.markAsUncloneable(this);
}
get data() {
webidl.brandCheck(this, _MessageEvent);
return this.#eventInit.data;
}
get origin() {
webidl.brandCheck(this, _MessageEvent);
return this.#eventInit.origin;
}
get lastEventId() {
webidl.brandCheck(this, _MessageEvent);
return this.#eventInit.lastEventId;
}
get source() {
webidl.brandCheck(this, _MessageEvent);
return this.#eventInit.source;
}
get ports() {
webidl.brandCheck(this, _MessageEvent);
if (!Object.isFrozen(this.#eventInit.ports)) {
Object.freeze(this.#eventInit.ports);
}
return this.#eventInit.ports;
}
initMessageEvent(type, bubbles = false, cancelable = false, data = null, origin = "", lastEventId2 = "", source = null, ports = []) {
webidl.brandCheck(this, _MessageEvent);
webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
return new _MessageEvent(type, {
bubbles,
cancelable,
data,
origin,
lastEventId: lastEventId2,
source,
ports
});
}
static createFastMessageEvent(type, init3) {
const messageEvent = new _MessageEvent(kConstruct, type, init3);
messageEvent.#eventInit = init3;
messageEvent.#eventInit.data ??= null;
messageEvent.#eventInit.origin ??= "";
messageEvent.#eventInit.lastEventId ??= "";
messageEvent.#eventInit.source ??= null;
messageEvent.#eventInit.ports ??= [];
return messageEvent;
}
};
var { createFastMessageEvent } = MessageEvent;
delete MessageEvent.createFastMessageEvent;
var CloseEvent = class _CloseEvent extends Event {
static {
__name(this, "CloseEvent");
}
#eventInit;
constructor(type, eventInitDict = {}) {
const prefix = "CloseEvent constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
type = webidl.converters.DOMString(type, prefix, "type");
eventInitDict = webidl.converters.CloseEventInit(eventInitDict);
super(type, eventInitDict);
this.#eventInit = eventInitDict;
webidl.util.markAsUncloneable(this);
}
get wasClean() {
webidl.brandCheck(this, _CloseEvent);
return this.#eventInit.wasClean;
}
get code() {
webidl.brandCheck(this, _CloseEvent);
return this.#eventInit.code;
}
get reason() {
webidl.brandCheck(this, _CloseEvent);
return this.#eventInit.reason;
}
};
var ErrorEvent = class _ErrorEvent extends Event {
static {
__name(this, "ErrorEvent");
}
#eventInit;
constructor(type, eventInitDict) {
const prefix = "ErrorEvent constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
super(type, eventInitDict);
webidl.util.markAsUncloneable(this);
type = webidl.converters.DOMString(type, prefix, "type");
eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {});
this.#eventInit = eventInitDict;
}
get message() {
webidl.brandCheck(this, _ErrorEvent);
return this.#eventInit.message;
}
get filename() {
webidl.brandCheck(this, _ErrorEvent);
return this.#eventInit.filename;
}
get lineno() {
webidl.brandCheck(this, _ErrorEvent);
return this.#eventInit.lineno;
}
get colno() {
webidl.brandCheck(this, _ErrorEvent);
return this.#eventInit.colno;
}
get error() {
webidl.brandCheck(this, _ErrorEvent);
return this.#eventInit.error;
}
};
Object.defineProperties(MessageEvent.prototype, {
[Symbol.toStringTag]: {
value: "MessageEvent",
configurable: true
},
data: kEnumerableProperty,
origin: kEnumerableProperty,
lastEventId: kEnumerableProperty,
source: kEnumerableProperty,
ports: kEnumerableProperty,
initMessageEvent: kEnumerableProperty
});
Object.defineProperties(CloseEvent.prototype, {
[Symbol.toStringTag]: {
value: "CloseEvent",
configurable: true
},
reason: kEnumerableProperty,
code: kEnumerableProperty,
wasClean: kEnumerableProperty
});
Object.defineProperties(ErrorEvent.prototype, {
[Symbol.toStringTag]: {
value: "ErrorEvent",
configurable: true
},
message: kEnumerableProperty,
filename: kEnumerableProperty,
lineno: kEnumerableProperty,
colno: kEnumerableProperty,
error: kEnumerableProperty
});
webidl.converters.MessagePort = webidl.interfaceConverter(
webidl.is.MessagePort,
"MessagePort"
);
webidl.converters["sequence<MessagePort>"] = webidl.sequenceConverter(
webidl.converters.MessagePort
);
var eventInit = [
{
key: "bubbles",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
},
{
key: "cancelable",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
},
{
key: "composed",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
}
];
webidl.converters.MessageEventInit = webidl.dictionaryConverter([
...eventInit,
{
key: "data",
converter: webidl.converters.any,
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
key: "origin",
converter: webidl.converters.USVString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
},
{
key: "lastEventId",
converter: webidl.converters.DOMString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
},
{
key: "source",
// Node doesn't implement WindowProxy or ServiceWorker, so the only
// valid value for source is a MessagePort.
converter: webidl.nullableConverter(webidl.converters.MessagePort),
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
},
{
key: "ports",
converter: webidl.converters["sequence<MessagePort>"],
defaultValue: /* @__PURE__ */ __name(() => new Array(0), "defaultValue")
}
]);
webidl.converters.CloseEventInit = webidl.dictionaryConverter([
...eventInit,
{
key: "wasClean",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
},
{
key: "code",
converter: webidl.converters["unsigned short"],
defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
},
{
key: "reason",
converter: webidl.converters.USVString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
}
]);
webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
...eventInit,
{
key: "message",
converter: webidl.converters.DOMString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
},
{
key: "filename",
converter: webidl.converters.USVString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
},
{
key: "lineno",
converter: webidl.converters["unsigned long"],
defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
},
{
key: "colno",
converter: webidl.converters["unsigned long"],
defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
},
{
key: "error",
converter: webidl.converters.any
}
]);
module3.exports = {
MessageEvent,
CloseEvent,
ErrorEvent,
createFastMessageEvent
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/constants.js
var require_constants5 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/constants.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var uid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
var staticPropertyDescriptors = {
enumerable: true,
writable: false,
configurable: false
};
var states = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3
};
var sentCloseFrameState = {
SENT: 1,
RECEIVED: 2
};
var opcodes = {
CONTINUATION: 0,
TEXT: 1,
BINARY: 2,
CLOSE: 8,
PING: 9,
PONG: 10
};
var maxUnsigned16Bit = 65535;
var parserStates = {
INFO: 0,
PAYLOADLENGTH_16: 2,
PAYLOADLENGTH_64: 3,
READ_DATA: 4
};
var emptyBuffer = Buffer.allocUnsafe(0);
var sendHints = {
text: 1,
typedArray: 2,
arrayBuffer: 3,
blob: 4
};
module3.exports = {
uid,
sentCloseFrameState,
staticPropertyDescriptors,
states,
opcodes,
maxUnsigned16Bit,
parserStates,
emptyBuffer,
sendHints
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/util.js
var require_util5 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { states, opcodes } = require_constants5();
var { isUtf8 } = require("buffer");
var { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require_data_url();
function isConnecting(readyState) {
return readyState === states.CONNECTING;
}
__name(isConnecting, "isConnecting");
function isEstablished(readyState) {
return readyState === states.OPEN;
}
__name(isEstablished, "isEstablished");
function isClosing(readyState) {
return readyState === states.CLOSING;
}
__name(isClosing, "isClosing");
function isClosed(readyState) {
return readyState === states.CLOSED;
}
__name(isClosed, "isClosed");
function fireEvent(e7, target, eventFactory = (type, init3) => new Event(type, init3), eventInitDict = {}) {
const event = eventFactory(e7, eventInitDict);
target.dispatchEvent(event);
}
__name(fireEvent, "fireEvent");
function websocketMessageReceived(handler, type, data) {
handler.onMessage(type, data);
}
__name(websocketMessageReceived, "websocketMessageReceived");
function toArrayBuffer(buffer) {
if (buffer.byteLength === buffer.buffer.byteLength) {
return buffer.buffer;
}
return new Uint8Array(buffer).buffer;
}
__name(toArrayBuffer, "toArrayBuffer");
function isValidSubprotocol(protocol) {
if (protocol.length === 0) {
return false;
}
for (let i5 = 0; i5 < protocol.length; ++i5) {
const code = protocol.charCodeAt(i5);
if (code < 33 || // CTL, contains SP (0x20) and HT (0x09)
code > 126 || code === 34 || // "
code === 40 || // (
code === 41 || // )
code === 44 || // ,
code === 47 || // /
code === 58 || // :
code === 59 || // ;
code === 60 || // <
code === 61 || // =
code === 62 || // >
code === 63 || // ?
code === 64 || // @
code === 91 || // [
code === 92 || // \
code === 93 || // ]
code === 123 || // {
code === 125) {
return false;
}
}
return true;
}
__name(isValidSubprotocol, "isValidSubprotocol");
function isValidStatusCode(code) {
if (code >= 1e3 && code < 1015) {
return code !== 1004 && // reserved
code !== 1005 && // "MUST NOT be set as a status code"
code !== 1006;
}
return code >= 3e3 && code <= 4999;
}
__name(isValidStatusCode, "isValidStatusCode");
function isControlFrame(opcode) {
return opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG;
}
__name(isControlFrame, "isControlFrame");
function isContinuationFrame(opcode) {
return opcode === opcodes.CONTINUATION;
}
__name(isContinuationFrame, "isContinuationFrame");
function isTextBinaryFrame(opcode) {
return opcode === opcodes.TEXT || opcode === opcodes.BINARY;
}
__name(isTextBinaryFrame, "isTextBinaryFrame");
function isValidOpcode(opcode) {
return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode);
}
__name(isValidOpcode, "isValidOpcode");
function parseExtensions(extensions) {
const position = { position: 0 };
const extensionList = /* @__PURE__ */ new Map();
while (position.position < extensions.length) {
const pair = collectASequenceOfCodePointsFast(";", extensions, position);
const [name2, value = ""] = pair.split("=", 2);
extensionList.set(
removeHTTPWhitespace(name2, true, false),
removeHTTPWhitespace(value, false, true)
);
position.position++;
}
return extensionList;
}
__name(parseExtensions, "parseExtensions");
function isValidClientWindowBits(value) {
for (let i5 = 0; i5 < value.length; i5++) {
const byte = value.charCodeAt(i5);
if (byte < 48 || byte > 57) {
return false;
}
}
return true;
}
__name(isValidClientWindowBits, "isValidClientWindowBits");
function getURLRecord(url4, baseURL) {
let urlRecord;
try {
urlRecord = new URL(url4, baseURL);
} catch (e7) {
throw new DOMException(e7, "SyntaxError");
}
if (urlRecord.protocol === "http:") {
urlRecord.protocol = "ws:";
} else if (urlRecord.protocol === "https:") {
urlRecord.protocol = "wss:";
}
if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") {
throw new DOMException("expected a ws: or wss: url", "SyntaxError");
}
if (urlRecord.hash.length || urlRecord.href.endsWith("#")) {
throw new DOMException("hash", "SyntaxError");
}
return urlRecord;
}
__name(getURLRecord, "getURLRecord");
function validateCloseCodeAndReason(code, reason) {
if (code !== null) {
if (code !== 1e3 && (code < 3e3 || code > 4999)) {
throw new DOMException("invalid code", "InvalidAccessError");
}
}
if (reason !== null) {
const reasonBytesLength = Buffer.byteLength(reason);
if (reasonBytesLength > 123) {
throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, "SyntaxError");
}
}
}
__name(validateCloseCodeAndReason, "validateCloseCodeAndReason");
var utf8Decode = (() => {
if (typeof process.versions.icu === "string") {
const fatalDecoder = new TextDecoder("utf-8", { fatal: true });
return fatalDecoder.decode.bind(fatalDecoder);
}
return function(buffer) {
if (isUtf8(buffer)) {
return buffer.toString("utf-8");
}
throw new TypeError("Invalid utf-8 received.");
};
})();
module3.exports = {
isConnecting,
isEstablished,
isClosing,
isClosed,
fireEvent,
isValidSubprotocol,
isValidStatusCode,
websocketMessageReceived,
utf8Decode,
isControlFrame,
isContinuationFrame,
isTextBinaryFrame,
isValidOpcode,
parseExtensions,
isValidClientWindowBits,
toArrayBuffer,
getURLRecord,
validateCloseCodeAndReason
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/frame.js
var require_frame = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/frame.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { maxUnsigned16Bit, opcodes } = require_constants5();
var BUFFER_SIZE = 8 * 1024;
var crypto8;
var buffer = null;
var bufIdx = BUFFER_SIZE;
try {
crypto8 = require("crypto");
} catch {
crypto8 = {
// not full compatibility, but minimum.
randomFillSync: /* @__PURE__ */ __name(function randomFillSync(buffer2, _offset, _size) {
for (let i5 = 0; i5 < buffer2.length; ++i5) {
buffer2[i5] = Math.random() * 255 | 0;
}
return buffer2;
}, "randomFillSync")
};
}
function generateMask() {
if (bufIdx === BUFFER_SIZE) {
bufIdx = 0;
crypto8.randomFillSync(buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE);
}
return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]];
}
__name(generateMask, "generateMask");
var WebsocketFrameSend = class {
static {
__name(this, "WebsocketFrameSend");
}
/**
* @param {Buffer|undefined} data
*/
constructor(data) {
this.frameData = data;
}
createFrame(opcode) {
const frameData = this.frameData;
const maskKey = generateMask();
const bodyLength = frameData?.byteLength ?? 0;
let payloadLength = bodyLength;
let offset = 6;
if (bodyLength > maxUnsigned16Bit) {
offset += 8;
payloadLength = 127;
} else if (bodyLength > 125) {
offset += 2;
payloadLength = 126;
}
const buffer2 = Buffer.allocUnsafe(bodyLength + offset);
buffer2[0] = buffer2[1] = 0;
buffer2[0] |= 128;
buffer2[0] = (buffer2[0] & 240) + opcode;
buffer2[offset - 4] = maskKey[0];
buffer2[offset - 3] = maskKey[1];
buffer2[offset - 2] = maskKey[2];
buffer2[offset - 1] = maskKey[3];
buffer2[1] = payloadLength;
if (payloadLength === 126) {
buffer2.writeUInt16BE(bodyLength, 2);
} else if (payloadLength === 127) {
buffer2[2] = buffer2[3] = 0;
buffer2.writeUIntBE(bodyLength, 4, 6);
}
buffer2[1] |= 128;
for (let i5 = 0; i5 < bodyLength; ++i5) {
buffer2[offset + i5] = frameData[i5] ^ maskKey[i5 & 3];
}
return buffer2;
}
/**
* @param {Uint8Array} buffer
*/
static createFastTextFrame(buffer2) {
const maskKey = generateMask();
const bodyLength = buffer2.length;
for (let i5 = 0; i5 < bodyLength; ++i5) {
buffer2[i5] ^= maskKey[i5 & 3];
}
let payloadLength = bodyLength;
let offset = 6;
if (bodyLength > maxUnsigned16Bit) {
offset += 8;
payloadLength = 127;
} else if (bodyLength > 125) {
offset += 2;
payloadLength = 126;
}
const head = Buffer.allocUnsafeSlow(offset);
head[0] = 128 | opcodes.TEXT;
head[1] = payloadLength | 128;
head[offset - 4] = maskKey[0];
head[offset - 3] = maskKey[1];
head[offset - 2] = maskKey[2];
head[offset - 1] = maskKey[3];
if (payloadLength === 126) {
head.writeUInt16BE(bodyLength, 2);
} else if (payloadLength === 127) {
head[2] = head[3] = 0;
head.writeUIntBE(bodyLength, 4, 6);
}
return [head, buffer2];
}
};
module3.exports = {
WebsocketFrameSend,
generateMask
// for benchmark
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/connection.js
var require_connection = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/connection.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants5();
var { parseExtensions, isClosed, isClosing, isEstablished, validateCloseCodeAndReason } = require_util5();
var { channels } = require_diagnostics();
var { makeRequest } = require_request2();
var { fetching } = require_fetch();
var { Headers: Headers5, getHeadersList } = require_headers();
var { getDecodeSplit } = require_util2();
var { WebsocketFrameSend } = require_frame();
var assert44 = require("assert");
var crypto8;
try {
crypto8 = require("crypto");
} catch {
}
function establishWebSocketConnection(url4, protocols, client, handler, options) {
const requestURL = url4;
requestURL.protocol = url4.protocol === "ws:" ? "http:" : "https:";
const request4 = makeRequest({
urlList: [requestURL],
client,
serviceWorkers: "none",
referrer: "no-referrer",
mode: "websocket",
credentials: "include",
cache: "no-store",
redirect: "error"
});
if (options.headers) {
const headersList = getHeadersList(new Headers5(options.headers));
request4.headersList = headersList;
}
const keyValue = crypto8.randomBytes(16).toString("base64");
request4.headersList.append("sec-websocket-key", keyValue, true);
request4.headersList.append("sec-websocket-version", "13", true);
for (const protocol of protocols) {
request4.headersList.append("sec-websocket-protocol", protocol, true);
}
const permessageDeflate = "permessage-deflate; client_max_window_bits";
request4.headersList.append("sec-websocket-extensions", permessageDeflate, true);
const controller = fetching({
request: request4,
useParallelQueue: true,
dispatcher: options.dispatcher,
processResponse(response) {
if (response.type === "error") {
handler.readyState = states.CLOSED;
}
if (response.type === "error" || response.status !== 101) {
failWebsocketConnection(handler, 1002, "Received network error or non-101 status code.", response.error);
return;
}
if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
failWebsocketConnection(handler, 1002, "Server did not respond with sent protocols.");
return;
}
if (response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".');
return;
}
if (response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".');
return;
}
const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
const digest = crypto8.createHash("sha1").update(keyValue + uid).digest("base64");
if (secWSAccept !== digest) {
failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
return;
}
const secExtension = response.headersList.get("Sec-WebSocket-Extensions");
let extensions;
if (secExtension !== null) {
extensions = parseExtensions(secExtension);
if (!extensions.has("permessage-deflate")) {
failWebsocketConnection(handler, 1002, "Sec-WebSocket-Extensions header does not match.");
return;
}
}
const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
if (secProtocol !== null) {
const requestProtocols = getDecodeSplit("sec-websocket-protocol", request4.headersList);
if (!requestProtocols.includes(secProtocol)) {
failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
return;
}
}
response.socket.on("data", handler.onSocketData);
response.socket.on("close", handler.onSocketClose);
response.socket.on("error", handler.onSocketError);
if (channels.open.hasSubscribers) {
channels.open.publish({
address: response.socket.address(),
protocol: secProtocol,
extensions: secExtension
});
}
handler.wasEverConnected = true;
handler.onConnectionEstablished(response, extensions);
}
});
return controller;
}
__name(establishWebSocketConnection, "establishWebSocketConnection");
function closeWebSocketConnection(object, code, reason, validate3 = false) {
code ??= null;
reason ??= "";
if (validate3) validateCloseCodeAndReason(code, reason);
if (isClosed(object.readyState) || isClosing(object.readyState)) {
} else if (!isEstablished(object.readyState)) {
failWebsocketConnection(object);
object.readyState = states.CLOSING;
} else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) {
const frame = new WebsocketFrameSend();
if (reason.length !== 0 && code === null) {
code = 1e3;
}
assert44(code === null || Number.isInteger(code));
if (code === null && reason.length === 0) {
frame.frameData = emptyBuffer;
} else if (code !== null && reason === null) {
frame.frameData = Buffer.allocUnsafe(2);
frame.frameData.writeUInt16BE(code, 0);
} else if (code !== null && reason !== null) {
frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));
frame.frameData.writeUInt16BE(code, 0);
frame.frameData.write(reason, 2, "utf-8");
} else {
frame.frameData = emptyBuffer;
}
object.socket.write(frame.createFrame(opcodes.CLOSE));
object.closeState.add(sentCloseFrameState.SENT);
object.readyState = states.CLOSING;
} else {
object.readyState = states.CLOSING;
}
}
__name(closeWebSocketConnection, "closeWebSocketConnection");
function failWebsocketConnection(handler, code, reason, cause) {
if (isEstablished(handler.readyState)) {
closeWebSocketConnection(handler, code, reason, false);
}
handler.controller.abort();
if (handler.socket?.destroyed === false) {
handler.socket.destroy();
}
handler.onFail(code, reason, cause);
}
__name(failWebsocketConnection, "failWebsocketConnection");
module3.exports = {
establishWebSocketConnection,
failWebsocketConnection,
closeWebSocketConnection
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require("zlib");
var { isValidClientWindowBits } = require_util5();
var tail = Buffer.from([0, 0, 255, 255]);
var kBuffer = Symbol("kBuffer");
var kLength = Symbol("kLength");
var PerMessageDeflate = class {
static {
__name(this, "PerMessageDeflate");
}
/** @type {import('node:zlib').InflateRaw} */
#inflate;
#options = {};
constructor(extensions) {
this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
}
decompress(chunk, fin, callback) {
if (!this.#inflate) {
let windowBits = Z_DEFAULT_WINDOWBITS;
if (this.#options.serverMaxWindowBits) {
if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
callback(new Error("Invalid server_max_window_bits"));
return;
}
windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
}
this.#inflate = createInflateRaw({ windowBits });
this.#inflate[kBuffer] = [];
this.#inflate[kLength] = 0;
this.#inflate.on("data", (data) => {
this.#inflate[kBuffer].push(data);
this.#inflate[kLength] += data.length;
});
this.#inflate.on("error", (err) => {
this.#inflate = null;
callback(err);
});
}
this.#inflate.write(chunk);
if (fin) {
this.#inflate.write(tail);
}
this.#inflate.flush(() => {
const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
this.#inflate[kBuffer].length = 0;
this.#inflate[kLength] = 0;
callback(null, full);
});
}
};
module3.exports = { PerMessageDeflate };
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/receiver.js
var require_receiver = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/receiver.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Writable: Writable5 } = require("stream");
var assert44 = require("assert");
var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants5();
var { channels } = require_diagnostics();
var {
isValidStatusCode,
isValidOpcode,
websocketMessageReceived,
utf8Decode,
isControlFrame,
isTextBinaryFrame,
isContinuationFrame
} = require_util5();
var { failWebsocketConnection } = require_connection();
var { WebsocketFrameSend } = require_frame();
var { PerMessageDeflate } = require_permessage_deflate();
var ByteParser = class extends Writable5 {
static {
__name(this, "ByteParser");
}
#buffers = [];
#fragmentsBytes = 0;
#byteOffset = 0;
#loop = false;
#state = parserStates.INFO;
#info = {};
#fragments = [];
/** @type {Map<string, PerMessageDeflate>} */
#extensions;
/** @type {import('./websocket').Handler} */
#handler;
constructor(handler, extensions) {
super();
this.#handler = handler;
this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
if (this.#extensions.has("permessage-deflate")) {
this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions));
}
}
/**
* @param {Buffer} chunk
* @param {() => void} callback
*/
_write(chunk, _4, callback) {
this.#buffers.push(chunk);
this.#byteOffset += chunk.length;
this.#loop = true;
this.run(callback);
}
/**
* Runs whenever a new chunk is received.
* Callback is called whenever there are no more chunks buffering,
* or not enough bytes are buffered to parse.
*/
run(callback) {
while (this.#loop) {
if (this.#state === parserStates.INFO) {
if (this.#byteOffset < 2) {
return callback();
}
const buffer = this.consume(2);
const fin = (buffer[0] & 128) !== 0;
const opcode = buffer[0] & 15;
const masked = (buffer[1] & 128) === 128;
const fragmented = !fin && opcode !== opcodes.CONTINUATION;
const payloadLength = buffer[1] & 127;
const rsv1 = buffer[0] & 64;
const rsv2 = buffer[0] & 32;
const rsv3 = buffer[0] & 16;
if (!isValidOpcode(opcode)) {
failWebsocketConnection(this.#handler, 1002, "Invalid opcode received");
return callback();
}
if (masked) {
failWebsocketConnection(this.#handler, 1002, "Frame cannot be masked");
return callback();
}
if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
failWebsocketConnection(this.#handler, 1002, "Expected RSV1 to be clear.");
return;
}
if (rsv2 !== 0 || rsv3 !== 0) {
failWebsocketConnection(this.#handler, 1002, "RSV1, RSV2, RSV3 must be clear");
return;
}
if (fragmented && !isTextBinaryFrame(opcode)) {
failWebsocketConnection(this.#handler, 1002, "Invalid frame type was fragmented.");
return;
}
if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
failWebsocketConnection(this.#handler, 1002, "Expected continuation frame");
return;
}
if (this.#info.fragmented && fragmented) {
failWebsocketConnection(this.#handler, 1002, "Fragmented frame exceeded 125 bytes.");
return;
}
if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
failWebsocketConnection(this.#handler, 1002, "Control frame either too large or fragmented");
return;
}
if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
failWebsocketConnection(this.#handler, 1002, "Unexpected continuation frame");
return;
}
if (payloadLength <= 125) {
this.#info.payloadLength = payloadLength;
this.#state = parserStates.READ_DATA;
} else if (payloadLength === 126) {
this.#state = parserStates.PAYLOADLENGTH_16;
} else if (payloadLength === 127) {
this.#state = parserStates.PAYLOADLENGTH_64;
}
if (isTextBinaryFrame(opcode)) {
this.#info.binaryType = opcode;
this.#info.compressed = rsv1 !== 0;
}
this.#info.opcode = opcode;
this.#info.masked = masked;
this.#info.fin = fin;
this.#info.fragmented = fragmented;
} else if (this.#state === parserStates.PAYLOADLENGTH_16) {
if (this.#byteOffset < 2) {
return callback();
}
const buffer = this.consume(2);
this.#info.payloadLength = buffer.readUInt16BE(0);
this.#state = parserStates.READ_DATA;
} else if (this.#state === parserStates.PAYLOADLENGTH_64) {
if (this.#byteOffset < 8) {
return callback();
}
const buffer = this.consume(8);
const upper = buffer.readUInt32BE(0);
if (upper > 2 ** 31 - 1) {
failWebsocketConnection(this.#handler, 1009, "Received payload length > 2^31 bytes.");
return;
}
const lower = buffer.readUInt32BE(4);
this.#info.payloadLength = (upper << 8) + lower;
this.#state = parserStates.READ_DATA;
} else if (this.#state === parserStates.READ_DATA) {
if (this.#byteOffset < this.#info.payloadLength) {
return callback();
}
const body = this.consume(this.#info.payloadLength);
if (isControlFrame(this.#info.opcode)) {
this.#loop = this.parseControlFrame(body);
this.#state = parserStates.INFO;
} else {
if (!this.#info.compressed) {
this.writeFragments(body);
if (!this.#info.fragmented && this.#info.fin) {
websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
}
this.#state = parserStates.INFO;
} else {
this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => {
if (error2) {
failWebsocketConnection(this.#handler, 1007, error2.message);
return;
}
this.writeFragments(data);
if (!this.#info.fin) {
this.#state = parserStates.INFO;
this.#loop = true;
this.run(callback);
return;
}
websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
this.#loop = true;
this.#state = parserStates.INFO;
this.run(callback);
});
this.#loop = false;
break;
}
}
}
}
}
/**
* Take n bytes from the buffered Buffers
* @param {number} n
* @returns {Buffer}
*/
consume(n6) {
if (n6 > this.#byteOffset) {
throw new Error("Called consume() before buffers satiated.");
} else if (n6 === 0) {
return emptyBuffer;
}
this.#byteOffset -= n6;
const first = this.#buffers[0];
if (first.length > n6) {
this.#buffers[0] = first.subarray(n6, first.length);
return first.subarray(0, n6);
} else if (first.length === n6) {
return this.#buffers.shift();
} else {
let offset = 0;
const buffer = Buffer.allocUnsafeSlow(n6);
while (offset !== n6) {
const next = this.#buffers[0];
const length = next.length;
if (length + offset === n6) {
buffer.set(this.#buffers.shift(), offset);
break;
} else if (length + offset > n6) {
buffer.set(next.subarray(0, n6 - offset), offset);
this.#buffers[0] = next.subarray(n6 - offset);
break;
} else {
buffer.set(this.#buffers.shift(), offset);
offset += length;
}
}
return buffer;
}
}
writeFragments(fragment) {
this.#fragmentsBytes += fragment.length;
this.#fragments.push(fragment);
}
consumeFragments() {
const fragments = this.#fragments;
if (fragments.length === 1) {
this.#fragmentsBytes = 0;
return fragments.shift();
}
let offset = 0;
const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes);
for (let i5 = 0; i5 < fragments.length; ++i5) {
const buffer = fragments[i5];
output.set(buffer, offset);
offset += buffer.length;
}
this.#fragments = [];
this.#fragmentsBytes = 0;
return output;
}
parseCloseBody(data) {
assert44(data.length !== 1);
let code;
if (data.length >= 2) {
code = data.readUInt16BE(0);
}
if (code !== void 0 && !isValidStatusCode(code)) {
return { code: 1002, reason: "Invalid status code", error: true };
}
let reason = data.subarray(2);
if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) {
reason = reason.subarray(3);
}
try {
reason = utf8Decode(reason);
} catch {
return { code: 1007, reason: "Invalid UTF-8", error: true };
}
return { code, reason, error: false };
}
/**
* Parses control frames.
* @param {Buffer} body
*/
parseControlFrame(body) {
const { opcode, payloadLength } = this.#info;
if (opcode === opcodes.CLOSE) {
if (payloadLength === 1) {
failWebsocketConnection(this.#handler, 1002, "Received close frame with a 1-byte body.");
return false;
}
this.#info.closeInfo = this.parseCloseBody(body);
if (this.#info.closeInfo.error) {
const { code, reason } = this.#info.closeInfo;
failWebsocketConnection(this.#handler, code, reason);
return false;
}
if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
let body2 = emptyBuffer;
if (this.#info.closeInfo.code) {
body2 = Buffer.allocUnsafe(2);
body2.writeUInt16BE(this.#info.closeInfo.code, 0);
}
const closeFrame = new WebsocketFrameSend(body2);
this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));
this.#handler.closeState.add(sentCloseFrameState.SENT);
}
this.#handler.readyState = states.CLOSING;
this.#handler.closeState.add(sentCloseFrameState.RECEIVED);
return false;
} else if (opcode === opcodes.PING) {
if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
const frame = new WebsocketFrameSend(body);
this.#handler.socket.write(frame.createFrame(opcodes.PONG));
if (channels.ping.hasSubscribers) {
channels.ping.publish({
payload: body
});
}
}
} else if (opcode === opcodes.PONG) {
if (channels.pong.hasSubscribers) {
channels.pong.publish({
payload: body
});
}
}
return true;
}
get closingInfo() {
return this.#info.closeInfo;
}
};
module3.exports = {
ByteParser
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/sender.js
var require_sender = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/sender.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { WebsocketFrameSend } = require_frame();
var { opcodes, sendHints } = require_constants5();
var FixedQueue = require_fixed_queue();
var SendQueue = class {
static {
__name(this, "SendQueue");
}
/**
* @type {FixedQueue}
*/
#queue = new FixedQueue();
/**
* @type {boolean}
*/
#running = false;
/** @type {import('node:net').Socket} */
#socket;
constructor(socket) {
this.#socket = socket;
}
add(item, cb2, hint) {
if (hint !== sendHints.blob) {
if (!this.#running) {
if (hint === sendHints.text) {
const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item);
this.#socket.cork();
this.#socket.write(head);
this.#socket.write(body, cb2);
this.#socket.uncork();
} else {
this.#socket.write(createFrame(item, hint), cb2);
}
} else {
const node3 = {
promise: null,
callback: cb2,
frame: createFrame(item, hint)
};
this.#queue.push(node3);
}
return;
}
const node2 = {
promise: item.arrayBuffer().then((ab2) => {
node2.promise = null;
node2.frame = createFrame(ab2, hint);
}),
callback: cb2,
frame: null
};
this.#queue.push(node2);
if (!this.#running) {
this.#run();
}
}
async #run() {
this.#running = true;
const queue = this.#queue;
while (!queue.isEmpty()) {
const node2 = queue.shift();
if (node2.promise !== null) {
await node2.promise;
}
this.#socket.write(node2.frame, node2.callback);
node2.callback = node2.frame = null;
}
this.#running = false;
}
};
function createFrame(data, hint) {
return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY);
}
__name(createFrame, "createFrame");
function toBuffer(data, hint) {
switch (hint) {
case sendHints.text:
case sendHints.typedArray:
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
case sendHints.arrayBuffer:
case sendHints.blob:
return new Uint8Array(data);
}
}
__name(toBuffer, "toBuffer");
module3.exports = { SendQueue };
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/websocket.js
var require_websocket = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/websocket.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { webidl } = require_webidl();
var { URLSerializer } = require_data_url();
var { environmentSettingsObject } = require_util2();
var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require_constants5();
var {
isConnecting,
isEstablished,
isClosing,
isValidSubprotocol,
fireEvent,
utf8Decode,
toArrayBuffer,
getURLRecord
} = require_util5();
var { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require_connection();
var { ByteParser } = require_receiver();
var { kEnumerableProperty } = require_util();
var { getGlobalDispatcher: getGlobalDispatcher2 } = require_global2();
var { types: types3 } = require("util");
var { ErrorEvent, CloseEvent, createFastMessageEvent } = require_events();
var { SendQueue } = require_sender();
var { channels } = require_diagnostics();
var WebSocket2 = class _WebSocket extends EventTarget {
static {
__name(this, "WebSocket");
}
#events = {
open: null,
error: null,
close: null,
message: null
};
#bufferedAmount = 0;
#protocol = "";
#extensions = "";
/** @type {SendQueue} */
#sendQueue;
/** @type {Handler} */
#handler = {
onConnectionEstablished: /* @__PURE__ */ __name((response, extensions) => this.#onConnectionEstablished(response, extensions), "onConnectionEstablished"),
onFail: /* @__PURE__ */ __name((code, reason, cause) => this.#onFail(code, reason, cause), "onFail"),
onMessage: /* @__PURE__ */ __name((opcode, data) => this.#onMessage(opcode, data), "onMessage"),
onParserError: /* @__PURE__ */ __name((err) => failWebsocketConnection(this.#handler, null, err.message), "onParserError"),
onParserDrain: /* @__PURE__ */ __name(() => this.#onParserDrain(), "onParserDrain"),
onSocketData: /* @__PURE__ */ __name((chunk) => {
if (!this.#parser.write(chunk)) {
this.#handler.socket.pause();
}
}, "onSocketData"),
onSocketError: /* @__PURE__ */ __name((err) => {
this.#handler.readyState = states.CLOSING;
if (channels.socketError.hasSubscribers) {
channels.socketError.publish(err);
}
this.#handler.socket.destroy();
}, "onSocketError"),
onSocketClose: /* @__PURE__ */ __name(() => this.#onSocketClose(), "onSocketClose"),
readyState: states.CONNECTING,
socket: null,
closeState: /* @__PURE__ */ new Set(),
controller: null,
wasEverConnected: false
};
#url;
#binaryType;
/** @type {import('./receiver').ByteParser} */
#parser;
/**
* @param {string} url
* @param {string|string[]} protocols
*/
constructor(url4, protocols = []) {
super();
webidl.util.markAsUncloneable(this);
const prefix = "WebSocket constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
const options = webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"](protocols, prefix, "options");
url4 = webidl.converters.USVString(url4);
protocols = options.protocols;
const baseURL = environmentSettingsObject.settingsObject.baseUrl;
const urlRecord = getURLRecord(url4, baseURL);
if (typeof protocols === "string") {
protocols = [protocols];
}
if (protocols.length !== new Set(protocols.map((p6) => p6.toLowerCase())).size) {
throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
}
if (protocols.length > 0 && !protocols.every((p6) => isValidSubprotocol(p6))) {
throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
}
this.#url = new URL(urlRecord.href);
const client = environmentSettingsObject.settingsObject;
this.#handler.controller = establishWebSocketConnection(
urlRecord,
protocols,
client,
this.#handler,
options
);
this.#handler.readyState = _WebSocket.CONNECTING;
this.#binaryType = "blob";
}
/**
* @see https://websockets.spec.whatwg.org/#dom-websocket-close
* @param {number|undefined} code
* @param {string|undefined} reason
*/
close(code = void 0, reason = void 0) {
webidl.brandCheck(this, _WebSocket);
const prefix = "WebSocket.close";
if (code !== void 0) {
code = webidl.converters["unsigned short"](code, prefix, "code", { clamp: true });
}
if (reason !== void 0) {
reason = webidl.converters.USVString(reason);
}
code ??= null;
reason ??= "";
closeWebSocketConnection(this.#handler, code, reason, true);
}
/**
* @see https://websockets.spec.whatwg.org/#dom-websocket-send
* @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
*/
send(data) {
webidl.brandCheck(this, _WebSocket);
const prefix = "WebSocket.send";
webidl.argumentLengthCheck(arguments, 1, prefix);
data = webidl.converters.WebSocketSendData(data, prefix, "data");
if (isConnecting(this.#handler.readyState)) {
throw new DOMException("Sent before connected.", "InvalidStateError");
}
if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) {
return;
}
if (typeof data === "string") {
const buffer = Buffer.from(data);
this.#bufferedAmount += buffer.byteLength;
this.#sendQueue.add(buffer, () => {
this.#bufferedAmount -= buffer.byteLength;
}, sendHints.text);
} else if (types3.isArrayBuffer(data)) {
this.#bufferedAmount += data.byteLength;
this.#sendQueue.add(data, () => {
this.#bufferedAmount -= data.byteLength;
}, sendHints.arrayBuffer);
} else if (ArrayBuffer.isView(data)) {
this.#bufferedAmount += data.byteLength;
this.#sendQueue.add(data, () => {
this.#bufferedAmount -= data.byteLength;
}, sendHints.typedArray);
} else if (webidl.is.Blob(data)) {
this.#bufferedAmount += data.size;
this.#sendQueue.add(data, () => {
this.#bufferedAmount -= data.size;
}, sendHints.blob);
}
}
get readyState() {
webidl.brandCheck(this, _WebSocket);
return this.#handler.readyState;
}
get bufferedAmount() {
webidl.brandCheck(this, _WebSocket);
return this.#bufferedAmount;
}
get url() {
webidl.brandCheck(this, _WebSocket);
return URLSerializer(this.#url);
}
get extensions() {
webidl.brandCheck(this, _WebSocket);
return this.#extensions;
}
get protocol() {
webidl.brandCheck(this, _WebSocket);
return this.#protocol;
}
get onopen() {
webidl.brandCheck(this, _WebSocket);
return this.#events.open;
}
set onopen(fn2) {
webidl.brandCheck(this, _WebSocket);
if (this.#events.open) {
this.removeEventListener("open", this.#events.open);
}
if (typeof fn2 === "function") {
this.#events.open = fn2;
this.addEventListener("open", fn2);
} else {
this.#events.open = null;
}
}
get onerror() {
webidl.brandCheck(this, _WebSocket);
return this.#events.error;
}
set onerror(fn2) {
webidl.brandCheck(this, _WebSocket);
if (this.#events.error) {
this.removeEventListener("error", this.#events.error);
}
if (typeof fn2 === "function") {
this.#events.error = fn2;
this.addEventListener("error", fn2);
} else {
this.#events.error = null;
}
}
get onclose() {
webidl.brandCheck(this, _WebSocket);
return this.#events.close;
}
set onclose(fn2) {
webidl.brandCheck(this, _WebSocket);
if (this.#events.close) {
this.removeEventListener("close", this.#events.close);
}
if (typeof fn2 === "function") {
this.#events.close = fn2;
this.addEventListener("close", fn2);
} else {
this.#events.close = null;
}
}
get onmessage() {
webidl.brandCheck(this, _WebSocket);
return this.#events.message;
}
set onmessage(fn2) {
webidl.brandCheck(this, _WebSocket);
if (this.#events.message) {
this.removeEventListener("message", this.#events.message);
}
if (typeof fn2 === "function") {
this.#events.message = fn2;
this.addEventListener("message", fn2);
} else {
this.#events.message = null;
}
}
get binaryType() {
webidl.brandCheck(this, _WebSocket);
return this.#binaryType;
}
set binaryType(type) {
webidl.brandCheck(this, _WebSocket);
if (type !== "blob" && type !== "arraybuffer") {
this.#binaryType = "blob";
} else {
this.#binaryType = type;
}
}
/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
*/
#onConnectionEstablished(response, parsedExtensions) {
this.#handler.socket = response.socket;
const parser2 = new ByteParser(this.#handler, parsedExtensions);
parser2.on("drain", () => this.#handler.onParserDrain());
parser2.on("error", (err) => this.#handler.onParserError(err));
this.#parser = parser2;
this.#sendQueue = new SendQueue(response.socket);
this.#handler.readyState = states.OPEN;
const extensions = response.headersList.get("sec-websocket-extensions");
if (extensions !== null) {
this.#extensions = extensions;
}
const protocol = response.headersList.get("sec-websocket-protocol");
if (protocol !== null) {
this.#protocol = protocol;
}
fireEvent("open", this);
}
#onFail(code, reason, cause) {
if (reason) {
fireEvent("error", this, (type, init3) => new ErrorEvent(type, init3), {
error: new Error(reason, cause ? { cause } : void 0),
message: reason
});
}
if (!this.#handler.wasEverConnected) {
this.#handler.readyState = states.CLOSED;
fireEvent("close", this, (type, init3) => new CloseEvent(type, init3), {
wasClean: false,
code,
reason
});
}
}
#onMessage(type, data) {
if (this.#handler.readyState !== states.OPEN) {
return;
}
let dataForEvent;
if (type === opcodes.TEXT) {
try {
dataForEvent = utf8Decode(data);
} catch {
failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
return;
}
} else if (type === opcodes.BINARY) {
if (this.#binaryType === "blob") {
dataForEvent = new Blob([data]);
} else {
dataForEvent = toArrayBuffer(data);
}
}
fireEvent("message", this, createFastMessageEvent, {
origin: this.#url.origin,
data: dataForEvent
});
}
#onParserDrain() {
this.#handler.socket.resume();
}
/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
*/
#onSocketClose() {
const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
let code = 1005;
let reason = "";
const result = this.#parser.closingInfo;
if (result && !result.error) {
code = result.code ?? 1005;
reason = result.reason;
} else if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
code = 1006;
}
this.#handler.readyState = states.CLOSED;
fireEvent("close", this, (type, init3) => new CloseEvent(type, init3), {
wasClean,
code,
reason
});
if (channels.close.hasSubscribers) {
channels.close.publish({
websocket: this,
code,
reason
});
}
}
};
WebSocket2.CONNECTING = WebSocket2.prototype.CONNECTING = states.CONNECTING;
WebSocket2.OPEN = WebSocket2.prototype.OPEN = states.OPEN;
WebSocket2.CLOSING = WebSocket2.prototype.CLOSING = states.CLOSING;
WebSocket2.CLOSED = WebSocket2.prototype.CLOSED = states.CLOSED;
Object.defineProperties(WebSocket2.prototype, {
CONNECTING: staticPropertyDescriptors,
OPEN: staticPropertyDescriptors,
CLOSING: staticPropertyDescriptors,
CLOSED: staticPropertyDescriptors,
url: kEnumerableProperty,
readyState: kEnumerableProperty,
bufferedAmount: kEnumerableProperty,
onopen: kEnumerableProperty,
onerror: kEnumerableProperty,
onclose: kEnumerableProperty,
close: kEnumerableProperty,
onmessage: kEnumerableProperty,
binaryType: kEnumerableProperty,
send: kEnumerableProperty,
extensions: kEnumerableProperty,
protocol: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "WebSocket",
writable: false,
enumerable: false,
configurable: true
}
});
Object.defineProperties(WebSocket2, {
CONNECTING: staticPropertyDescriptors,
OPEN: staticPropertyDescriptors,
CLOSING: staticPropertyDescriptors,
CLOSED: staticPropertyDescriptors
});
webidl.converters["sequence<DOMString>"] = webidl.sequenceConverter(
webidl.converters.DOMString
);
webidl.converters["DOMString or sequence<DOMString>"] = function(V3, prefix, argument) {
if (webidl.util.Type(V3) === webidl.util.Types.OBJECT && Symbol.iterator in V3) {
return webidl.converters["sequence<DOMString>"](V3);
}
return webidl.converters.DOMString(V3, prefix, argument);
};
webidl.converters.WebSocketInit = webidl.dictionaryConverter([
{
key: "protocols",
converter: webidl.converters["DOMString or sequence<DOMString>"],
defaultValue: /* @__PURE__ */ __name(() => new Array(0), "defaultValue")
},
{
key: "dispatcher",
converter: webidl.converters.any,
defaultValue: /* @__PURE__ */ __name(() => getGlobalDispatcher2(), "defaultValue")
},
{
key: "headers",
converter: webidl.nullableConverter(webidl.converters.HeadersInit)
}
]);
webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"] = function(V3) {
if (webidl.util.Type(V3) === webidl.util.Types.OBJECT && !(Symbol.iterator in V3)) {
return webidl.converters.WebSocketInit(V3);
}
return { protocols: webidl.converters["DOMString or sequence<DOMString>"](V3) };
};
webidl.converters.WebSocketSendData = function(V3) {
if (webidl.util.Type(V3) === webidl.util.Types.OBJECT) {
if (webidl.is.Blob(V3)) {
return V3;
}
if (ArrayBuffer.isView(V3) || types3.isArrayBuffer(V3)) {
return V3;
}
}
return webidl.converters.USVString(V3);
};
module3.exports = {
WebSocket: WebSocket2
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/stream/websocketerror.js
var require_websocketerror = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { webidl } = require_webidl();
var { validateCloseCodeAndReason } = require_util5();
var { kConstruct } = require_symbols();
var { kEnumerableProperty } = require_util();
var WebSocketError = class _WebSocketError extends DOMException {
static {
__name(this, "WebSocketError");
}
#closeCode;
#reason;
constructor(message = "", init3 = void 0) {
message = webidl.converters.DOMString(message, "WebSocketError", "message");
super(message, "WebSocketError");
if (init3 === kConstruct) {
return;
} else if (init3 !== null) {
init3 = webidl.converters.WebSocketCloseInfo(init3);
}
let code = init3.closeCode ?? null;
const reason = init3.reason ?? "";
validateCloseCodeAndReason(code, reason);
if (reason.length !== 0 && code === null) {
code = 1e3;
}
this.#closeCode = code;
this.#reason = reason;
}
get closeCode() {
return this.#closeCode;
}
get reason() {
return this.#reason;
}
/**
* @param {string} message
* @param {number|null} code
* @param {string} reason
*/
static createUnvalidatedWebSocketError(message, code, reason) {
const error2 = new _WebSocketError(message, kConstruct);
error2.#closeCode = code;
error2.#reason = reason;
return error2;
}
};
var { createUnvalidatedWebSocketError } = WebSocketError;
delete WebSocketError.createUnvalidatedWebSocketError;
Object.defineProperties(WebSocketError.prototype, {
closeCode: kEnumerableProperty,
reason: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "WebSocketError",
writable: false,
enumerable: false,
configurable: true
}
});
webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError);
module3.exports = { WebSocketError, createUnvalidatedWebSocketError };
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/stream/websocketstream.js
var require_websocketstream = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { createDeferredPromise, environmentSettingsObject } = require_util2();
var { states, opcodes, sentCloseFrameState } = require_constants5();
var { webidl } = require_webidl();
var { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util5();
var { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection();
var { types: types3 } = require("util");
var { channels } = require_diagnostics();
var { WebsocketFrameSend } = require_frame();
var { ByteParser } = require_receiver();
var { WebSocketError, createUnvalidatedWebSocketError } = require_websocketerror();
var { utf8DecodeBytes } = require_util2();
var { kEnumerableProperty } = require_util();
var emittedExperimentalWarning = false;
var WebSocketStream = class {
static {
__name(this, "WebSocketStream");
}
// Each WebSocketStream object has an associated url , which is a URL record .
/** @type {URL} */
#url;
// Each WebSocketStream object has an associated opened promise , which is a promise.
/** @type {ReturnType<typeof createDeferredPromise>} */
#openedPromise;
// Each WebSocketStream object has an associated closed promise , which is a promise.
/** @type {ReturnType<typeof createDeferredPromise>} */
#closedPromise;
// Each WebSocketStream object has an associated readable stream , which is a ReadableStream .
/** @type {ReadableStream} */
#readableStream;
/** @type {ReadableStreamDefaultController} */
#readableStreamController;
// Each WebSocketStream object has an associated writable stream , which is a WritableStream .
/** @type {WritableStream} */
#writableStream;
// Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
#handshakeAborted = false;
/** @type {import('../websocket').Handler} */
#handler = {
// https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol
onConnectionEstablished: /* @__PURE__ */ __name((response, extensions) => this.#onConnectionEstablished(response, extensions), "onConnectionEstablished"),
onFail: /* @__PURE__ */ __name((_code, _reason) => {
}, "onFail"),
onMessage: /* @__PURE__ */ __name((opcode, data) => this.#onMessage(opcode, data), "onMessage"),
onParserError: /* @__PURE__ */ __name((err) => failWebsocketConnection(this.#handler, null, err.message), "onParserError"),
onParserDrain: /* @__PURE__ */ __name(() => this.#handler.socket.resume(), "onParserDrain"),
onSocketData: /* @__PURE__ */ __name((chunk) => {
if (!this.#parser.write(chunk)) {
this.#handler.socket.pause();
}
}, "onSocketData"),
onSocketError: /* @__PURE__ */ __name((err) => {
this.#handler.readyState = states.CLOSING;
if (channels.socketError.hasSubscribers) {
channels.socketError.publish(err);
}
this.#handler.socket.destroy();
}, "onSocketError"),
onSocketClose: /* @__PURE__ */ __name(() => this.#onSocketClose(), "onSocketClose"),
readyState: states.CONNECTING,
socket: null,
closeState: /* @__PURE__ */ new Set(),
controller: null,
wasEverConnected: false
};
/** @type {import('../receiver').ByteParser} */
#parser;
constructor(url4, options = void 0) {
if (!emittedExperimentalWarning) {
process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.", {
code: "UNDICI-WSS"
});
emittedExperimentalWarning = true;
}
webidl.argumentLengthCheck(arguments, 1, "WebSocket");
url4 = webidl.converters.USVString(url4);
if (options !== null) {
options = webidl.converters.WebSocketStreamOptions(options);
}
const baseURL = environmentSettingsObject.settingsObject.baseUrl;
const urlRecord = getURLRecord(url4, baseURL);
const protocols = options.protocols;
if (protocols.length !== new Set(protocols.map((p6) => p6.toLowerCase())).size) {
throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
}
if (protocols.length > 0 && !protocols.every((p6) => isValidSubprotocol(p6))) {
throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
}
this.#url = urlRecord.toString();
this.#openedPromise = createDeferredPromise();
this.#closedPromise = createDeferredPromise();
if (options.signal != null) {
const signal = options.signal;
if (signal.aborted) {
this.#openedPromise.reject(signal.reason);
this.#closedPromise.reject(signal.reason);
return;
}
signal.addEventListener("abort", () => {
if (!isEstablished(this.#handler.readyState)) {
failWebsocketConnection(this.#handler);
this.#handler.readyState = states.CLOSING;
this.#openedPromise.reject(signal.reason);
this.#closedPromise.reject(signal.reason);
this.#handshakeAborted = true;
}
}, { once: true });
}
const client = environmentSettingsObject.settingsObject;
this.#handler.controller = establishWebSocketConnection(
urlRecord,
protocols,
client,
this.#handler,
options
);
}
// The url getter steps are to return this 's url , serialized .
get url() {
return this.#url.toString();
}
// The opened getter steps are to return this 's opened promise .
get opened() {
return this.#openedPromise.promise;
}
// The closed getter steps are to return this 's closed promise .
get closed() {
return this.#closedPromise.promise;
}
// The close( closeInfo ) method steps are:
close(closeInfo = void 0) {
if (closeInfo !== null) {
closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo);
}
const code = closeInfo.closeCode ?? null;
const reason = closeInfo.reason;
closeWebSocketConnection(this.#handler, code, reason, true);
}
#write(chunk) {
const promise = createDeferredPromise();
let data = null;
let opcode = null;
if (ArrayBuffer.isView(chunk) || types3.isArrayBuffer(chunk)) {
data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk);
opcode = opcodes.BINARY;
} else {
let string;
try {
string = webidl.converters.DOMString(chunk);
} catch (e7) {
promise.reject(e7);
return;
}
data = new TextEncoder().encode(string);
opcode = opcodes.TEXT;
}
if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
const frame = new WebsocketFrameSend(data);
this.#handler.socket.write(frame.createFrame(opcode), () => {
promise.resolve(void 0);
});
}
return promise;
}
/** @type {import('../websocket').Handler['onConnectionEstablished']} */
#onConnectionEstablished(response, parsedExtensions) {
this.#handler.socket = response.socket;
const parser2 = new ByteParser(this.#handler, parsedExtensions);
parser2.on("drain", () => this.#handler.onParserDrain());
parser2.on("error", (err) => this.#handler.onParserError(err));
this.#parser = parser2;
this.#handler.readyState = states.OPEN;
const extensions = parsedExtensions ?? "";
const protocol = response.headersList.get("sec-websocket-protocol") ?? "";
const readable = new ReadableStream({
start: /* @__PURE__ */ __name((controller) => {
this.#readableStreamController = controller;
}, "start"),
pull(controller) {
let chunk;
while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) {
controller.enqueue(chunk);
}
},
cancel: /* @__PURE__ */ __name((reason) => this.#cancel(reason), "cancel")
});
const writable = new WritableStream({
write: /* @__PURE__ */ __name((chunk) => this.#write(chunk), "write"),
close: /* @__PURE__ */ __name(() => closeWebSocketConnection(this.#handler, null, null), "close"),
abort: /* @__PURE__ */ __name((reason) => this.#closeUsingReason(reason), "abort")
});
this.#readableStream = readable;
this.#writableStream = writable;
this.#openedPromise.resolve({
extensions,
protocol,
readable,
writable
});
}
/** @type {import('../websocket').Handler['onMessage']} */
#onMessage(type, data) {
if (this.#handler.readyState !== states.OPEN) {
return;
}
let chunk;
if (type === opcodes.TEXT) {
try {
chunk = utf8Decode(data);
} catch {
failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
return;
}
} else if (type === opcodes.BINARY) {
chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
this.#readableStreamController.enqueue(chunk);
}
/** @type {import('../websocket').Handler['onSocketClose']} */
#onSocketClose() {
const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
this.#handler.readyState = states.CLOSED;
if (this.#handshakeAborted) {
return;
}
if (!this.#handler.wasEverConnected) {
this.#openedPromise.reject(new WebSocketError("Socket never opened"));
}
const result = this.#parser.closingInfo;
let code = result?.code ?? 1005;
if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
code = 1006;
}
const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
if (wasClean) {
this.#readableStream.cancel().catch(() => {
});
if (!this.#writableStream.locked) {
this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
}
this.#closedPromise.resolve({
closeCode: code,
reason
});
} else {
const error2 = createUnvalidatedWebSocketError("unclean close", code, reason);
this.#readableStreamController.error(error2);
this.#writableStream.abort(error2);
this.#closedPromise.reject(error2);
}
}
#closeUsingReason(reason) {
let code = null;
let reasonString = "";
if (webidl.is.WebSocketError(reason)) {
code = reason.closeCode;
reasonString = reason.reason;
}
closeWebSocketConnection(this.#handler, code, reasonString);
}
// To cancel a WebSocketStream stream given reason , close using reason giving stream and reason .
#cancel(reason) {
this.#closeUsingReason(reason);
}
};
Object.defineProperties(WebSocketStream.prototype, {
url: kEnumerableProperty,
opened: kEnumerableProperty,
closed: kEnumerableProperty,
close: kEnumerableProperty,
[Symbol.toStringTag]: {
value: "WebSocketStream",
writable: false,
enumerable: false,
configurable: true
}
});
webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([
{
key: "protocols",
converter: webidl.sequenceConverter(webidl.converters.USVString),
defaultValue: /* @__PURE__ */ __name(() => [], "defaultValue")
},
{
key: "signal",
converter: webidl.nullableConverter(webidl.converters.AbortSignal),
defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
}
]);
webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([
{
key: "closeCode",
converter: /* @__PURE__ */ __name((V3) => webidl.converters["unsigned short"](V3, { enforceRange: true }), "converter")
},
{
key: "reason",
converter: webidl.converters.USVString,
defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
}
]);
module3.exports = { WebSocketStream };
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/eventsource/util.js
var require_util6 = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/eventsource/util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function isValidLastEventId(value) {
return value.indexOf("\0") === -1;
}
__name(isValidLastEventId, "isValidLastEventId");
function isASCIINumber(value) {
if (value.length === 0) return false;
for (let i5 = 0; i5 < value.length; i5++) {
if (value.charCodeAt(i5) < 48 || value.charCodeAt(i5) > 57) return false;
}
return true;
}
__name(isASCIINumber, "isASCIINumber");
function delay(ms) {
return new Promise((resolve25) => {
setTimeout(resolve25, ms);
});
}
__name(delay, "delay");
module3.exports = {
isValidLastEventId,
isASCIINumber,
delay
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Transform: Transform2 } = require("stream");
var { isASCIINumber, isValidLastEventId } = require_util6();
var BOM = [239, 187, 191];
var LF = 10;
var CR = 13;
var COLON = 58;
var SPACE2 = 32;
var EventSourceStream = class extends Transform2 {
static {
__name(this, "EventSourceStream");
}
/**
* @type {eventSourceSettings}
*/
state;
/**
* Leading byte-order-mark check.
* @type {boolean}
*/
checkBOM = true;
/**
* @type {boolean}
*/
crlfCheck = false;
/**
* @type {boolean}
*/
eventEndCheck = false;
/**
* @type {Buffer|null}
*/
buffer = null;
pos = 0;
event = {
data: void 0,
event: void 0,
id: void 0,
retry: void 0
};
/**
* @param {object} options
* @param {boolean} [options.readableObjectMode]
* @param {eventSourceSettings} [options.eventSourceSettings]
* @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push]
*/
constructor(options = {}) {
options.readableObjectMode = true;
super(options);
this.state = options.eventSourceSettings || {};
if (options.push) {
this.push = options.push;
}
}
/**
* @param {Buffer} chunk
* @param {string} _encoding
* @param {Function} callback
* @returns {void}
*/
_transform(chunk, _encoding, callback) {
if (chunk.length === 0) {
callback();
return;
}
if (this.buffer) {
this.buffer = Buffer.concat([this.buffer, chunk]);
} else {
this.buffer = chunk;
}
if (this.checkBOM) {
switch (this.buffer.length) {
case 1:
if (this.buffer[0] === BOM[0]) {
callback();
return;
}
this.checkBOM = false;
callback();
return;
case 2:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
callback();
return;
}
this.checkBOM = false;
break;
case 3:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
this.buffer = Buffer.alloc(0);
this.checkBOM = false;
callback();
return;
}
this.checkBOM = false;
break;
default:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
this.buffer = this.buffer.subarray(3);
}
this.checkBOM = false;
break;
}
}
while (this.pos < this.buffer.length) {
if (this.eventEndCheck) {
if (this.crlfCheck) {
if (this.buffer[this.pos] === LF) {
this.buffer = this.buffer.subarray(this.pos + 1);
this.pos = 0;
this.crlfCheck = false;
continue;
}
this.crlfCheck = false;
}
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
if (this.buffer[this.pos] === CR) {
this.crlfCheck = true;
}
this.buffer = this.buffer.subarray(this.pos + 1);
this.pos = 0;
if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) {
this.processEvent(this.event);
}
this.clearEvent();
continue;
}
this.eventEndCheck = false;
continue;
}
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
if (this.buffer[this.pos] === CR) {
this.crlfCheck = true;
}
this.parseLine(this.buffer.subarray(0, this.pos), this.event);
this.buffer = this.buffer.subarray(this.pos + 1);
this.pos = 0;
this.eventEndCheck = true;
continue;
}
this.pos++;
}
callback();
}
/**
* @param {Buffer} line
* @param {EventSourceStreamEvent} event
*/
parseLine(line, event) {
if (line.length === 0) {
return;
}
const colonPosition = line.indexOf(COLON);
if (colonPosition === 0) {
return;
}
let field = "";
let value = "";
if (colonPosition !== -1) {
field = line.subarray(0, colonPosition).toString("utf8");
let valueStart = colonPosition + 1;
if (line[valueStart] === SPACE2) {
++valueStart;
}
value = line.subarray(valueStart).toString("utf8");
} else {
field = line.toString("utf8");
value = "";
}
switch (field) {
case "data":
if (event[field] === void 0) {
event[field] = value;
} else {
event[field] += `
${value}`;
}
break;
case "retry":
if (isASCIINumber(value)) {
event[field] = value;
}
break;
case "id":
if (isValidLastEventId(value)) {
event[field] = value;
}
break;
case "event":
if (value.length > 0) {
event[field] = value;
}
break;
}
}
/**
* @param {EventSourceStreamEvent} event
*/
processEvent(event) {
if (event.retry && isASCIINumber(event.retry)) {
this.state.reconnectionTime = parseInt(event.retry, 10);
}
if (event.id && isValidLastEventId(event.id)) {
this.state.lastEventId = event.id;
}
if (event.data !== void 0) {
this.push({
type: event.event || "message",
options: {
data: event.data,
lastEventId: this.state.lastEventId,
origin: this.state.origin
}
});
}
}
clearEvent() {
this.event = {
data: void 0,
event: void 0,
id: void 0,
retry: void 0
};
}
};
module3.exports = {
EventSourceStream
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { pipeline } = require("stream");
var { fetching } = require_fetch();
var { makeRequest } = require_request2();
var { webidl } = require_webidl();
var { EventSourceStream } = require_eventsource_stream();
var { parseMIMEType } = require_data_url();
var { createFastMessageEvent } = require_events();
var { isNetworkError } = require_response();
var { delay } = require_util6();
var { kEnumerableProperty } = require_util();
var { environmentSettingsObject } = require_util2();
var experimentalWarned = false;
var defaultReconnectionTime = 3e3;
var CONNECTING = 0;
var OPEN = 1;
var CLOSED = 2;
var ANONYMOUS = "anonymous";
var USE_CREDENTIALS = "use-credentials";
var EventSource = class _EventSource extends EventTarget {
static {
__name(this, "EventSource");
}
#events = {
open: null,
error: null,
message: null
};
#url;
#withCredentials = false;
/**
* @type {ReadyState}
*/
#readyState = CONNECTING;
#request = null;
#controller = null;
#dispatcher;
/**
* @type {import('./eventsource-stream').eventSourceSettings}
*/
#state;
/**
* Creates a new EventSource object.
* @param {string} url
* @param {EventSourceInit} [eventSourceInitDict={}]
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
*/
constructor(url4, eventSourceInitDict = {}) {
super();
webidl.util.markAsUncloneable(this);
const prefix = "EventSource constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
if (!experimentalWarned) {
experimentalWarned = true;
process.emitWarning("EventSource is experimental, expect them to change at any time.", {
code: "UNDICI-ES"
});
}
url4 = webidl.converters.USVString(url4);
eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
this.#dispatcher = eventSourceInitDict.dispatcher;
this.#state = {
lastEventId: "",
reconnectionTime: defaultReconnectionTime
};
const settings = environmentSettingsObject;
let urlRecord;
try {
urlRecord = new URL(url4, settings.settingsObject.baseUrl);
this.#state.origin = urlRecord.origin;
} catch (e7) {
throw new DOMException(e7, "SyntaxError");
}
this.#url = urlRecord.href;
let corsAttributeState = ANONYMOUS;
if (eventSourceInitDict.withCredentials === true) {
corsAttributeState = USE_CREDENTIALS;
this.#withCredentials = true;
}
const initRequest = {
redirect: "follow",
keepalive: true,
// @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
mode: "cors",
credentials: corsAttributeState === "anonymous" ? "same-origin" : "omit",
referrer: "no-referrer"
};
initRequest.client = environmentSettingsObject.settingsObject;
initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]];
initRequest.cache = "no-store";
initRequest.initiator = "other";
initRequest.urlList = [new URL(this.#url)];
this.#request = makeRequest(initRequest);
this.#connect();
}
/**
* Returns the state of this EventSource object's connection. It can have the
* values described below.
* @returns {ReadyState}
* @readonly
*/
get readyState() {
return this.#readyState;
}
/**
* Returns the URL providing the event stream.
* @readonly
* @returns {string}
*/
get url() {
return this.#url;
}
/**
* Returns a boolean indicating whether the EventSource object was
* instantiated with CORS credentials set (true), or not (false, the default).
*/
get withCredentials() {
return this.#withCredentials;
}
#connect() {
if (this.#readyState === CLOSED) return;
this.#readyState = CONNECTING;
const fetchParams = {
request: this.#request,
dispatcher: this.#dispatcher
};
const processEventSourceEndOfBody = /* @__PURE__ */ __name((response) => {
if (!isNetworkError(response)) {
return this.#reconnect();
}
}, "processEventSourceEndOfBody");
fetchParams.processResponseEndOfBody = processEventSourceEndOfBody;
fetchParams.processResponse = (response) => {
if (isNetworkError(response)) {
if (response.aborted) {
this.close();
this.dispatchEvent(new Event("error"));
return;
} else {
this.#reconnect();
return;
}
}
const contentType = response.headersList.get("content-type", true);
const mimeType = contentType !== null ? parseMIMEType(contentType) : "failure";
const contentTypeValid = mimeType !== "failure" && mimeType.essence === "text/event-stream";
if (response.status !== 200 || contentTypeValid === false) {
this.close();
this.dispatchEvent(new Event("error"));
return;
}
this.#readyState = OPEN;
this.dispatchEvent(new Event("open"));
this.#state.origin = response.urlList[response.urlList.length - 1].origin;
const eventSourceStream = new EventSourceStream({
eventSourceSettings: this.#state,
push: /* @__PURE__ */ __name((event) => {
this.dispatchEvent(createFastMessageEvent(
event.type,
event.options
));
}, "push")
});
pipeline(
response.body.stream,
eventSourceStream,
(error2) => {
if (error2?.aborted === false) {
this.close();
this.dispatchEvent(new Event("error"));
}
}
);
};
this.#controller = fetching(fetchParams);
}
/**
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
* @returns {Promise<void>}
*/
async #reconnect() {
if (this.#readyState === CLOSED) return;
this.#readyState = CONNECTING;
this.dispatchEvent(new Event("error"));
await delay(this.#state.reconnectionTime);
if (this.#readyState !== CONNECTING) return;
if (this.#state.lastEventId.length) {
this.#request.headersList.set("last-event-id", this.#state.lastEventId, true);
}
this.#connect();
}
/**
* Closes the connection, if any, and sets the readyState attribute to
* CLOSED.
*/
close() {
webidl.brandCheck(this, _EventSource);
if (this.#readyState === CLOSED) return;
this.#readyState = CLOSED;
this.#controller.abort();
this.#request = null;
}
get onopen() {
return this.#events.open;
}
set onopen(fn2) {
if (this.#events.open) {
this.removeEventListener("open", this.#events.open);
}
if (typeof fn2 === "function") {
this.#events.open = fn2;
this.addEventListener("open", fn2);
} else {
this.#events.open = null;
}
}
get onmessage() {
return this.#events.message;
}
set onmessage(fn2) {
if (this.#events.message) {
this.removeEventListener("message", this.#events.message);
}
if (typeof fn2 === "function") {
this.#events.message = fn2;
this.addEventListener("message", fn2);
} else {
this.#events.message = null;
}
}
get onerror() {
return this.#events.error;
}
set onerror(fn2) {
if (this.#events.error) {
this.removeEventListener("error", this.#events.error);
}
if (typeof fn2 === "function") {
this.#events.error = fn2;
this.addEventListener("error", fn2);
} else {
this.#events.error = null;
}
}
};
var constantsPropertyDescriptors = {
CONNECTING: {
__proto__: null,
configurable: false,
enumerable: true,
value: CONNECTING,
writable: false
},
OPEN: {
__proto__: null,
configurable: false,
enumerable: true,
value: OPEN,
writable: false
},
CLOSED: {
__proto__: null,
configurable: false,
enumerable: true,
value: CLOSED,
writable: false
}
};
Object.defineProperties(EventSource, constantsPropertyDescriptors);
Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors);
Object.defineProperties(EventSource.prototype, {
close: kEnumerableProperty,
onerror: kEnumerableProperty,
onmessage: kEnumerableProperty,
onopen: kEnumerableProperty,
readyState: kEnumerableProperty,
url: kEnumerableProperty,
withCredentials: kEnumerableProperty
});
webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
{
key: "withCredentials",
converter: webidl.converters.boolean,
defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
},
{
key: "dispatcher",
// undici only
converter: webidl.converters.any
}
]);
module3.exports = {
EventSource,
defaultReconnectionTime
};
}
});
// ../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/index.js
var require_undici = __commonJS({
"../../node_modules/.pnpm/undici@7.11.0/node_modules/undici/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var Client2 = require_client();
var Dispatcher2 = require_dispatcher();
var Pool = require_pool();
var BalancedPool = require_balanced_pool();
var Agent = require_agent();
var ProxyAgent2 = require_proxy_agent();
var EnvHttpProxyAgent = require_env_http_proxy_agent();
var RetryAgent = require_retry_agent();
var H2CClient = require_h2c_client();
var errors = require_errors();
var util3 = require_util();
var { InvalidArgumentError } = errors;
var api = require_api();
var buildConnector = require_connect();
var MockClient = require_mock_client();
var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history();
var MockAgent = require_mock_agent();
var MockPool = require_mock_pool();
var mockErrors = require_mock_errors();
var RetryHandler = require_retry_handler();
var { getGlobalDispatcher: getGlobalDispatcher2, setGlobalDispatcher: setGlobalDispatcher2 } = require_global2();
var DecoratorHandler = require_decorator_handler();
var RedirectHandler = require_redirect_handler();
Object.assign(Dispatcher2.prototype, api);
module3.exports.Dispatcher = Dispatcher2;
module3.exports.Client = Client2;
module3.exports.Pool = Pool;
module3.exports.BalancedPool = BalancedPool;
module3.exports.Agent = Agent;
module3.exports.ProxyAgent = ProxyAgent2;
module3.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
module3.exports.RetryAgent = RetryAgent;
module3.exports.H2CClient = H2CClient;
module3.exports.RetryHandler = RetryHandler;
module3.exports.DecoratorHandler = DecoratorHandler;
module3.exports.RedirectHandler = RedirectHandler;
module3.exports.interceptors = {
redirect: require_redirect(),
responseError: require_response_error(),
retry: require_retry(),
dump: require_dump(),
dns: require_dns(),
cache: require_cache2()
};
module3.exports.cacheStores = {
MemoryCacheStore: require_memory_cache_store()
};
var SqliteCacheStore = require_sqlite_cache_store();
module3.exports.cacheStores.SqliteCacheStore = SqliteCacheStore;
module3.exports.buildConnector = buildConnector;
module3.exports.errors = errors;
module3.exports.util = {
parseHeaders: util3.parseHeaders,
headerNameToString: util3.headerNameToString
};
function makeDispatcher(fn2) {
return (url4, opts, handler) => {
if (typeof opts === "function") {
handler = opts;
opts = null;
}
if (!url4 || typeof url4 !== "string" && typeof url4 !== "object" && !(url4 instanceof URL)) {
throw new InvalidArgumentError("invalid url");
}
if (opts != null && typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (opts && opts.path != null) {
if (typeof opts.path !== "string") {
throw new InvalidArgumentError("invalid opts.path");
}
let path72 = opts.path;
if (!opts.path.startsWith("/")) {
path72 = `/${path72}`;
}
url4 = new URL(util3.parseOrigin(url4).origin + path72);
} else {
if (!opts) {
opts = typeof url4 === "object" ? url4 : {};
}
url4 = util3.parseURL(url4);
}
const { agent, dispatcher = getGlobalDispatcher2() } = opts;
if (agent) {
throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
}
return fn2.call(dispatcher, {
...opts,
origin: url4.origin,
path: url4.search ? `${url4.pathname}${url4.search}` : url4.pathname,
method: opts.method || (opts.body ? "PUT" : "GET")
}, handler);
};
}
__name(makeDispatcher, "makeDispatcher");
module3.exports.setGlobalDispatcher = setGlobalDispatcher2;
module3.exports.getGlobalDispatcher = getGlobalDispatcher2;
var fetchImpl = require_fetch().fetch;
module3.exports.fetch = /* @__PURE__ */ __name(async function fetch13(init3, options = void 0) {
try {
return await fetchImpl(init3, options);
} catch (err) {
if (err && typeof err === "object") {
Error.captureStackTrace(err);
}
throw err;
}
}, "fetch");
module3.exports.Headers = require_headers().Headers;
module3.exports.Response = require_response().Response;
module3.exports.Request = require_request2().Request;
module3.exports.FormData = require_formdata().FormData;
var { setGlobalOrigin, getGlobalOrigin } = require_global();
module3.exports.setGlobalOrigin = setGlobalOrigin;
module3.exports.getGlobalOrigin = getGlobalOrigin;
var { CacheStorage: CacheStorage2 } = require_cachestorage();
var { kConstruct } = require_symbols();
module3.exports.caches = new CacheStorage2(kConstruct);
var { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie: parseCookie2 } = require_cookies();
module3.exports.deleteCookie = deleteCookie;
module3.exports.getCookies = getCookies;
module3.exports.getSetCookies = getSetCookies;
module3.exports.setCookie = setCookie;
module3.exports.parseCookie = parseCookie2;
var { parseMIMEType, serializeAMimeType } = require_data_url();
module3.exports.parseMIMEType = parseMIMEType;
module3.exports.serializeAMimeType = serializeAMimeType;
var { CloseEvent, ErrorEvent, MessageEvent } = require_events();
module3.exports.WebSocket = require_websocket().WebSocket;
module3.exports.CloseEvent = CloseEvent;
module3.exports.ErrorEvent = ErrorEvent;
module3.exports.MessageEvent = MessageEvent;
module3.exports.WebSocketStream = require_websocketstream().WebSocketStream;
module3.exports.WebSocketError = require_websocketerror().WebSocketError;
module3.exports.request = makeDispatcher(api.request);
module3.exports.stream = makeDispatcher(api.stream);
module3.exports.pipeline = makeDispatcher(api.pipeline);
module3.exports.connect = makeDispatcher(api.connect);
module3.exports.upgrade = makeDispatcher(api.upgrade);
module3.exports.MockClient = MockClient;
module3.exports.MockCallHistory = MockCallHistory;
module3.exports.MockCallHistoryLog = MockCallHistoryLog;
module3.exports.MockPool = MockPool;
module3.exports.MockAgent = MockAgent;
module3.exports.mockErrors = mockErrors;
var { EventSource } = require_eventsource();
module3.exports.EventSource = EventSource;
function install() {
globalThis.fetch = module3.exports.fetch;
globalThis.Headers = module3.exports.Headers;
globalThis.Response = module3.exports.Response;
globalThis.Request = module3.exports.Request;
globalThis.FormData = module3.exports.FormData;
globalThis.WebSocket = module3.exports.WebSocket;
globalThis.CloseEvent = module3.exports.CloseEvent;
globalThis.ErrorEvent = module3.exports.ErrorEvent;
globalThis.MessageEvent = module3.exports.MessageEvent;
globalThis.EventSource = module3.exports.EventSource;
}
__name(install, "install");
module3.exports.install = install;
}
});
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js
function assembleStyles() {
const codes = /* @__PURE__ */ new Map();
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, "codes", {
value: codes,
enumerable: false
});
styles.color.close = "\x1B[39m";
styles.bgColor.close = "\x1B[49m";
styles.color.ansi = wrapAnsi16();
styles.color.ansi256 = wrapAnsi256();
styles.color.ansi16m = wrapAnsi16m();
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
Object.defineProperties(styles, {
rgbToAnsi256: {
value(red2, green2, blue2) {
if (red2 === green2 && green2 === blue2) {
if (red2 < 8) {
return 16;
}
if (red2 > 248) {
return 231;
}
return Math.round((red2 - 8) / 247 * 24) + 232;
}
return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue2 / 255 * 5);
},
enumerable: false
},
hexToRgb: {
value(hex) {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map((character) => character + character).join("");
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
integer >> 16 & 255,
integer >> 8 & 255,
integer & 255
/* eslint-enable no-bitwise */
];
},
enumerable: false
},
hexToAnsi256: {
value: /* @__PURE__ */ __name((hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)), "value"),
enumerable: false
},
ansi256ToAnsi: {
value(code) {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red2;
let green2;
let blue2;
if (code >= 232) {
red2 = ((code - 232) * 10 + 8) / 255;
green2 = red2;
blue2 = red2;
} else {
code -= 16;
const remainder = code % 36;
red2 = Math.floor(code / 36) / 5;
green2 = Math.floor(remainder / 6) / 5;
blue2 = remainder % 6 / 5;
}
const value = Math.max(red2, green2, blue2) * 2;
if (value === 0) {
return 30;
}
let result = 30 + (Math.round(blue2) << 2 | Math.round(green2) << 1 | Math.round(red2));
if (value === 2) {
result += 60;
}
return result;
},
enumerable: false
},
rgbToAnsi: {
value: /* @__PURE__ */ __name((red2, green2, blue2) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red2, green2, blue2)), "value"),
enumerable: false
},
hexToAnsi: {
value: /* @__PURE__ */ __name((hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), "value"),
enumerable: false
}
});
return styles;
}
var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
var init_ansi_styles = __esm({
"../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
init_import_meta_url();
ANSI_BACKGROUND_OFFSET = 10;
wrapAnsi16 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
wrapAnsi256 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
wrapAnsi16m = /* @__PURE__ */ __name((offset = 0) => (red2, green2, blue2) => `\x1B[${38 + offset};2;${red2};${green2};${blue2}m`, "wrapAnsi16m");
styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39],
// Alias of `blackBright`
grey: [90, 39],
// Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49],
// Alias of `bgBlackBright`
bgGrey: [100, 49],
// Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
modifierNames = Object.keys(styles.modifier);
foregroundColorNames = Object.keys(styles.color);
backgroundColorNames = Object.keys(styles.bgColor);
colorNames = [...foregroundColorNames, ...backgroundColorNames];
__name(assembleStyles, "assembleStyles");
ansiStyles = assembleStyles();
ansi_styles_default = ansiStyles;
}
});
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
function envForceColor() {
if ("FORCE_COLOR" in env2) {
if (env2.FORCE_COLOR === "true") {
return 1;
}
if (env2.FORCE_COLOR === "false") {
return 0;
}
return env2.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env2.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== void 0) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
return 3;
}
if (hasFlag("color=256")) {
return 2;
}
}
if ("TF_BUILD" in env2 && "AGENT_NAME" in env2) {
return 1;
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env2.TERM === "dumb") {
return min;
}
if (import_node_process.default.platform === "win32") {
const osRelease = import_node_os.default.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env2) {
if ("GITHUB_ACTIONS" in env2 || "GITEA_ACTIONS" in env2) {
return 3;
}
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env2) || env2.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env2) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
}
if (env2.COLORTERM === "truecolor") {
return 3;
}
if (env2.TERM === "xterm-kitty") {
return 3;
}
if ("TERM_PROGRAM" in env2) {
const version5 = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env2.TERM_PROGRAM) {
case "iTerm.app": {
return version5 >= 3 ? 3 : 2;
}
case "Apple_Terminal": {
return 2;
}
}
}
if (/-256(color)?$/i.test(env2.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
return 1;
}
if ("COLORTERM" in env2) {
return 1;
}
return min;
}
function createSupportsColor(stream2, options = {}) {
const level = _supportsColor(stream2, {
streamIsTTY: stream2 && stream2.isTTY,
...options
});
return translateLevel(level);
}
var import_node_process, import_node_os, import_node_tty, env2, flagForceColor, supportsColor, supports_color_default;
var init_supports_color = __esm({
"../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js"() {
init_import_meta_url();
import_node_process = __toESM(require("process"), 1);
import_node_os = __toESM(require("os"), 1);
import_node_tty = __toESM(require("tty"), 1);
__name(hasFlag, "hasFlag");
({ env: env2 } = import_node_process.default);
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
flagForceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
flagForceColor = 1;
}
__name(envForceColor, "envForceColor");
__name(translateLevel, "translateLevel");
__name(_supportsColor, "_supportsColor");
__name(createSupportsColor, "createSupportsColor");
supportsColor = {
stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
};
supports_color_default = supportsColor;
}
});
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js
function stringReplaceAll(string, substring2, replacer2) {
let index = string.indexOf(substring2);
if (index === -1) {
return string;
}
const substringLength = substring2.length;
let endIndex = 0;
let returnValue = "";
do {
returnValue += string.slice(endIndex, index) + substring2 + replacer2;
endIndex = index + substringLength;
index = string.indexOf(substring2, endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let endIndex = 0;
let returnValue = "";
do {
const gotCR = string[index - 1] === "\r";
returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
endIndex = index + 1;
index = string.indexOf("\n", endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
var init_utilities = __esm({
"../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js"() {
init_import_meta_url();
__name(stringReplaceAll, "stringReplaceAll");
__name(stringEncaseCRLFWithFirstIndex, "stringEncaseCRLFWithFirstIndex");
}
});
// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/index.js
function createChalk(options) {
return chalkFactory(options);
}
var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default;
var init_source = __esm({
"../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/index.js"() {
init_import_meta_url();
init_ansi_styles();
init_supports_color();
init_utilities();
({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
GENERATOR = Symbol("GENERATOR");
STYLER = Symbol("STYLER");
IS_EMPTY = Symbol("IS_EMPTY");
levelMapping = [
"ansi",
"ansi",
"ansi256",
"ansi16m"
];
styles2 = /* @__PURE__ */ Object.create(null);
applyOptions = /* @__PURE__ */ __name((object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error("The `level` option should be an integer from 0 to 3");
}
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === void 0 ? colorLevel : options.level;
}, "applyOptions");
chalkFactory = /* @__PURE__ */ __name((options) => {
const chalk2 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
applyOptions(chalk2, options);
Object.setPrototypeOf(chalk2, createChalk.prototype);
return chalk2;
}, "chalkFactory");
__name(createChalk, "createChalk");
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default)) {
styles2[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
Object.defineProperty(this, styleName, { value: builder });
return builder;
}
};
}
styles2.visible = {
get() {
const builder = createBuilder(this, this[STYLER], true);
Object.defineProperty(this, "visible", { value: builder });
return builder;
}
};
getModelAnsi = /* @__PURE__ */ __name((model, level, type, ...arguments_) => {
if (model === "rgb") {
if (level === "ansi16m") {
return ansi_styles_default[type].ansi16m(...arguments_);
}
if (level === "ansi256") {
return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
}
return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
}
if (model === "hex") {
return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
}
return ansi_styles_default[type][model](...arguments_);
}, "getModelAnsi");
usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
styles2[model] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
styles2[bgModel] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
}
proto = Object.defineProperties(() => {
}, {
...styles2,
level: {
enumerable: true,
get() {
return this[GENERATOR].level;
},
set(level) {
this[GENERATOR].level = level;
}
}
});
createStyler = /* @__PURE__ */ __name((open4, close2, parent) => {
let openAll;
let closeAll;
if (parent === void 0) {
openAll = open4;
closeAll = close2;
} else {
openAll = parent.openAll + open4;
closeAll = close2 + parent.closeAll;
}
return {
open: open4,
close: close2,
openAll,
closeAll,
parent
};
}, "createStyler");
createBuilder = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
const builder = /* @__PURE__ */ __name((...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")), "builder");
Object.setPrototypeOf(builder, proto);
builder[GENERATOR] = self2;
builder[STYLER] = _styler;
builder[IS_EMPTY] = _isEmpty;
return builder;
}, "createBuilder");
applyStyle = /* @__PURE__ */ __name((self2, string) => {
if (self2.level <= 0 || !string) {
return self2[IS_EMPTY] ? "" : string;
}
let styler = self2[STYLER];
if (styler === void 0) {
return string;
}
const { openAll, closeAll } = styler;
if (string.includes("\x1B")) {
while (styler !== void 0) {
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
const lfIndex = string.indexOf("\n");
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
}, "applyStyle");
Object.defineProperties(createChalk.prototype, styles2);
chalk = createChalk();
chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
source_default = chalk;
}
});
// ../cli/colors.ts
var white, gray, dim, hidden, bold, cyanBright, bgCyan, brandColor, black, blue, bgBlue, red, bgRed, green, bgGreen, yellow, bgYellow;
var init_colors = __esm({
"../cli/colors.ts"() {
init_import_meta_url();
init_source();
({ white, gray, dim, hidden, bold, cyanBright, bgCyan } = source_default);
brandColor = source_default.hex("#BD5B08");
black = source_default.hex("#111");
blue = source_default.hex("#0E838F");
bgBlue = black.bgHex("#0E838F");
red = source_default.hex("#AB2526");
bgRed = black.bgHex("#AB2526");
green = source_default.hex("#218529");
bgGreen = black.bgHex("#218529");
yellow = source_default.hex("#7F7322");
bgYellow = black.bgHex("#7F7322");
}
});
// ../containers-shared/src/client/core/ApiError.ts
var ApiError;
var init_ApiError = __esm({
"../containers-shared/src/client/core/ApiError.ts"() {
init_import_meta_url();
ApiError = class extends Error {
static {
__name(this, "ApiError");
}
url;
status;
statusText;
body;
request;
constructor(request4, response, message) {
super(message);
this.name = "ApiError";
this.url = response.url;
this.status = response.status;
this.statusText = response.statusText;
this.body = response.body;
this.request = request4;
}
};
}
});
// ../containers-shared/src/client/core/CancelablePromise.ts
var CancelError, CancelablePromise;
var init_CancelablePromise = __esm({
"../containers-shared/src/client/core/CancelablePromise.ts"() {
init_import_meta_url();
CancelError = class extends Error {
static {
__name(this, "CancelError");
}
constructor(message) {
super(message);
this.name = "CancelError";
}
get isCancelled() {
return true;
}
};
CancelablePromise = class {
static {
__name(this, "CancelablePromise");
}
#isResolved;
#isRejected;
#isCancelled;
#cancelHandlers;
#promise;
#resolve;
#reject;
constructor(executor) {
this.#isResolved = false;
this.#isRejected = false;
this.#isCancelled = false;
this.#cancelHandlers = [];
this.#promise = new Promise((resolve25, reject) => {
this.#resolve = resolve25;
this.#reject = reject;
const onResolve = /* @__PURE__ */ __name((value) => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isResolved = true;
this.#resolve?.(value);
}, "onResolve");
const onReject = /* @__PURE__ */ __name((reason) => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isRejected = true;
this.#reject?.(reason);
}, "onReject");
const onCancel = /* @__PURE__ */ __name((cancelHandler) => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#cancelHandlers.push(cancelHandler);
}, "onCancel");
Object.defineProperty(onCancel, "isResolved", {
get: /* @__PURE__ */ __name(() => this.#isResolved, "get")
});
Object.defineProperty(onCancel, "isRejected", {
get: /* @__PURE__ */ __name(() => this.#isRejected, "get")
});
Object.defineProperty(onCancel, "isCancelled", {
get: /* @__PURE__ */ __name(() => this.#isCancelled, "get")
});
return executor(onResolve, onReject, onCancel);
});
}
get [Symbol.toStringTag]() {
return "Cancellable Promise";
}
then(onFulfilled, onRejected) {
return this.#promise.then(onFulfilled, onRejected);
}
catch(onRejected) {
return this.#promise.catch(onRejected);
}
finally(onFinally) {
return this.#promise.finally(onFinally);
}
cancel() {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isCancelled = true;
if (this.#cancelHandlers.length) {
try {
for (const cancelHandler of this.#cancelHandlers) {
cancelHandler();
}
} catch (error2) {
console.warn("Cancellation threw an error", error2);
return;
}
}
this.#cancelHandlers.length = 0;
this.#reject?.(new CancelError("Request aborted"));
}
get isCancelled() {
return this.#isCancelled;
}
};
}
});
// ../containers-shared/src/client/core/OpenAPI.ts
var OpenAPI;
var init_OpenAPI = __esm({
"../containers-shared/src/client/core/OpenAPI.ts"() {
init_import_meta_url();
OpenAPI = {
BASE: "",
VERSION: "1.0.0",
WITH_CREDENTIALS: false,
CREDENTIALS: "include",
TOKEN: void 0,
USERNAME: void 0,
PASSWORD: void 0,
HEADERS: void 0,
ENCODE_PATH: void 0,
LOGGER: void 0
};
}
});
// ../containers-shared/src/client/models/ApplicationAffinityColocation.ts
var init_ApplicationAffinityColocation = __esm({
"../containers-shared/src/client/models/ApplicationAffinityColocation.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/ApplicationMutationError.ts
var init_ApplicationMutationError = __esm({
"../containers-shared/src/client/models/ApplicationMutationError.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/ApplicationRollout.ts
var ApplicationRollout;
var init_ApplicationRollout = __esm({
"../containers-shared/src/client/models/ApplicationRollout.ts"() {
init_import_meta_url();
((ApplicationRollout2) => {
let kind;
((kind2) => {
kind2["FULL_AUTO"] = "full_auto";
kind2["FULL_MANUAL"] = "full_manual";
kind2["DURABLE_OBJECTS_AUTO"] = "durable_objects_auto";
})(kind = ApplicationRollout2.kind || (ApplicationRollout2.kind = {}));
let strategy;
((strategy2) => {
strategy2["ROLLING"] = "rolling";
})(strategy = ApplicationRollout2.strategy || (ApplicationRollout2.strategy = {}));
let status2;
((status3) => {
status3["PENDING"] = "pending";
status3["PROGRESSING"] = "progressing";
status3["COMPLETED"] = "completed";
status3["REVERTED"] = "reverted";
status3["REPLACED"] = "replaced";
})(status2 = ApplicationRollout2.status || (ApplicationRollout2.status = {}));
})(ApplicationRollout || (ApplicationRollout = {}));
}
});
// ../containers-shared/src/client/models/AssignIPv4.ts
var init_AssignIPv4 = __esm({
"../containers-shared/src/client/models/AssignIPv4.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/AssignIPv6.ts
var init_AssignIPv6 = __esm({
"../containers-shared/src/client/models/AssignIPv6.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/BadRequestWithCodeError.ts
var BadRequestWithCodeError;
var init_BadRequestWithCodeError = __esm({
"../containers-shared/src/client/models/BadRequestWithCodeError.ts"() {
init_import_meta_url();
((BadRequestWithCodeError2) => {
let error2;
((error3) => {
error3["VALIDATE_INPUT"] = "VALIDATE_INPUT";
})(error2 = BadRequestWithCodeError2.error || (BadRequestWithCodeError2.error = {}));
})(BadRequestWithCodeError || (BadRequestWithCodeError = {}));
}
});
// ../containers-shared/src/client/models/ContainerNetworkMode.ts
var init_ContainerNetworkMode = __esm({
"../containers-shared/src/client/models/ContainerNetworkMode.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/CreateApplicationRolloutRequest.ts
var CreateApplicationRolloutRequest;
var init_CreateApplicationRolloutRequest = __esm({
"../containers-shared/src/client/models/CreateApplicationRolloutRequest.ts"() {
init_import_meta_url();
((CreateApplicationRolloutRequest2) => {
let strategy;
((strategy2) => {
strategy2["ROLLING"] = "rolling";
})(strategy = CreateApplicationRolloutRequest2.strategy || (CreateApplicationRolloutRequest2.strategy = {}));
let step_percentage;
((step_percentage2) => {
step_percentage2[step_percentage2["_5"] = 5] = "_5";
step_percentage2[step_percentage2["_10"] = 10] = "_10";
step_percentage2[step_percentage2["_20"] = 20] = "_20";
step_percentage2[step_percentage2["_25"] = 25] = "_25";
step_percentage2[step_percentage2["_50"] = 50] = "_50";
step_percentage2[step_percentage2["_100"] = 100] = "_100";
})(step_percentage = CreateApplicationRolloutRequest2.step_percentage || (CreateApplicationRolloutRequest2.step_percentage = {}));
let kind;
((kind2) => {
kind2["FULL_AUTO"] = "full_auto";
kind2["FULL_MANUAL"] = "full_manual";
})(kind = CreateApplicationRolloutRequest2.kind || (CreateApplicationRolloutRequest2.kind = {}));
})(CreateApplicationRolloutRequest || (CreateApplicationRolloutRequest = {}));
}
});
// ../containers-shared/src/client/models/DeploymentCheckKind.ts
var init_DeploymentCheckKind = __esm({
"../containers-shared/src/client/models/DeploymentCheckKind.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/DeploymentCheckType.ts
var init_DeploymentCheckType = __esm({
"../containers-shared/src/client/models/DeploymentCheckType.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/DeploymentMutationError.ts
var DeploymentMutationError;
var init_DeploymentMutationError = __esm({
"../containers-shared/src/client/models/DeploymentMutationError.ts"() {
init_import_meta_url();
DeploymentMutationError = /* @__PURE__ */ ((DeploymentMutationError2) => {
DeploymentMutationError2["VALIDATE_INPUT"] = "VALIDATE_INPUT";
DeploymentMutationError2["SURPASSED_BASE_LIMITS"] = "SURPASSED_BASE_LIMITS";
DeploymentMutationError2["SURPASSED_TOTAL_LIMITS"] = "SURPASSED_TOTAL_LIMITS";
DeploymentMutationError2["LOCATION_NOT_ALLOWED"] = "LOCATION_NOT_ALLOWED";
DeploymentMutationError2["LOCATION_SURPASSED_BASE_LIMITS"] = "LOCATION_SURPASSED_BASE_LIMITS";
DeploymentMutationError2["IMAGE_REGISTRY_NOT_CONFIGURED"] = "IMAGE_REGISTRY_NOT_CONFIGURED";
return DeploymentMutationError2;
})(DeploymentMutationError || {});
}
});
// ../containers-shared/src/client/models/DeploymentNotFoundError.ts
var DeploymentNotFoundError;
var init_DeploymentNotFoundError = __esm({
"../containers-shared/src/client/models/DeploymentNotFoundError.ts"() {
init_import_meta_url();
((DeploymentNotFoundError2) => {
let error2;
((error3) => {
error3["DEPLOYMENT_NOT_FOUND"] = "DEPLOYMENT_NOT_FOUND";
})(error2 = DeploymentNotFoundError2.error || (DeploymentNotFoundError2.error = {}));
})(DeploymentNotFoundError || (DeploymentNotFoundError = {}));
}
});
// ../containers-shared/src/client/models/DeploymentPlacementState.ts
var init_DeploymentPlacementState = __esm({
"../containers-shared/src/client/models/DeploymentPlacementState.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/DeploymentQueuedReason.ts
var init_DeploymentQueuedReason = __esm({
"../containers-shared/src/client/models/DeploymentQueuedReason.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/DeploymentSchedulingState.ts
var init_DeploymentSchedulingState = __esm({
"../containers-shared/src/client/models/DeploymentSchedulingState.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/DeploymentType.ts
var init_DeploymentType = __esm({
"../containers-shared/src/client/models/DeploymentType.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/DurableObjectStatusHealth.ts
var init_DurableObjectStatusHealth = __esm({
"../containers-shared/src/client/models/DurableObjectStatusHealth.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/EventName.ts
var init_EventName = __esm({
"../containers-shared/src/client/models/EventName.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/EventType.ts
var init_EventType = __esm({
"../containers-shared/src/client/models/EventType.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/HTTPMethod.ts
var init_HTTPMethod = __esm({
"../containers-shared/src/client/models/HTTPMethod.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/ImageRegistryAlreadyExistsError.ts
var ImageRegistryAlreadyExistsError;
var init_ImageRegistryAlreadyExistsError = __esm({
"../containers-shared/src/client/models/ImageRegistryAlreadyExistsError.ts"() {
init_import_meta_url();
((ImageRegistryAlreadyExistsError2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_ALREADY_EXISTS"] = "IMAGE_REGISTRY_ALREADY_EXISTS";
})(error2 = ImageRegistryAlreadyExistsError2.error || (ImageRegistryAlreadyExistsError2.error = {}));
})(ImageRegistryAlreadyExistsError || (ImageRegistryAlreadyExistsError = {}));
}
});
// ../containers-shared/src/client/models/ImageRegistryIsPublic.ts
var ImageRegistryIsPublic;
var init_ImageRegistryIsPublic = __esm({
"../containers-shared/src/client/models/ImageRegistryIsPublic.ts"() {
init_import_meta_url();
((ImageRegistryIsPublic2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_IS_PUBLIC"] = "IMAGE_REGISTRY_IS_PUBLIC";
})(error2 = ImageRegistryIsPublic2.error || (ImageRegistryIsPublic2.error = {}));
})(ImageRegistryIsPublic || (ImageRegistryIsPublic = {}));
}
});
// ../containers-shared/src/client/models/ImageRegistryNotAllowedError.ts
var ImageRegistryNotAllowedError;
var init_ImageRegistryNotAllowedError = __esm({
"../containers-shared/src/client/models/ImageRegistryNotAllowedError.ts"() {
init_import_meta_url();
((ImageRegistryNotAllowedError2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_NOT_ALLOWED"] = "IMAGE_REGISTRY_NOT_ALLOWED";
})(error2 = ImageRegistryNotAllowedError2.error || (ImageRegistryNotAllowedError2.error = {}));
})(ImageRegistryNotAllowedError || (ImageRegistryNotAllowedError = {}));
}
});
// ../containers-shared/src/client/models/ImageRegistryNotFoundError.ts
var ImageRegistryNotFoundError;
var init_ImageRegistryNotFoundError = __esm({
"../containers-shared/src/client/models/ImageRegistryNotFoundError.ts"() {
init_import_meta_url();
((ImageRegistryNotFoundError2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_NOT_FOUND"] = "IMAGE_REGISTRY_NOT_FOUND";
})(error2 = ImageRegistryNotFoundError2.error || (ImageRegistryNotFoundError2.error = {}));
})(ImageRegistryNotFoundError || (ImageRegistryNotFoundError = {}));
}
});
// ../containers-shared/src/client/models/ImageRegistryPermissions.ts
var init_ImageRegistryPermissions = __esm({
"../containers-shared/src/client/models/ImageRegistryPermissions.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/ImageRegistryProtocolAlreadyExists.ts
var ImageRegistryProtocolAlreadyExists;
var init_ImageRegistryProtocolAlreadyExists = __esm({
"../containers-shared/src/client/models/ImageRegistryProtocolAlreadyExists.ts"() {
init_import_meta_url();
((ImageRegistryProtocolAlreadyExists2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_PROTOCOL_ALREADY_EXISTS"] = "IMAGE_REGISTRY_PROTOCOL_ALREADY_EXISTS";
})(error2 = ImageRegistryProtocolAlreadyExists2.error || (ImageRegistryProtocolAlreadyExists2.error = {}));
})(ImageRegistryProtocolAlreadyExists || (ImageRegistryProtocolAlreadyExists = {}));
}
});
// ../containers-shared/src/client/models/ImageRegistryProtocolIsReferencedError.ts
var ImageRegistryProtocolIsReferencedError;
var init_ImageRegistryProtocolIsReferencedError = __esm({
"../containers-shared/src/client/models/ImageRegistryProtocolIsReferencedError.ts"() {
init_import_meta_url();
((ImageRegistryProtocolIsReferencedError2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_PROTO_IS_REFERENCED"] = "IMAGE_REGISTRY_PROTO_IS_REFERENCED";
})(error2 = ImageRegistryProtocolIsReferencedError2.error || (ImageRegistryProtocolIsReferencedError2.error = {}));
})(ImageRegistryProtocolIsReferencedError || (ImageRegistryProtocolIsReferencedError = {}));
}
});
// ../containers-shared/src/client/models/ImageRegistryProtocolNotFound.ts
var ImageRegistryProtocolNotFound;
var init_ImageRegistryProtocolNotFound = __esm({
"../containers-shared/src/client/models/ImageRegistryProtocolNotFound.ts"() {
init_import_meta_url();
((ImageRegistryProtocolNotFound2) => {
let error2;
((error3) => {
error3["IMAGE_REGISTRY_PROTOCOL_NOT_FOUND"] = "IMAGE_REGISTRY_PROTOCOL_NOT_FOUND";
})(error2 = ImageRegistryProtocolNotFound2.error || (ImageRegistryProtocolNotFound2.error = {}));
})(ImageRegistryProtocolNotFound || (ImageRegistryProtocolNotFound = {}));
}
});
// ../containers-shared/src/client/models/InstanceType.ts
var init_InstanceType = __esm({
"../containers-shared/src/client/models/InstanceType.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/IPType.ts
var init_IPType = __esm({
"../containers-shared/src/client/models/IPType.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/JobStatusHealth.ts
var init_JobStatusHealth = __esm({
"../containers-shared/src/client/models/JobStatusHealth.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/NetworkMode.ts
var init_NetworkMode = __esm({
"../containers-shared/src/client/models/NetworkMode.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/NodeGroup.ts
var init_NodeGroup = __esm({
"../containers-shared/src/client/models/NodeGroup.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/PlacementStatusHealth.ts
var init_PlacementStatusHealth = __esm({
"../containers-shared/src/client/models/PlacementStatusHealth.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/ProvisionerConfiguration.ts
var ProvisionerConfiguration;
var init_ProvisionerConfiguration = __esm({
"../containers-shared/src/client/models/ProvisionerConfiguration.ts"() {
init_import_meta_url();
((ProvisionerConfiguration2) => {
let type;
((type2) => {
type2["NONE"] = "none";
type2["CLOUDINIT"] = "cloudinit";
})(type = ProvisionerConfiguration2.type || (ProvisionerConfiguration2.type = {}));
})(ProvisionerConfiguration || (ProvisionerConfiguration = {}));
}
});
// ../containers-shared/src/client/models/RolloutStep.ts
var RolloutStep;
var init_RolloutStep = __esm({
"../containers-shared/src/client/models/RolloutStep.ts"() {
init_import_meta_url();
((RolloutStep2) => {
let status2;
((status3) => {
status3["PENDING"] = "pending";
status3["PROGRESSING"] = "progressing";
status3["REVERTING"] = "reverting";
status3["COMPLETED"] = "completed";
status3["REVERTED"] = "reverted";
})(status2 = RolloutStep2.status || (RolloutStep2.status = {}));
})(RolloutStep || (RolloutStep = {}));
}
});
// ../containers-shared/src/client/models/SchedulingPolicy.ts
var init_SchedulingPolicy = __esm({
"../containers-shared/src/client/models/SchedulingPolicy.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/SecretAccessType.ts
var init_SecretAccessType = __esm({
"../containers-shared/src/client/models/SecretAccessType.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/client/models/SecretNameAlreadyExists.ts
var SecretNameAlreadyExists;
var init_SecretNameAlreadyExists = __esm({
"../containers-shared/src/client/models/SecretNameAlreadyExists.ts"() {
init_import_meta_url();
((SecretNameAlreadyExists2) => {
let error2;
((error3) => {
error3["SECRET_NAME_ALREADY_EXISTS"] = "SECRET_NAME_ALREADY_EXISTS";
})(error2 = SecretNameAlreadyExists2.error || (SecretNameAlreadyExists2.error = {}));
})(SecretNameAlreadyExists || (SecretNameAlreadyExists = {}));
}
});
// ../containers-shared/src/client/models/SecretNotFound.ts
var SecretNotFound;
var init_SecretNotFound = __esm({
"../containers-shared/src/client/models/SecretNotFound.ts"() {
init_import_meta_url();
((SecretNotFound2) => {
let error2;
((error3) => {
error3["SECRET_NAME_NOT_FOUND"] = "SECRET_NAME_NOT_FOUND";
})(error2 = SecretNotFound2.error || (SecretNotFound2.error = {}));
})(SecretNotFound || (SecretNotFound = {}));
}
});
// ../containers-shared/src/client/models/SSHPublicKeyNotFoundError.ts
var SSHPublicKeyNotFoundError;
var init_SSHPublicKeyNotFoundError = __esm({
"../containers-shared/src/client/models/SSHPublicKeyNotFoundError.ts"() {
init_import_meta_url();
((SSHPublicKeyNotFoundError2) => {
let error2;
((error3) => {
error3["SSH_PUBLIC_KEY_NOT_FOUND"] = "SSH_PUBLIC_KEY_NOT_FOUND";
})(error2 = SSHPublicKeyNotFoundError2.error || (SSHPublicKeyNotFoundError2.error = {}));
})(SSHPublicKeyNotFoundError || (SSHPublicKeyNotFoundError = {}));
}
});
// ../containers-shared/src/client/models/UpdateApplicationRolloutRequest.ts
var UpdateApplicationRolloutRequest;
var init_UpdateApplicationRolloutRequest = __esm({
"../containers-shared/src/client/models/UpdateApplicationRolloutRequest.ts"() {
init_import_meta_url();
((UpdateApplicationRolloutRequest2) => {
let action;
((action2) => {
action2["NEXT"] = "next";
action2["PREVIOUS"] = "previous";
action2["REVERT"] = "revert";
})(action = UpdateApplicationRolloutRequest2.action || (UpdateApplicationRolloutRequest2.action = {}));
})(UpdateApplicationRolloutRequest || (UpdateApplicationRolloutRequest = {}));
}
});
// ../containers-shared/src/client/core/request.ts
var isDefined, isString, isStringWithValue, isBlob, base64, getQueryString, getUrl, getFormData, resolve5, getHeaders, getRequestBody, isResponseSchemaV4, parseResponseSchemaV4, sendRequest, getResponseHeader, getResponseBody, catchErrorCodes, request, debugLogRequest, debugLogResponse;
var init_request = __esm({
"../containers-shared/src/client/core/request.ts"() {
init_import_meta_url();
init_ApiError();
init_CancelablePromise();
isDefined = /* @__PURE__ */ __name((value) => {
return value !== void 0 && value !== null;
}, "isDefined");
isString = /* @__PURE__ */ __name((value) => {
return typeof value === "string";
}, "isString");
isStringWithValue = /* @__PURE__ */ __name((value) => {
return isString(value) && value !== "";
}, "isStringWithValue");
isBlob = /* @__PURE__ */ __name((value) => {
return typeof value === "object" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.arrayBuffer === "function" && typeof value.constructor === "function" && typeof value.constructor.name === "string" && /^(Blob|File)$/.test(value.constructor.name) && /^(Blob|File)$/.test(value[Symbol.toStringTag]);
}, "isBlob");
base64 = /* @__PURE__ */ __name((str) => {
try {
return btoa(str);
} catch (err) {
return Buffer.from(str).toString("base64");
}
}, "base64");
getQueryString = /* @__PURE__ */ __name((params) => {
const qs = [];
const append = /* @__PURE__ */ __name((key, value) => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}, "append");
const process11 = /* @__PURE__ */ __name((key, value) => {
if (isDefined(value)) {
if (Array.isArray(value)) {
value.forEach((v7) => {
process11(key, v7);
});
} else if (typeof value === "object") {
Object.entries(value).forEach(([k6, v7]) => {
process11(`${key}[${k6}]`, v7);
});
} else {
append(key, value);
}
}
}, "process");
Object.entries(params).forEach(([key, value]) => {
process11(key, value);
});
if (qs.length > 0) {
return `?${qs.join("&")}`;
}
return "";
}, "getQueryString");
getUrl = /* @__PURE__ */ __name((config, options) => {
const encoder = config.ENCODE_PATH || encodeURI;
const path72 = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring2, group) => {
if (options.path?.hasOwnProperty(group)) {
return encoder(String(options.path[group]));
}
return substring2;
});
const url4 = `${config.BASE}${path72}`;
if (options.query) {
return `${url4}${getQueryString(options.query)}`;
}
return url4;
}, "getUrl");
getFormData = /* @__PURE__ */ __name((options) => {
if (options.formData) {
const formData = new FormData();
const process11 = /* @__PURE__ */ __name(async (key, value) => {
if (isString(value)) {
formData.append(key, value);
} else {
formData.append(key, JSON.stringify(value));
}
}, "process");
Object.entries(options.formData).filter(([_4, value]) => isDefined(value)).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((v7) => process11(key, v7));
} else {
process11(key, value);
}
});
return formData;
}
return void 0;
}, "getFormData");
resolve5 = /* @__PURE__ */ __name(async (options, resolver) => {
if (typeof resolver === "function") {
return resolver(options);
}
return resolver;
}, "resolve");
getHeaders = /* @__PURE__ */ __name(async (config, options) => {
const token = await resolve5(options, config.TOKEN);
const username = await resolve5(options, config.USERNAME);
const password = await resolve5(options, config.PASSWORD);
const additionalHeaders = await resolve5(options, config.HEADERS);
const headers = Object.entries({
Accept: "application/json",
...additionalHeaders,
...options.headers
}).filter(([_4, value]) => isDefined(value)).reduce(
(headers2, [key, value]) => ({
...headers2,
[key]: String(value)
}),
{}
);
if (isStringWithValue(token)) {
headers["Authorization"] = `Bearer ${token}`;
}
if (isStringWithValue(username) && isStringWithValue(password)) {
const credentials = base64(`${username}:${password}`);
headers["Authorization"] = `Basic ${credentials}`;
}
if (options.body) {
if (options.mediaType) {
headers["Content-Type"] = options.mediaType;
} else if (isBlob(options.body)) {
headers["Content-Type"] = options.body.type || "application/octet-stream";
} else if (isString(options.body)) {
headers["Content-Type"] = "text/plain";
} else {
headers["Content-Type"] = "application/json";
}
}
return new Headers(headers);
}, "getHeaders");
getRequestBody = /* @__PURE__ */ __name((options) => {
if (options.body !== void 0) {
if (options.mediaType?.includes("/json")) {
return JSON.stringify(options.body);
} else if (isString(options.body) || isBlob(options.body)) {
return options.body;
} else {
return JSON.stringify(options.body);
}
}
return void 0;
}, "getRequestBody");
isResponseSchemaV4 = /* @__PURE__ */ __name((config, _options) => {
return config.BASE.endsWith("/containers");
}, "isResponseSchemaV4");
parseResponseSchemaV4 = /* @__PURE__ */ __name((url4, response, responseHeader, responseBody) => {
const fetchResult2 = typeof responseBody === "object" ? responseBody : JSON.parse(responseBody);
const ok = response.ok && fetchResult2.success;
let result;
if (ok) {
if (fetchResult2.result !== void 0) {
result = fetchResult2.result;
} else {
result = {};
}
} else {
result = { error: fetchResult2.errors?.[0]?.message };
}
return {
url: url4,
ok,
status: response.status,
statusText: response.statusText,
body: responseHeader ?? result
};
}, "parseResponseSchemaV4");
sendRequest = /* @__PURE__ */ __name(async (config, options, url4, body, formData, headers, onCancel) => {
const controller = new AbortController();
const request4 = {
headers,
body: body ?? formData,
method: options.method,
signal: controller.signal
};
if (config.WITH_CREDENTIALS) {
request4.credentials = config.CREDENTIALS;
}
onCancel(() => controller.abort());
return await fetch(url4, request4);
}, "sendRequest");
getResponseHeader = /* @__PURE__ */ __name((response, responseHeader) => {
if (responseHeader) {
const content = response.headers.get(responseHeader);
if (isString(content)) {
return content;
}
}
return void 0;
}, "getResponseHeader");
getResponseBody = /* @__PURE__ */ __name(async (response) => {
if (response.status !== 204) {
try {
const contentType = response.headers.get("Content-Type");
if (contentType) {
const jsonTypes = ["application/json", "application/problem+json"];
const isJSON = jsonTypes.some(
(type) => contentType.toLowerCase().startsWith(type)
);
if (isJSON) {
return await response.json();
} else {
return await response.text();
}
}
} catch (error2) {
console.error(error2);
}
}
return void 0;
}, "getResponseBody");
catchErrorCodes = /* @__PURE__ */ __name((options, result) => {
const errors = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
502: "Bad Gateway",
503: "Service Unavailable",
...options.errors
};
const error2 = errors[result.status];
if (error2) {
throw new ApiError(options, result, error2);
}
if (!result.ok) {
throw new ApiError(options, result, "Generic Error");
}
}, "catchErrorCodes");
request = /* @__PURE__ */ __name((config, options) => {
return new CancelablePromise(async (resolve25, reject, onCancel) => {
try {
const url4 = getUrl(config, options);
const formData = getFormData(options);
const body = getRequestBody(options);
const headers = await getHeaders(config, options);
debugLogRequest(config, url4, headers, formData ?? body ?? {});
if (!onCancel.isCancelled) {
const response = await sendRequest(
config,
options,
url4,
body,
formData,
headers,
onCancel
);
const responseBody = await getResponseBody(response);
const responseHeader = getResponseHeader(
response,
options.responseHeader
);
let result;
if (isResponseSchemaV4(config, options)) {
result = parseResponseSchemaV4(
url4,
response,
responseHeader,
responseBody
);
} else {
result = {
url: url4,
ok: response.ok,
status: response.status,
statusText: response.statusText,
body: responseHeader ?? responseBody
};
}
debugLogResponse(config, result);
catchErrorCodes(options, result);
resolve25(result.body);
}
} catch (error2) {
reject(error2);
}
});
}, "request");
debugLogRequest = /* @__PURE__ */ __name(async (config, url4, headers, body) => {
config.LOGGER?.debug(`-- START CF API REQUEST: ${url4}`);
const logHeaders2 = new Headers(headers);
logHeaders2.delete("Authorization");
config.LOGGER?.debugWithSanitization(
"HEADERS:",
JSON.stringify(logHeaders2, null, 2)
);
config.LOGGER?.debugWithSanitization(
"BODY:",
JSON.stringify(
body instanceof FormData ? await new Response(body).text() : body,
null,
2
)
);
config.LOGGER?.debug("-- END CF API REQUEST");
}, "debugLogRequest");
debugLogResponse = /* @__PURE__ */ __name((config, response) => {
config.LOGGER?.debug(
"-- START CF API RESPONSE:",
response.statusText,
response.status
);
config.LOGGER?.debugWithSanitization("RESPONSE:", response.body);
config.LOGGER?.debug("-- END CF API RESPONSE");
}, "debugLogResponse");
}
});
// ../containers-shared/src/client/services/AccountService.ts
var AccountService;
var init_AccountService = __esm({
"../containers-shared/src/client/services/AccountService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
AccountService = class {
static {
__name(this, "AccountService");
}
/**
* Get complete account details related to Cloudchamber
* Get complete account details related to Cloudchamber, like limits and available locations
* @returns CompleteAccountCustomer Complete account for the user
* @throws ApiError
*/
static getMe() {
return request(OpenAPI, {
method: "GET",
url: "/me",
errors: {
401: `Unauthorized`,
500: `There has been an internal error`
}
});
}
/**
* Modify account details like defaults
* Modify account details like defaults
* @param requestBody
* @returns CompleteAccountCustomer Complete account for the user
* @throws ApiError
*/
static modifyMe(requestBody) {
return request(OpenAPI, {
method: "PATCH",
url: "/me",
body: requestBody,
mediaType: "application/json",
errors: {
400: `Bad Request that contains a specific constant code and details object about the error.`,
401: `Unauthorized`,
500: `There has been an internal error`
}
});
}
};
}
});
// ../containers-shared/src/client/services/ApplicationsService.ts
var ApplicationsService;
var init_ApplicationsService = __esm({
"../containers-shared/src/client/services/ApplicationsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
ApplicationsService = class {
static {
__name(this, "ApplicationsService");
}
/**
* Create a new application
* Create a new application. An Application represents an intent to run one or more containers, with the same image, dynamically scheduled based on constraints
* @param requestBody
* @returns Application A newly created application
* @throws ApiError
*/
static createApplication(requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications",
body: requestBody,
mediaType: "application/json",
errors: {
400: `Could not create the application because of input/limits reasons, more details in the error code`,
401: `Unauthorized`,
500: `There has been an internal error`
}
});
}
/**
* List Applications associated with your account
* Lists all the applications that are associated with your account
* @param name Filter applications by name
* @param image Filter applications by image
* @param label Filter applications by label
* @returns ListApplications Get all application associated with your account
* @throws ApiError
*/
static listApplications(name2, image, label) {
return request(OpenAPI, {
method: "GET",
url: "/applications",
query: {
name: name2,
image,
label
},
errors: {
401: `Unauthorized`,
500: `There has been an internal error`
}
});
}
/**
* Get a single application by id
* Returns a single application by id
* @param applicationId
* @returns Application A single application
* @throws ApiError
*/
static getApplication(applicationId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}",
path: {
application_id: applicationId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Modify an application
* Modifies a single application by id.
* @param applicationId
* @param requestBody
* @returns Application Modify application response
* @throws ApiError
*/
static modifyApplication(applicationId, requestBody) {
return request(OpenAPI, {
method: "PATCH",
url: "/applications/{application_id}",
path: {
application_id: applicationId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Could not modify the application because of input/limits reasons, more details in the error code`,
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Delete a single application by id
* Deletes a single application by id
* @param applicationId
* @returns EmptyResponse Delete application response
* @throws ApiError
*/
static deleteApplication(applicationId) {
return request(OpenAPI, {
method: "DELETE",
url: "/applications/{application_id}",
path: {
application_id: applicationId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Application queue status
* Get an application's queue status. Only works under an application with type jobs.
* @param applicationId
* @returns ApplicationStatus Application status with details about the job queue, instances and other metadata for introspection.
* @throws ApiError
*/
static getApplicationStatus(applicationId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/status",
path: {
application_id: applicationId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Create a new job within an application
* Returns the created job
* @param applicationId
* @param requestBody
* @returns ApplicationJob A single job within an application
* @throws ApiError
*/
static createApplicationJob(applicationId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/jobs",
path: {
application_id: applicationId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't create the application job because it has bad inputs`,
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Get an application job by application and job id
* Returns a single application job by id with its current status
* @param applicationId
* @param jobId
* @returns ApplicationJob A single application
* @throws ApiError
*/
static getApplicationJob(applicationId, jobId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/jobs/{job_id}",
path: {
application_id: applicationId,
job_id: jobId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application/Job is not found`,
500: `There has been an internal error`
}
});
}
/**
* Delete an application job by application and job id
* Cleans up the specific job from the Application and all its assoicated resources
* @param applicationId
* @param jobId
* @returns GenericMessageResponse Generic OK response
* @throws ApiError
*/
static deleteApplicationJob(applicationId, jobId) {
return request(OpenAPI, {
method: "DELETE",
url: "/applications/{application_id}/jobs/{job_id}",
path: {
application_id: applicationId,
job_id: jobId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application/Job is not found`,
500: `There has been an internal error`
}
});
}
/**
* Modify an existing application job
* Modify an application job state
* @param applicationId
* @param jobId
* @param requestBody
* @returns ApplicationJob A modified job within an application
* @throws ApiError
*/
static modifyApplicationJob(applicationId, jobId, requestBody) {
return request(OpenAPI, {
method: "PATCH",
url: "/applications/{application_id}/jobs/{job_id}",
path: {
application_id: applicationId,
job_id: jobId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't modify the application job because it has bad inputs`,
401: `Unauthorized`,
404: `Response body when an Application/Job is not found`,
500: `There has been an internal error`
}
});
}
/**
* Create a new rollout for an application
* A rollout can be used to update the application's configuration across instances with minimal downtime.
* @param applicationId
* @param requestBody
* @returns ApplicationRollout
* @throws ApiError
*/
static createApplicationRollout(applicationId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/rollouts",
path: {
application_id: applicationId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't update the application rollout because it has bad inputs`,
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* List rollouts
* List all rollouts within an application
* @param applicationId
* @param limit The amount of rollouts to return. By default it is all of them.
* @param last The last rollout that was used to paginate
* @returns ApplicationRollout
* @throws ApiError
*/
static listApplicationRollouts(applicationId, limit, last) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/rollouts",
path: {
application_id: applicationId
},
query: {
limit,
last
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Get a rollout by id within an application
* View rollout configurations and state for a specific rollout
* @param applicationId
* @param rolloutId
* @returns ApplicationRollout
* @throws ApiError
*/
static getApplicationRollout(applicationId, rolloutId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/rollouts/{rollout_id}",
path: {
application_id: applicationId,
rollout_id: rolloutId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Update a rollout within an application
* A rollout can be updated to modify its current state. Actions include - next, previous, rollback
* @param applicationId
* @param rolloutId
* @param requestBody
* @returns UpdateRolloutResponse
* @throws ApiError
*/
static updateApplicationRollout(applicationId, rolloutId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/rollouts/{rollout_id}",
path: {
application_id: applicationId,
rollout_id: rolloutId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't create the application rollout because it has bad inputs`,
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Delete a rollout within an application by its rollout id
* Cleans up the specific rollout from the Application if it is not in use
* @param applicationId
* @param rolloutId
* @returns EmptyResponse
* @throws ApiError
*/
static deleteApplicationRollout(applicationId, rolloutId) {
return request(OpenAPI, {
method: "DELETE",
url: "/applications/{application_id}/rollouts/{rollout_id}",
path: {
application_id: applicationId,
rollout_id: rolloutId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Get a single applications deployments
* Returns a single applications deployments
* @param applicationId
* @returns ListDeploymentsV2 List of deployments with their corresponding placements
* @throws ApiError
*/
static listDeploymentsByApplication(applicationId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/deployments",
path: {
application_id: applicationId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Get a specific deployment within an application
* Get a deployment by its app and deployment IDs
* @param applicationId
* @param deploymentId
* @returns DeploymentV2 Get a specific deployment along with its respective placements
* @throws ApiError
*/
static getApplicationsV3Deployment(applicationId, deploymentId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/deployments/{deployment_id}",
path: {
application_id: applicationId,
deployment_id: deploymentId
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Get Error`
}
});
}
/**
* Recreate an existing deployment within an application.
* The given existing deployment is deleted and a replacement deployment is created. The latter retains some properties of the former that cannot be set by the client.
*
* @param applicationId
* @param deploymentId
* @param requestBody
* @returns DeploymentV2 Deployment created
* @throws ApiError
*/
static recreateDeploymentV3(applicationId, deploymentId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/deployments/{deployment_id}/recreate",
path: {
application_id: applicationId,
deployment_id: deploymentId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Could not create the deployment because of input/limits reasons, more details in the error code`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Creation Error`
}
});
}
};
}
});
// ../containers-shared/src/client/services/DeploymentsService.ts
var DeploymentsService;
var init_DeploymentsService = __esm({
"../containers-shared/src/client/services/DeploymentsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
DeploymentsService = class {
static {
__name(this, "DeploymentsService");
}
/**
* Get a specific deployment within an application
* Get a deployment by its app and deployment IDs
* @param applicationId
* @param deploymentId
* @returns DeploymentV2 Get a specific deployment along with its respective placements
* @throws ApiError
*/
static getApplicationsV3Deployment(applicationId, deploymentId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/deployments/{deployment_id}",
path: {
application_id: applicationId,
deployment_id: deploymentId
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Get Error`
}
});
}
/**
* Recreate an existing deployment within an application.
* The given existing deployment is deleted and a replacement deployment is created. The latter retains some properties of the former that cannot be set by the client.
*
* @param applicationId
* @param deploymentId
* @param requestBody
* @returns DeploymentV2 Deployment created
* @throws ApiError
*/
static recreateDeploymentV3(applicationId, deploymentId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/deployments/{deployment_id}/recreate",
path: {
application_id: applicationId,
deployment_id: deploymentId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Could not create the deployment because of input/limits reasons, more details in the error code`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Creation Error`
}
});
}
/**
* Create a new deployment
* Creates a new deployment. A Deployment represents an intent to run one container, with image, in a particular location
* @param requestBody
* @returns DeploymentV2 Deployment created
* @throws ApiError
*/
static createDeploymentV2(requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/deployments/v2",
body: requestBody,
mediaType: "application/json",
errors: {
400: `Could not create the deployment because of input/limits reasons, more details in the error code`,
401: `Unauthorized`,
409: `Deployment already exists`,
500: `Deployment Creation Error`
}
});
}
/**
* List deployments
* List all deployments in the current account. Optionally filter them
* @param appId Filter deployments by application id
* @param location Filter deployments by location
* @param image Filter deployments by image
* @param state Filter deployments by placement state
* @param ipv4 Filter deployments by ipv4 address
* @param label Filter deployments by label
* @returns ListDeploymentsV2 List of deployments with their corresponding placements
* @throws ApiError
*/
static listDeploymentsV2(appId, location, image, state2, ipv4, label) {
return request(OpenAPI, {
method: "GET",
url: "/deployments/v2",
query: {
app_id: appId,
location,
image,
state: state2,
ipv4,
label
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
500: `Deployment List Error`
}
});
}
/**
* Get a specific deployment
* Get a deployment by its deployment
* @param deploymentId
* @returns DeploymentV2 Get a specific deployment along with its respective placements
* @throws ApiError
*/
static getDeploymentV2(deploymentId) {
return request(OpenAPI, {
method: "GET",
url: "/deployments/{deployment_id}/v2",
path: {
deployment_id: deploymentId
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Get Error`
}
});
}
/**
* Modify an existing deployment
* Change specific properties in an existing deployment
* @param deploymentId
* @param requestBody
* @returns DeploymentV2 Deployment modified
* @throws ApiError
*/
static modifyDeploymentV2(deploymentId, requestBody) {
return request(OpenAPI, {
method: "PATCH",
url: "/deployments/{deployment_id}/v2",
path: {
deployment_id: deploymentId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't modify the deployment because it surpasses limits or it has bad input`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Modification Error`
}
});
}
/**
* Delete a specific deployment
* Delete a deployment by its deployment ID
* @param deploymentId
* @returns EmptyResponse Delete a specific deployment along with its respective placements
* @throws ApiError
*/
static deleteDeploymentV2(deploymentId) {
return request(OpenAPI, {
method: "DELETE",
url: "/deployments/{deployment_id}/v2",
path: {
deployment_id: deploymentId
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Delete Error`
}
});
}
/**
* Recreate an existing deployment.
* The given existing deployment is deleted and a replacement deployment is created. The latter retains some properties of the former that cannot be set by the client.
*
* @param deploymentId
* @param requestBody
* @returns DeploymentV2 Deployment created
* @throws ApiError
*/
static recreateDeployment(deploymentId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/deployments/{deployment_id}/recreate",
path: {
deployment_id: deploymentId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Could not create the deployment because of input/limits reasons, more details in the error code`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `Deployment Creation Error`
}
});
}
/**
* Replace a deployment
* You can stop the current placement and create a new one. The new one will have the same durable properties of the deployment, but will otherwise be like new
* @param placementId
* @param requestBody
* @returns DeploymentV2 Deployment replaced
* @throws ApiError
*/
static replaceDeployment(placementId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/placements/{placement_id}",
path: {
placement_id: placementId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Responses with 400 status code`,
401: `Unauthorized`,
404: `Placement not found`,
500: `Deployment Replacement Error`
}
});
}
};
}
});
// ../containers-shared/src/client/services/ImageRegistriesService.ts
var ImageRegistriesService;
var init_ImageRegistriesService = __esm({
"../containers-shared/src/client/services/ImageRegistriesService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
ImageRegistriesService = class {
static {
__name(this, "ImageRegistriesService");
}
/**
* Create an image registry protocol that resolves to multiple domains.
* @param requestBody
* @returns ImageRegistryProtocol The image registry protocol was created
* @throws ApiError
*/
static createImageRegistryProtocol(requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/registries/protos",
body: requestBody,
mediaType: "application/json",
errors: {
400: `Bad Request that contains a specific constant code and details object about the error.`,
403: `The registry that is being added is not allowed`,
409: `Image registry protocol already exists`,
500: `There has been an internal error`
}
});
}
/**
* List all image registry protocols.
* @returns ImageRegistryProtocols The image registry protocols in the account
* @throws ApiError
*/
static listImageRegistryProtocols() {
return request(OpenAPI, {
method: "GET",
url: "/registries/protos",
errors: {
500: `There has been an internal error`
}
});
}
/**
* Modify an image registry protocol. The previous list of domains will be replaced by the ones you specify in this endpoint.
* @param requestBody
* @returns ImageRegistryProtocol The image registry protocol was modified
* @throws ApiError
*/
static modifyImageRegistryProtocol(requestBody) {
return request(OpenAPI, {
method: "PUT",
url: "/registries/protos",
body: requestBody,
mediaType: "application/json",
errors: {
400: `Bad Request that contains a specific constant code and details object about the error.`,
403: `The registry that is being added is not allowed`,
404: `Image registry protocol doesn't exist`,
500: `There has been an internal error`
}
});
}
/**
* Delete an image registry protocol. Be careful, if there is deployments running referencing this protocol they won't be able to pull the image.
* @param proto
* @returns EmptyResponse Image registry protocol was deleted successfully
* @throws ApiError
*/
static deleteImageRegistryProto(proto2) {
return request(OpenAPI, {
method: "DELETE",
url: "/registries/protos/{proto}",
path: {
proto: proto2
},
errors: {
400: `The image registry protocol couldn't be deleted because it's referenced by a deployment or application`,
404: `Image registry protocol doesn't exist`,
500: `There has been an internal error`
}
});
}
/**
* Get a JWT to pull from the image registry
* Get a JWT to pull from the image registry specifying its domain
* @param domain
* @param requestBody
* @returns AccountRegistryToken Credentials with 'pull' or 'push' permissions to access the registry
* @throws ApiError
*/
static generateImageRegistryCredentials(domain2, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/registries/{domain}/credentials",
path: {
domain: domain2
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Bad Request that contains a specific constant code and details object about the error.`,
404: `The image registry does not exist`,
409: `The registry was configured as public, so credentials can not be generated`,
500: `There has been an internal error`
}
});
}
/**
* Delete a registry from the account
* Delete a registry from the account, this will make Cloudchamber unable to pull images from the registry
* @param domain
* @returns EmptyResponse The image registry is deleted
* @throws ApiError
*/
static deleteImageRegistry(domain2) {
return request(OpenAPI, {
method: "DELETE",
url: "/registries/{domain}",
path: {
domain: domain2
},
errors: {
404: `The image registry does not exist`,
500: `There has been an internal error`
}
});
}
/**
* Get the list of configured registries in the account
* Get the list of configured registries in the account
* @returns CustomerImageRegistry The list of registries that are added in the account
* @throws ApiError
*/
static listImageRegistries() {
return request(OpenAPI, {
method: "GET",
url: "/registries",
errors: {
500: `There has been an internal error`
}
});
}
/**
* Add a new image registry configuration
* Add a new image registry into your account, so then Cloudflare can pull docker images with public key JWT authentication
* @param requestBody
* @returns CustomerImageRegistry Created a new image registry in the account
* @throws ApiError
*/
static createImageRegistry(requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/registries",
body: requestBody,
mediaType: "application/json",
errors: {
400: `Image registry input is malformed, see the error details`,
403: `The registry that is being added is not allowed`,
409: `The image registry already exists in the account`,
500: `There has been an internal error`
}
});
}
};
}
});
// ../containers-shared/src/client/services/IPsService.ts
var init_IPsService = __esm({
"../containers-shared/src/client/services/IPsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
}
});
// ../containers-shared/src/client/services/JobsService.ts
var init_JobsService = __esm({
"../containers-shared/src/client/services/JobsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
}
});
// ../containers-shared/src/client/services/PlacementsService.ts
var PlacementsService;
var init_PlacementsService = __esm({
"../containers-shared/src/client/services/PlacementsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
PlacementsService = class {
static {
__name(this, "PlacementsService");
}
/**
* List placements
* List all placements under a given deploymentID with all its events
* @param deploymentId
* @returns ListPlacements A list of placements along with its events under a deployment
* @throws ApiError
*/
static listPlacements(deploymentId) {
return request(OpenAPI, {
method: "GET",
url: "/deployments/{deployment_id}/placements",
path: {
deployment_id: deploymentId
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
404: `Deployment not found`,
500: `List Placements Error`
}
});
}
/**
* Get placement
* A Placement represents the lifetime of a single instance of a Deployment
* @param placementId
* @returns PlacementWithEvents A specific placement along with its events
* @throws ApiError
*/
static getPlacement(placementId) {
return request(OpenAPI, {
method: "GET",
url: "/placements/{placement_id}",
path: {
placement_id: placementId
},
errors: {
400: `Unknown account`,
401: `Unauthorized`,
404: `Placement not found`,
500: `Get Placement Error`
}
});
}
/**
* Replace a deployment
* You can stop the current placement and create a new one. The new one will have the same durable properties of the deployment, but will otherwise be like new
* @param placementId
* @param requestBody
* @returns DeploymentV2 Deployment replaced
* @throws ApiError
*/
static replaceDeployment(placementId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/placements/{placement_id}",
path: {
placement_id: placementId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Responses with 400 status code`,
401: `Unauthorized`,
404: `Placement not found`,
500: `Deployment Replacement Error`
}
});
}
};
}
});
// ../containers-shared/src/client/services/RolloutsService.ts
var RolloutsService;
var init_RolloutsService = __esm({
"../containers-shared/src/client/services/RolloutsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
RolloutsService = class {
static {
__name(this, "RolloutsService");
}
/**
* Create a new rollout for an application
* A rollout can be used to update the application's configuration across instances with minimal downtime.
* @param applicationId
* @param requestBody
* @returns ApplicationRollout
* @throws ApiError
*/
static createApplicationRollout(applicationId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/rollouts",
path: {
application_id: applicationId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't update the application rollout because it has bad inputs`,
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* List rollouts
* List all rollouts within an application
* @param applicationId
* @param limit The amount of rollouts to return. By default it is all of them.
* @param last The last rollout that was used to paginate
* @returns ApplicationRollout
* @throws ApiError
*/
static listApplicationRollouts(applicationId, limit, last) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/rollouts",
path: {
application_id: applicationId
},
query: {
limit,
last
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Get a rollout by id within an application
* View rollout configurations and state for a specific rollout
* @param applicationId
* @param rolloutId
* @returns ApplicationRollout
* @throws ApiError
*/
static getApplicationRollout(applicationId, rolloutId) {
return request(OpenAPI, {
method: "GET",
url: "/applications/{application_id}/rollouts/{rollout_id}",
path: {
application_id: applicationId,
rollout_id: rolloutId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Update a rollout within an application
* A rollout can be updated to modify its current state. Actions include - next, previous, rollback
* @param applicationId
* @param rolloutId
* @param requestBody
* @returns UpdateRolloutResponse
* @throws ApiError
*/
static updateApplicationRollout(applicationId, rolloutId, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/applications/{application_id}/rollouts/{rollout_id}",
path: {
application_id: applicationId,
rollout_id: rolloutId
},
body: requestBody,
mediaType: "application/json",
errors: {
400: `Can't create the application rollout because it has bad inputs`,
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
/**
* Delete a rollout within an application by its rollout id
* Cleans up the specific rollout from the Application if it is not in use
* @param applicationId
* @param rolloutId
* @returns EmptyResponse
* @throws ApiError
*/
static deleteApplicationRollout(applicationId, rolloutId) {
return request(OpenAPI, {
method: "DELETE",
url: "/applications/{application_id}/rollouts/{rollout_id}",
path: {
application_id: applicationId,
rollout_id: rolloutId
},
errors: {
401: `Unauthorized`,
404: `Response body when an Application is not found`,
500: `There has been an internal error`
}
});
}
};
}
});
// ../containers-shared/src/client/services/SecretsService.ts
var init_SecretsService = __esm({
"../containers-shared/src/client/services/SecretsService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
}
});
// ../containers-shared/src/client/services/SshPublicKeysService.ts
var SshPublicKeysService;
var init_SshPublicKeysService = __esm({
"../containers-shared/src/client/services/SshPublicKeysService.ts"() {
init_import_meta_url();
init_OpenAPI();
init_request();
SshPublicKeysService = class {
static {
__name(this, "SshPublicKeysService");
}
/**
* Add SSH public key
* Adds a new ssh public key to an account. This can then be associated with a specific deployment during its creation or modification.
* @param requestBody
* @returns SSHPublicKeyItem SSH Public key added successfully
* @throws ApiError
*/
static createSshPublicKey(requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/ssh-public-keys",
body: requestBody,
mediaType: "application/json",
errors: {
401: `Unauthorized`,
500: `Create SSH Public key error`
}
});
}
/**
* List SSH Public keys
* List all SSH Public keys in an account
* @returns ListSSHPublicKeys List SSH Public keys response
* @throws ApiError
*/
static listSshPublicKeys() {
return request(OpenAPI, {
method: "GET",
url: "/ssh-public-keys",
errors: {
401: `Unauthorized`,
500: `List SSH Public keys error`
}
});
}
/**
* Delete SSH public key from the account
* Delete an SSH public key from an account.
* @param sshPublicKeyName
* @returns EmptyResponse SSH Public key was removed successfully
* @throws ApiError
*/
static deleteSshPublicKey(sshPublicKeyName) {
return request(OpenAPI, {
method: "DELETE",
url: "/ssh-public-keys/{sshPublicKeyName}",
path: {
sshPublicKeyName
},
errors: {
401: `Unauthorized`,
404: `Response body when the SSH public key that is trying to be found does not exist`,
500: `There has been an internal error`
}
});
}
};
}
});
// ../containers-shared/src/client/index.ts
var init_client = __esm({
"../containers-shared/src/client/index.ts"() {
init_import_meta_url();
init_ApiError();
init_CancelablePromise();
init_OpenAPI();
init_ApplicationAffinityColocation();
init_ApplicationMutationError();
init_ApplicationRollout();
init_AssignIPv4();
init_AssignIPv6();
init_BadRequestWithCodeError();
init_ContainerNetworkMode();
init_CreateApplicationRolloutRequest();
init_DeploymentCheckKind();
init_DeploymentCheckType();
init_DeploymentMutationError();
init_DeploymentNotFoundError();
init_DeploymentPlacementState();
init_DeploymentQueuedReason();
init_DeploymentSchedulingState();
init_DeploymentType();
init_DurableObjectStatusHealth();
init_EventName();
init_EventType();
init_HTTPMethod();
init_ImageRegistryAlreadyExistsError();
init_ImageRegistryIsPublic();
init_ImageRegistryNotAllowedError();
init_ImageRegistryNotFoundError();
init_ImageRegistryPermissions();
init_ImageRegistryProtocolAlreadyExists();
init_ImageRegistryProtocolIsReferencedError();
init_ImageRegistryProtocolNotFound();
init_InstanceType();
init_IPType();
init_JobStatusHealth();
init_NetworkMode();
init_NodeGroup();
init_PlacementStatusHealth();
init_ProvisionerConfiguration();
init_RolloutStep();
init_SchedulingPolicy();
init_SecretAccessType();
init_SecretNameAlreadyExists();
init_SecretNotFound();
init_SSHPublicKeyNotFoundError();
init_UpdateApplicationRolloutRequest();
init_AccountService();
init_ApplicationsService();
init_DeploymentsService();
init_ImageRegistriesService();
init_IPsService();
init_JobsService();
init_PlacementsService();
init_RolloutsService();
init_SecretsService();
init_SshPublicKeysService();
}
});
// ../containers-shared/src/build.ts
async function constructBuildCommand(options, logger4) {
const platform3 = options.platform ?? "linux/amd64";
const buildCmd = [
"build",
"-t",
options.tag,
"--platform",
platform3,
"--provenance=false"
];
if (options.args) {
for (const arg in options.args) {
buildCmd.push("--build-arg", `${arg}=${options.args[arg]}`);
}
}
if (options.setNetworkToHost) {
buildCmd.push("--network", "host");
}
const dockerfile = (0, import_fs5.readFileSync)(options.pathToDockerfile, "utf-8");
buildCmd.push("-f", "-");
buildCmd.push(options.buildContext);
logger4?.debug(`Building image with command: ${buildCmd.join(" ")}`);
return { buildCmd, dockerfile };
}
function dockerBuild(dockerPath, options) {
let errorHandled = false;
let resolve25;
let reject;
const ready = new Promise((res, rej) => {
resolve25 = res;
reject = rej;
});
const child = (0, import_child_process.spawn)(dockerPath, options.buildCmd, {
stdio: ["pipe", "inherit", "inherit"],
// We need to set detached to true so that the child process
// will control all of its child processed and we can kill
// all of them in case we need to abort the build process
detached: true
});
if (child.stdin !== null) {
child.stdin.write(options.dockerfile);
child.stdin.end();
}
child.on("exit", (code) => {
if (code === 0) {
resolve25();
} else if (!errorHandled) {
errorHandled = true;
reject(new Error(`Docker build exited with code: ${code}`));
}
});
child.on("error", (err) => {
if (!errorHandled) {
errorHandled = true;
reject(err);
}
});
return {
abort: /* @__PURE__ */ __name(() => {
child.unref();
if (child.pid !== void 0) {
process.kill(-child.pid);
}
}, "abort"),
ready
};
}
async function buildImage(dockerPath, options) {
const { buildCmd, dockerfile } = await constructBuildCommand({
tag: options.image_tag,
pathToDockerfile: options.dockerfile,
buildContext: options.image_build_context,
args: options.image_vars,
platform: "linux/amd64"
});
return dockerBuild(dockerPath, { buildCmd, dockerfile });
}
var import_child_process, import_fs5;
var init_build = __esm({
"../containers-shared/src/build.ts"() {
init_import_meta_url();
import_child_process = require("child_process");
import_fs5 = require("fs");
__name(constructBuildCommand, "constructBuildCommand");
__name(dockerBuild, "dockerBuild");
__name(buildImage, "buildImage");
}
});
// ../containers-shared/src/registry.ts
var getCloudflareRegistryWithAccountNamespace, MF_DEV_CONTAINER_PREFIX;
var init_registry = __esm({
"../containers-shared/src/registry.ts"() {
init_import_meta_url();
init_knobs();
getCloudflareRegistryWithAccountNamespace = /* @__PURE__ */ __name((accountID, tag) => {
return `${getCloudflareContainerRegistry()}/${accountID}/${tag}`;
}, "getCloudflareRegistryWithAccountNamespace");
MF_DEV_CONTAINER_PREFIX = "cloudflare-dev";
}
});
// ../containers-shared/src/knobs.ts
function isCloudflareRegistryLink(image) {
const cfRegistry = getCloudflareContainerRegistry();
return image.includes(cfRegistry);
}
var getCloudflareContainerRegistry, getDevContainerImageName;
var init_knobs = __esm({
"../containers-shared/src/knobs.ts"() {
init_import_meta_url();
init_registry();
getCloudflareContainerRegistry = /* @__PURE__ */ __name(() => {
return process.env.CLOUDFLARE_CONTAINER_REGISTRY ?? "registry.cloudflare.com";
}, "getCloudflareContainerRegistry");
__name(isCloudflareRegistryLink, "isCloudflareRegistryLink");
getDevContainerImageName = /* @__PURE__ */ __name((name2, tag) => {
return `${MF_DEV_CONTAINER_PREFIX}/${name2.toLowerCase()}:${tag}`;
}, "getDevContainerImageName");
}
});
// ../containers-shared/src/login.ts
async function dockerLoginManagedRegistry(pathToDocker) {
const expirationMinutes = 15;
const credentials = await ImageRegistriesService.generateImageRegistryCredentials(
getCloudflareContainerRegistry(),
{
expiration_minutes: expirationMinutes,
permissions: [
"push" /* PUSH */,
"pull" /* PULL */
]
}
);
const child = (0, import_node_child_process.spawn)(
pathToDocker,
[
"login",
"--password-stdin",
"--username",
"v1",
getCloudflareContainerRegistry()
],
{ stdio: ["pipe", "inherit", "inherit"] }
).on("error", (err) => {
throw err;
});
child.stdin.write(credentials.password);
child.stdin.end();
await new Promise((resolve25, reject) => {
child.on("close", (code) => {
if (code === 0) {
resolve25();
} else {
reject(new Error(`Login failed with code: ${code}`));
}
});
});
}
var import_node_child_process;
var init_login = __esm({
"../containers-shared/src/login.ts"() {
init_import_meta_url();
import_node_child_process = require("child_process");
init_client();
init_knobs();
__name(dockerLoginManagedRegistry, "dockerLoginManagedRegistry");
}
});
// ../containers-shared/src/inspect.ts
async function dockerImageInspect(dockerPath, options) {
return new Promise((resolve25, reject) => {
const proc = (0, import_child_process2.spawn)(
dockerPath,
["image", "inspect", options.imageTag, "--format", options.formatString],
{
stdio: ["ignore", "pipe", "pipe"]
}
);
let stdout2 = "";
let stderr2 = "";
proc.stdout.on("data", (chunk) => stdout2 += chunk);
proc.stderr.on("data", (chunk) => stderr2 += chunk);
proc.on("close", (code) => {
if (code !== 0) {
return reject(
new Error(`failed inspecting image locally: ${stderr2.trim()}`)
);
}
resolve25(stdout2.trim());
});
proc.on("error", (err) => reject(err));
});
}
var import_child_process2;
var init_inspect = __esm({
"../containers-shared/src/inspect.ts"() {
init_import_meta_url();
import_child_process2 = require("child_process");
__name(dockerImageInspect, "dockerImageInspect");
}
});
// ../containers-shared/src/utils.ts
function isDir(inputPath) {
const stats = (0, import_fs6.statSync)(inputPath);
return stats.isDirectory();
}
function getContainerIdsByImageTags(dockerPath, imageTags) {
const ids = /* @__PURE__ */ new Set();
for (const imageTag of imageTags) {
const containerIdsFromImage = getContainerIdsFromImage(
dockerPath,
imageTag
);
containerIdsFromImage.forEach((id) => ids.add(id));
}
return Array.from(ids);
}
async function checkExposedPorts(dockerPath, options) {
const output = await dockerImageInspect(dockerPath, {
imageTag: options.image_tag,
formatString: "{{ len .Config.ExposedPorts }}"
});
if (output === "0") {
throw new Error(
`The container "${options.class_name}" does not expose any ports. In your Dockerfile, please expose any ports you intend to connect to.
For additional information please see: https://developers.cloudflare.com/containers/local-dev/#exposing-ports.
`
);
}
}
function generateContainerBuildId() {
return (0, import_crypto.randomUUID)().slice(0, 8);
}
function getDockerSocketFromContext(dockerPath) {
try {
const output = runDockerCmdWithOutput(dockerPath, [
"context",
"ls",
"--format",
"json"
]);
const lines = output.trim().split("\n");
const contexts = lines.map((line) => JSON.parse(line));
const currentContext = contexts.find((context2) => context2.Current === true);
if (currentContext && currentContext.DockerEndpoint) {
return currentContext.DockerEndpoint;
}
} catch {
}
return null;
}
function resolveDockerHost(dockerPath) {
if (process.env.WRANGLER_DOCKER_HOST) {
return process.env.WRANGLER_DOCKER_HOST;
}
if (process.env.DOCKER_HOST) {
return process.env.DOCKER_HOST;
}
const contextSocket = getDockerSocketFromContext(dockerPath);
if (contextSocket) {
return contextSocket;
}
return process.platform === "win32" ? "//./pipe/docker_engine" : "unix:///var/run/docker.sock";
}
async function getImageRepoTags(dockerPath, imageTag) {
try {
const output = await dockerImageInspect(dockerPath, {
imageTag,
formatString: "{{ range .RepoTags }}{{ . }}\n{{ end }}"
});
return output.split("\n").filter((tag) => tag.trim() !== "");
} catch {
return [];
}
}
async function cleanupDuplicateImageTags(dockerPath, imageTag) {
try {
const repoTags = await getImageRepoTags(dockerPath, imageTag);
const tagsToRemove = repoTags.filter(
(tag) => tag !== imageTag && tag.startsWith("cloudflare-dev")
);
if (tagsToRemove.length > 0) {
runDockerCmdWithOutput(dockerPath, ["rmi", ...tagsToRemove]);
}
} catch {
}
}
var import_child_process3, import_crypto, import_fs6, import_path5, runDockerCmd, runDockerCmdWithOutput, verifyDockerInstalled, isDockerfile, cleanupContainers, getContainerIdsFromImage;
var init_utils = __esm({
"../containers-shared/src/utils.ts"() {
init_import_meta_url();
import_child_process3 = require("child_process");
import_crypto = require("crypto");
import_fs6 = require("fs");
import_path5 = __toESM(require("path"));
init_inspect();
runDockerCmd = /* @__PURE__ */ __name((dockerPath, args, stdio) => {
let aborted = false;
let resolve25;
let reject;
const ready = new Promise((res, rej) => {
resolve25 = res;
reject = rej;
});
const child = (0, import_child_process3.spawn)(dockerPath, args, {
stdio: stdio ?? "inherit",
// We need to set detached to true so that the child process
// will control all of its child processed and we can kill
// all of them in case we need to abort the build process
detached: true
});
let errorHandled = false;
child.on("close", (code) => {
if (code === 0 || aborted) {
resolve25({ aborted });
} else if (!errorHandled) {
errorHandled = true;
reject(new Error(`Docker command exited with code: ${code}`));
}
});
child.on("error", (err) => {
if (!errorHandled) {
errorHandled = true;
reject(new Error(`Docker command failed: ${err.message}`));
}
});
return {
abort: /* @__PURE__ */ __name(() => {
aborted = true;
child.unref();
if (child.pid !== void 0) {
process.kill(-child.pid);
}
}, "abort"),
ready,
then: /* @__PURE__ */ __name(async (onResolve, onReject) => ready.then(onResolve).catch(onReject), "then")
};
}, "runDockerCmd");
runDockerCmdWithOutput = /* @__PURE__ */ __name((dockerPath, args) => {
try {
const stdout2 = (0, import_child_process3.execFileSync)(dockerPath, args, { encoding: "utf8" });
return stdout2.trim();
} catch (error2) {
throw new Error(
`Failed running docker command: ${error2.message}. Command: ${dockerPath} ${args.join(" ")}`
);
}
}, "runDockerCmdWithOutput");
verifyDockerInstalled = /* @__PURE__ */ __name(async (dockerPath, isDev = true) => {
try {
await runDockerCmd(dockerPath, ["info"], ["inherit", "pipe", "pipe"]);
} catch {
throw new Error(
`The Docker CLI could not be launched. Please ensure that the Docker CLI is installed and the daemon is running.
Other container tooling that is compatible with the Docker CLI and engine may work, but is not yet guaranteed to do so. You can specify an executable with the environment variable WRANGLER_DOCKER_BIN and a socket with DOCKER_HOST.${isDev ? "\nTo suppress this error if you do not intend on triggering any container instances, set dev.enable_containers to false in your Wrangler config or passing in --enable-containers=false." : ""}`
);
}
}, "verifyDockerInstalled");
__name(isDir, "isDir");
isDockerfile = /* @__PURE__ */ __name((image, configPath) => {
const baseDir = configPath ? import_path5.default.dirname(configPath) : process.cwd();
const maybeDockerfile = import_path5.default.resolve(baseDir, image);
if ((0, import_fs6.existsSync)(maybeDockerfile)) {
if (isDir(maybeDockerfile)) {
throw new Error(
`${image} is a directory, you should specify a path to the Dockerfile`
);
}
return true;
}
const errorPrefix = `The image "${image}" does not appear to be a valid path to a Dockerfile, or a valid image registry path:
`;
try {
new URL(`https://${image}`);
} catch (e7) {
if (e7 instanceof Error) {
throw new Error(errorPrefix + e7.message);
}
throw e7;
}
const imageParts = image.split("/");
if (!imageParts[imageParts.length - 1]?.includes(":")) {
throw new Error(
errorPrefix + `If this is an image registry path, it needs to include at least a tag ':' (e.g: docker.io/httpd:1)`
);
}
if (image.includes("://")) {
throw new Error(
errorPrefix + `Image reference should not include the protocol part (e.g: docker.io/httpd:1, not https://docker.io/httpd:1)`
);
}
return false;
}, "isDockerfile");
cleanupContainers = /* @__PURE__ */ __name((dockerPath, imageTags) => {
try {
const containerIds = getContainerIdsByImageTags(dockerPath, imageTags);
if (containerIds.length === 0) {
return true;
}
runDockerCmdWithOutput(dockerPath, ["rm", "--force", ...containerIds]);
return true;
} catch {
return false;
}
}, "cleanupContainers");
__name(getContainerIdsByImageTags, "getContainerIdsByImageTags");
getContainerIdsFromImage = /* @__PURE__ */ __name((dockerPath, ancestorImage) => {
const output = runDockerCmdWithOutput(dockerPath, [
"ps",
"-a",
"--filter",
`ancestor=${ancestorImage}`,
"--format",
"{{.ID}}"
]);
return output.split("\n").filter((line) => line.trim());
}, "getContainerIdsFromImage");
__name(checkExposedPorts, "checkExposedPorts");
__name(generateContainerBuildId, "generateContainerBuildId");
__name(getDockerSocketFromContext, "getDockerSocketFromContext");
__name(resolveDockerHost, "resolveDockerHost");
__name(getImageRepoTags, "getImageRepoTags");
__name(cleanupDuplicateImageTags, "cleanupDuplicateImageTags");
}
});
// ../containers-shared/src/types.ts
var init_types = __esm({
"../containers-shared/src/types.ts"() {
init_import_meta_url();
}
});
// ../containers-shared/src/images.ts
async function pullImage(dockerPath, options) {
await dockerLoginManagedRegistry(dockerPath);
const pull = runDockerCmd(dockerPath, [
"pull",
options.image_uri,
// All containers running on our platform need to be built for amd64 architecture, but by default docker pull seems to look for an image matching the host system, so we need to specify this here
"--platform",
"linux/amd64"
]);
const ready = pull.ready.then(async ({ aborted }) => {
if (!aborted) {
await runDockerCmd(dockerPath, [
"tag",
options.image_uri,
options.image_tag
]);
}
});
return {
abort: /* @__PURE__ */ __name(() => {
pull.abort();
}, "abort"),
ready
};
}
async function prepareContainerImagesForDev(args) {
const {
dockerPath,
containerOptions,
onContainerImagePreparationStart,
onContainerImagePreparationEnd
} = args;
let aborted = false;
if (process.platform === "win32") {
throw new Error(
"Local development with containers is currently not supported on Windows. You should use WSL instead. You can also set `enable_containers` to false if you do not need to develop the container part of your application."
);
}
await verifyDockerInstalled(dockerPath);
for (const options of containerOptions) {
if ("dockerfile" in options) {
const build5 = await buildImage(dockerPath, options);
onContainerImagePreparationStart({
containerOptions: options,
abort: /* @__PURE__ */ __name(() => {
aborted = true;
build5.abort();
}, "abort")
});
await build5.ready;
onContainerImagePreparationEnd({
containerOptions: options
});
} else {
if (!isCloudflareRegistryLink(options.image_uri)) {
throw new Error(
`Image "${options.image_uri}" is a registry link but does not point to the Cloudflare container registry.
To use an existing image from another repository, see https://developers.cloudflare.com/containers/image-management/#using-existing-images`
);
}
const pull = await pullImage(dockerPath, options);
onContainerImagePreparationStart({
containerOptions: options,
abort: /* @__PURE__ */ __name(() => {
aborted = true;
pull.abort();
}, "abort")
});
await pull.ready;
onContainerImagePreparationEnd({
containerOptions: options
});
}
if (!aborted) {
await cleanupDuplicateImageTags(dockerPath, options.image_tag);
await checkExposedPorts(dockerPath, options);
}
}
}
function resolveImageName(accountId, image) {
let url4;
try {
url4 = new URL(`http://${image}`);
} catch {
return image;
}
if (url4.hostname !== getCloudflareContainerRegistry()) {
return image;
}
if (url4.pathname.startsWith(`/${accountId}`)) {
return image;
}
return `${url4.hostname}/${accountId}${url4.pathname}`;
}
var init_images = __esm({
"../containers-shared/src/images.ts"() {
init_import_meta_url();
init_build();
init_knobs();
init_login();
init_utils();
__name(pullImage, "pullImage");
__name(prepareContainerImagesForDev, "prepareContainerImagesForDev");
__name(resolveImageName, "resolveImageName");
}
});
// ../containers-shared/index.ts
var init_containers_shared = __esm({
"../containers-shared/index.ts"() {
init_import_meta_url();
init_client();
init_build();
init_login();
init_knobs();
init_utils();
init_types();
init_inspect();
init_registry();
init_images();
}
});
// ../../node_modules/.pnpm/@webcontainer+env@1.1.0/node_modules/@webcontainer/env/dist/index.js
var require_dist = __commonJS({
"../../node_modules/.pnpm/@webcontainer+env@1.1.0/node_modules/@webcontainer/env/dist/index.js"(exports2, module3) {
init_import_meta_url();
var c6 = Object.defineProperty;
var g6 = Object.getOwnPropertyDescriptor;
var y4 = Object.getOwnPropertyNames;
var d6 = Object.prototype.hasOwnProperty;
var a5 = /* @__PURE__ */ __name((e7, t7) => c6(e7, "name", { value: t7, configurable: true }), "a");
var b6 = /* @__PURE__ */ __name((e7, t7) => {
for (var o5 in t7) c6(e7, o5, { get: t7[o5], enumerable: true });
}, "b");
var P3 = /* @__PURE__ */ __name((e7, t7, o5, u5) => {
if (t7 && typeof t7 == "object" || typeof t7 == "function") for (let s5 of y4(t7)) !d6.call(e7, s5) && s5 !== o5 && c6(e7, s5, { get: /* @__PURE__ */ __name(() => t7[s5], "get"), enumerable: !(u5 = g6(t7, s5)) || u5.enumerable });
return e7;
}, "P");
var U3 = /* @__PURE__ */ __name((e7) => P3(c6({}, "__esModule", { value: true }), e7), "U");
var x6 = {};
b6(x6, { HostURL: /* @__PURE__ */ __name(() => n6, "HostURL"), isWebContainer: /* @__PURE__ */ __name(() => h6, "isWebContainer") });
module3.exports = U3(x6);
var r7;
try {
r7 = require("@blitz/internal/env");
} catch (e7) {
}
function h6() {
return r7 != null && process.versions.webcontainer != null;
}
__name(h6, "h");
a5(h6, "isWebContainer");
function p6(e7) {
let t7 = r7 == null ? void 0 : r7.createServiceHostname(e7);
if (!t7) throw new Error("Failed to construct service hostname");
return t7;
}
__name(p6, "p");
a5(p6, "_createServiceHostname");
function f6(e7) {
return r7 == null ? void 0 : r7.isServiceUrl(e7);
}
__name(f6, "f");
a5(f6, "_isServiceUrl");
function l6(e7) {
return r7 == null ? void 0 : r7.isLocalhost(e7);
}
__name(l6, "l");
a5(l6, "_isLocalhost");
var n6 = class {
static {
__name(this, "n");
}
constructor(t7) {
this._url = t7;
if (this._port = this._url.port, h6() && l6(this._url.hostname)) {
let o5 = p6(this._port);
this._url.host = o5, this._port === this._url.port && (this._url.port = "");
}
}
static parse(t7) {
return t7 = typeof t7 == "string" ? new URL(t7) : t7, new n6(t7);
}
get port() {
return h6() ? this._port : this._url.port;
}
get hash() {
return this._url.hash;
}
get host() {
return this._url.host;
}
get hostname() {
return this._url.hostname;
}
get href() {
return this._url.href;
}
get origin() {
return this._url.origin;
}
get username() {
return this._url.username;
}
get password() {
return this._url.password;
}
get pathname() {
return this._url.pathname;
}
get protocol() {
return this._url.protocol;
}
get search() {
return this._url.search;
}
get searchParams() {
return this._url.searchParams;
}
update(t7) {
var u5;
let o5 = h6();
for (let s5 in t7) {
let i5 = (u5 = t7[s5]) != null ? u5 : "";
if (o5) switch (s5) {
case "port": {
if (this._port = i5, (l6(this._url.hostname) || f6(this._url.hostname)) && (this._url.host = p6(i5), this._port !== this._url.port)) continue;
break;
}
case "host": {
let [m6, _4 = this._port] = i5.split(":");
this._port = _4, l6(m6) && (i5 = p6(_4));
break;
}
case "hostname": {
if (l6(i5)) {
if (/\/|:/.test(i5)) continue;
i5 = p6(this._port);
} else this._url.port = this._port;
break;
}
case "href": {
this._url = n6.parse(i5);
continue;
}
}
this._url[s5] = i5;
}
return this;
}
toString() {
return this._url.toString();
}
toJSON() {
return this._url.toJSON();
}
};
a5(n6, "HostURL");
}
});
// ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/esm/index.js
function dedent(templ) {
var values = [];
for (var _i2 = 1; _i2 < arguments.length; _i2++) {
values[_i2 - 1] = arguments[_i2];
}
var strings = Array.from(typeof templ === "string" ? [templ] : templ);
strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
var indentLengths = strings.reduce(function(arr, str) {
var matches = str.match(/\n([\t ]+|(?!\s).)/g);
if (matches) {
return arr.concat(matches.map(function(match2) {
var _a4, _b2;
return (_b2 = (_a4 = match2.match(/[\t ]/g)) === null || _a4 === void 0 ? void 0 : _a4.length) !== null && _b2 !== void 0 ? _b2 : 0;
}));
}
return arr;
}, []);
if (indentLengths.length) {
var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
strings = strings.map(function(str) {
return str.replace(pattern_1, "\n");
});
}
strings[0] = strings[0].replace(/^\r?\n/, "");
var string = strings[0];
values.forEach(function(value, i5) {
var endentations = string.match(/(?:^|\n)( *)$/);
var endentation = endentations ? endentations[1] : "";
var indentedValue = value;
if (typeof value === "string" && value.includes("\n")) {
indentedValue = String(value).split("\n").map(function(str, i6) {
return i6 === 0 ? str : "" + endentation + str;
}).join("\n");
}
string += indentedValue + strings[i5 + 1];
});
return string;
}
var esm_default2;
var init_esm2 = __esm({
"../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/esm/index.js"() {
init_import_meta_url();
__name(dedent, "dedent");
esm_default2 = dedent;
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/parser.js
var require_parser = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/parser.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var ParserEND = 1114112;
var ParserError = class _ParserError extends Error {
static {
__name(this, "ParserError");
}
/* istanbul ignore next */
constructor(msg, filename, linenumber) {
super("[ParserError] " + msg, filename, linenumber);
this.name = "ParserError";
this.code = "ParserError";
if (Error.captureStackTrace) Error.captureStackTrace(this, _ParserError);
}
};
var State = class {
static {
__name(this, "State");
}
constructor(parser2) {
this.parser = parser2;
this.buf = "";
this.returned = null;
this.result = null;
this.resultTable = null;
this.resultArr = null;
}
};
var Parser2 = class {
static {
__name(this, "Parser");
}
constructor() {
this.pos = 0;
this.col = 0;
this.line = 0;
this.obj = {};
this.ctx = this.obj;
this.stack = [];
this._buf = "";
this.char = null;
this.ii = 0;
this.state = new State(this.parseStart);
}
parse(str) {
if (str.length === 0 || str.length == null) return;
this._buf = String(str);
this.ii = -1;
this.char = -1;
let getNext;
while (getNext === false || this.nextChar()) {
getNext = this.runOne();
}
this._buf = null;
}
nextChar() {
if (this.char === 10) {
++this.line;
this.col = -1;
}
++this.ii;
this.char = this._buf.codePointAt(this.ii);
++this.pos;
++this.col;
return this.haveBuffer();
}
haveBuffer() {
return this.ii < this._buf.length;
}
runOne() {
return this.state.parser.call(this, this.state.returned);
}
finish() {
this.char = ParserEND;
let last;
do {
last = this.state.parser;
this.runOne();
} while (this.state.parser !== last);
this.ctx = null;
this.state = null;
this._buf = null;
return this.obj;
}
next(fn2) {
if (typeof fn2 !== "function") throw new ParserError("Tried to set state to non-existent state: " + JSON.stringify(fn2));
this.state.parser = fn2;
}
goto(fn2) {
this.next(fn2);
return this.runOne();
}
call(fn2, returnWith) {
if (returnWith) this.next(returnWith);
this.stack.push(this.state);
this.state = new State(fn2);
}
callNow(fn2, returnWith) {
this.call(fn2, returnWith);
return this.runOne();
}
return(value) {
if (this.stack.length === 0) throw this.error(new ParserError("Stack underflow"));
if (value === void 0) value = this.state.buf;
this.state = this.stack.pop();
this.state.returned = value;
}
returnNow(value) {
this.return(value);
return this.runOne();
}
consume() {
if (this.char === ParserEND) throw this.error(new ParserError("Unexpected end-of-buffer"));
this.state.buf += this._buf[this.ii];
}
error(err) {
err.line = this.line;
err.col = this.col;
err.pos = this.pos;
return err;
}
/* istanbul ignore next */
parseStart() {
throw new ParserError("Must declare a parseStart method");
}
};
Parser2.END = ParserEND;
Parser2.Error = ParserError;
module3.exports = Parser2;
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-datetime.js
var require_create_datetime = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-datetime.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (value) => {
const date = new Date(value);
if (isNaN(date)) {
throw new TypeError("Invalid Datetime");
} else {
return date;
}
};
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/format-num.js
var require_format_num = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/format-num.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (d6, num) => {
num = String(num);
while (num.length < d6) num = "0" + num;
return num;
};
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-datetime-float.js
var require_create_datetime_float = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var f6 = require_format_num();
var FloatingDateTime = class extends Date {
static {
__name(this, "FloatingDateTime");
}
constructor(value) {
super(value + "Z");
this.isFloating = true;
}
toISOString() {
const date = `${this.getUTCFullYear()}-${f6(2, this.getUTCMonth() + 1)}-${f6(2, this.getUTCDate())}`;
const time = `${f6(2, this.getUTCHours())}:${f6(2, this.getUTCMinutes())}:${f6(2, this.getUTCSeconds())}.${f6(3, this.getUTCMilliseconds())}`;
return `${date}T${time}`;
}
};
module3.exports = (value) => {
const date = new FloatingDateTime(value);
if (isNaN(date)) {
throw new TypeError("Invalid Datetime");
} else {
return date;
}
};
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-date.js
var require_create_date = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-date.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var f6 = require_format_num();
var DateTime = global.Date;
var Date2 = class extends DateTime {
static {
__name(this, "Date");
}
constructor(value) {
super(value);
this.isDate = true;
}
toISOString() {
return `${this.getUTCFullYear()}-${f6(2, this.getUTCMonth() + 1)}-${f6(2, this.getUTCDate())}`;
}
};
module3.exports = (value) => {
const date = new Date2(value);
if (isNaN(date)) {
throw new TypeError("Invalid Datetime");
} else {
return date;
}
};
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-time.js
var require_create_time = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/create-time.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var f6 = require_format_num();
var Time = class extends Date {
static {
__name(this, "Time");
}
constructor(value) {
super(`0000-01-01T${value}Z`);
this.isTime = true;
}
toISOString() {
return `${f6(2, this.getUTCHours())}:${f6(2, this.getUTCMinutes())}:${f6(2, this.getUTCSeconds())}.${f6(3, this.getUTCMilliseconds())}`;
}
};
module3.exports = (value) => {
const date = new Time(value);
if (isNaN(date)) {
throw new TypeError("Invalid Datetime");
} else {
return date;
}
};
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/toml-parser.js
var require_toml_parser = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/lib/toml-parser.js"(exports, module) {
"use strict";
init_import_meta_url();
module.exports = makeParserClass(require_parser());
module.exports.makeParserClass = makeParserClass;
var TomlError = class _TomlError extends Error {
static {
__name(this, "TomlError");
}
constructor(msg) {
super(msg);
this.name = "TomlError";
if (Error.captureStackTrace) Error.captureStackTrace(this, _TomlError);
this.fromTOML = true;
this.wrapped = null;
}
};
TomlError.wrap = (err) => {
const terr = new TomlError(err.message);
terr.code = err.code;
terr.wrapped = err;
return terr;
};
module.exports.TomlError = TomlError;
var createDateTime = require_create_datetime();
var createDateTimeFloat = require_create_datetime_float();
var createDate = require_create_date();
var createTime = require_create_time();
var CTRL_I = 9;
var CTRL_J = 10;
var CTRL_M = 13;
var CTRL_CHAR_BOUNDARY = 31;
var CHAR_SP = 32;
var CHAR_QUOT = 34;
var CHAR_NUM = 35;
var CHAR_APOS = 39;
var CHAR_PLUS = 43;
var CHAR_COMMA = 44;
var CHAR_HYPHEN = 45;
var CHAR_PERIOD = 46;
var CHAR_0 = 48;
var CHAR_1 = 49;
var CHAR_7 = 55;
var CHAR_9 = 57;
var CHAR_COLON = 58;
var CHAR_EQUALS = 61;
var CHAR_A = 65;
var CHAR_E = 69;
var CHAR_F = 70;
var CHAR_T = 84;
var CHAR_U = 85;
var CHAR_Z = 90;
var CHAR_LOWBAR = 95;
var CHAR_a = 97;
var CHAR_b = 98;
var CHAR_e = 101;
var CHAR_f = 102;
var CHAR_i = 105;
var CHAR_l = 108;
var CHAR_n = 110;
var CHAR_o = 111;
var CHAR_r = 114;
var CHAR_s = 115;
var CHAR_t = 116;
var CHAR_u = 117;
var CHAR_x = 120;
var CHAR_z = 122;
var CHAR_LCUB = 123;
var CHAR_RCUB = 125;
var CHAR_LSQB = 91;
var CHAR_BSOL = 92;
var CHAR_RSQB = 93;
var CHAR_DEL = 127;
var SURROGATE_FIRST = 55296;
var SURROGATE_LAST = 57343;
var escapes = {
[CHAR_b]: "\b",
[CHAR_t]: " ",
[CHAR_n]: "\n",
[CHAR_f]: "\f",
[CHAR_r]: "\r",
[CHAR_QUOT]: '"',
[CHAR_BSOL]: "\\"
};
function isDigit(cp3) {
return cp3 >= CHAR_0 && cp3 <= CHAR_9;
}
__name(isDigit, "isDigit");
function isHexit(cp3) {
return cp3 >= CHAR_A && cp3 <= CHAR_F || cp3 >= CHAR_a && cp3 <= CHAR_f || cp3 >= CHAR_0 && cp3 <= CHAR_9;
}
__name(isHexit, "isHexit");
function isBit(cp3) {
return cp3 === CHAR_1 || cp3 === CHAR_0;
}
__name(isBit, "isBit");
function isOctit(cp3) {
return cp3 >= CHAR_0 && cp3 <= CHAR_7;
}
__name(isOctit, "isOctit");
function isAlphaNumQuoteHyphen(cp3) {
return cp3 >= CHAR_A && cp3 <= CHAR_Z || cp3 >= CHAR_a && cp3 <= CHAR_z || cp3 >= CHAR_0 && cp3 <= CHAR_9 || cp3 === CHAR_APOS || cp3 === CHAR_QUOT || cp3 === CHAR_LOWBAR || cp3 === CHAR_HYPHEN;
}
__name(isAlphaNumQuoteHyphen, "isAlphaNumQuoteHyphen");
function isAlphaNumHyphen(cp3) {
return cp3 >= CHAR_A && cp3 <= CHAR_Z || cp3 >= CHAR_a && cp3 <= CHAR_z || cp3 >= CHAR_0 && cp3 <= CHAR_9 || cp3 === CHAR_LOWBAR || cp3 === CHAR_HYPHEN;
}
__name(isAlphaNumHyphen, "isAlphaNumHyphen");
var _type = Symbol("type");
var _declared = Symbol("declared");
var hasOwnProperty = Object.prototype.hasOwnProperty;
var defineProperty = Object.defineProperty;
var descriptor = { configurable: true, enumerable: true, writable: true, value: void 0 };
function hasKey(obj, key) {
if (hasOwnProperty.call(obj, key)) return true;
if (key === "__proto__") defineProperty(obj, "__proto__", descriptor);
return false;
}
__name(hasKey, "hasKey");
var INLINE_TABLE = Symbol("inline-table");
function InlineTable() {
return Object.defineProperties({}, {
[_type]: { value: INLINE_TABLE }
});
}
__name(InlineTable, "InlineTable");
function isInlineTable(obj) {
if (obj === null || typeof obj !== "object") return false;
return obj[_type] === INLINE_TABLE;
}
__name(isInlineTable, "isInlineTable");
var TABLE = Symbol("table");
function Table() {
return Object.defineProperties({}, {
[_type]: { value: TABLE },
[_declared]: { value: false, writable: true }
});
}
__name(Table, "Table");
function isTable(obj) {
if (obj === null || typeof obj !== "object") return false;
return obj[_type] === TABLE;
}
__name(isTable, "isTable");
var _contentType = Symbol("content-type");
var INLINE_LIST = Symbol("inline-list");
function InlineList(type) {
return Object.defineProperties([], {
[_type]: { value: INLINE_LIST },
[_contentType]: { value: type }
});
}
__name(InlineList, "InlineList");
function isInlineList(obj) {
if (obj === null || typeof obj !== "object") return false;
return obj[_type] === INLINE_LIST;
}
__name(isInlineList, "isInlineList");
var LIST = Symbol("list");
function List() {
return Object.defineProperties([], {
[_type]: { value: LIST }
});
}
__name(List, "List");
function isList(obj) {
if (obj === null || typeof obj !== "object") return false;
return obj[_type] === LIST;
}
__name(isList, "isList");
var _custom;
try {
const utilInspect = eval("require('util').inspect");
_custom = utilInspect.custom;
} catch (_4) {
}
var _inspect = _custom || "inspect";
var BoxedBigInt = class {
static {
__name(this, "BoxedBigInt");
}
constructor(value) {
try {
this.value = global.BigInt.asIntN(64, value);
} catch (_4) {
this.value = null;
}
Object.defineProperty(this, _type, { value: INTEGER });
}
isNaN() {
return this.value === null;
}
/* istanbul ignore next */
toString() {
return String(this.value);
}
/* istanbul ignore next */
[_inspect]() {
return `[BigInt: ${this.toString()}]}`;
}
valueOf() {
return this.value;
}
};
var INTEGER = Symbol("integer");
function Integer(value) {
let num = Number(value);
if (Object.is(num, -0)) num = 0;
if (global.BigInt && !Number.isSafeInteger(num)) {
return new BoxedBigInt(value);
} else {
return Object.defineProperties(new Number(num), {
isNaN: { value: /* @__PURE__ */ __name(function() {
return isNaN(this);
}, "value") },
[_type]: { value: INTEGER },
[_inspect]: { value: /* @__PURE__ */ __name(() => `[Integer: ${value}]`, "value") }
});
}
}
__name(Integer, "Integer");
function isInteger(obj) {
if (obj === null || typeof obj !== "object") return false;
return obj[_type] === INTEGER;
}
__name(isInteger, "isInteger");
var FLOAT = Symbol("float");
function Float(value) {
return Object.defineProperties(new Number(value), {
[_type]: { value: FLOAT },
[_inspect]: { value: /* @__PURE__ */ __name(() => `[Float: ${value}]`, "value") }
});
}
__name(Float, "Float");
function isFloat(obj) {
if (obj === null || typeof obj !== "object") return false;
return obj[_type] === FLOAT;
}
__name(isFloat, "isFloat");
function tomlType(value) {
const type = typeof value;
if (type === "object") {
if (value === null) return "null";
if (value instanceof Date) return "datetime";
if (_type in value) {
switch (value[_type]) {
case INLINE_TABLE:
return "inline-table";
case INLINE_LIST:
return "inline-list";
/* istanbul ignore next */
case TABLE:
return "table";
/* istanbul ignore next */
case LIST:
return "list";
case FLOAT:
return "float";
case INTEGER:
return "integer";
}
}
}
return type;
}
__name(tomlType, "tomlType");
function makeParserClass(Parser2) {
class TOMLParser extends Parser2 {
static {
__name(this, "TOMLParser");
}
constructor() {
super();
this.ctx = this.obj = Table();
}
/* MATCH HELPER */
atEndOfWord() {
return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
}
atEndOfLine() {
return this.char === Parser2.END || this.char === CTRL_J || this.char === CTRL_M;
}
parseStart() {
if (this.char === Parser2.END) {
return null;
} else if (this.char === CHAR_LSQB) {
return this.call(this.parseTableOrList);
} else if (this.char === CHAR_NUM) {
return this.call(this.parseComment);
} else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
return null;
} else if (isAlphaNumQuoteHyphen(this.char)) {
return this.callNow(this.parseAssignStatement);
} else {
throw this.error(new TomlError(`Unknown character "${this.char}"`));
}
}
// HELPER, this strips any whitespace and comments to the end of the line
// then RETURNS. Last state in a production.
parseWhitespaceToEOL() {
if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
return null;
} else if (this.char === CHAR_NUM) {
return this.goto(this.parseComment);
} else if (this.char === Parser2.END || this.char === CTRL_J) {
return this.return();
} else {
throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"));
}
}
/* ASSIGNMENT: key = value */
parseAssignStatement() {
return this.callNow(this.parseAssign, this.recordAssignStatement);
}
recordAssignStatement(kv) {
let target = this.ctx;
let finalKey = kv.key.pop();
for (let kw of kv.key) {
if (hasKey(target, kw) && !isTable(target[kw])) {
throw this.error(new TomlError("Can't redefine existing key"));
}
target = target[kw] = target[kw] || Table();
}
if (hasKey(target, finalKey)) {
throw this.error(new TomlError("Can't redefine existing key"));
}
target[_declared] = true;
if (isInteger(kv.value) || isFloat(kv.value)) {
target[finalKey] = kv.value.valueOf();
} else {
target[finalKey] = kv.value;
}
return this.goto(this.parseWhitespaceToEOL);
}
/* ASSSIGNMENT expression, key = value possibly inside an inline table */
parseAssign() {
return this.callNow(this.parseKeyword, this.recordAssignKeyword);
}
recordAssignKeyword(key) {
if (this.state.resultTable) {
this.state.resultTable.push(key);
} else {
this.state.resultTable = [key];
}
return this.goto(this.parseAssignKeywordPreDot);
}
parseAssignKeywordPreDot() {
if (this.char === CHAR_PERIOD) {
return this.next(this.parseAssignKeywordPostDot);
} else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
return this.goto(this.parseAssignEqual);
}
}
parseAssignKeywordPostDot() {
if (this.char !== CHAR_SP && this.char !== CTRL_I) {
return this.callNow(this.parseKeyword, this.recordAssignKeyword);
}
}
parseAssignEqual() {
if (this.char === CHAR_EQUALS) {
return this.next(this.parseAssignPreValue);
} else {
throw this.error(new TomlError('Invalid character, expected "="'));
}
}
parseAssignPreValue() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else {
return this.callNow(this.parseValue, this.recordAssignValue);
}
}
recordAssignValue(value) {
return this.returnNow({ key: this.state.resultTable, value });
}
/* COMMENTS: #...eol */
parseComment() {
do {
if (this.char === Parser2.END || this.char === CTRL_J) {
return this.return();
} else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
throw this.errorControlCharIn("comments");
}
} while (this.nextChar());
}
/* TABLES AND LISTS, [foo] and [[foo]] */
parseTableOrList() {
if (this.char === CHAR_LSQB) {
this.next(this.parseList);
} else {
return this.goto(this.parseTable);
}
}
/* TABLE [foo.bar.baz] */
parseTable() {
this.ctx = this.obj;
return this.goto(this.parseTableNext);
}
parseTableNext() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else {
return this.callNow(this.parseKeyword, this.parseTableMore);
}
}
parseTableMore(keyword) {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else if (this.char === CHAR_RSQB) {
if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
throw this.error(new TomlError("Can't redefine existing key"));
} else {
this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
this.ctx[_declared] = true;
}
return this.next(this.parseWhitespaceToEOL);
} else if (this.char === CHAR_PERIOD) {
if (!hasKey(this.ctx, keyword)) {
this.ctx = this.ctx[keyword] = Table();
} else if (isTable(this.ctx[keyword])) {
this.ctx = this.ctx[keyword];
} else if (isList(this.ctx[keyword])) {
this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
} else {
throw this.error(new TomlError("Can't redefine existing key"));
}
return this.next(this.parseTableNext);
} else {
throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
}
}
/* LIST [[a.b.c]] */
parseList() {
this.ctx = this.obj;
return this.goto(this.parseListNext);
}
parseListNext() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else {
return this.callNow(this.parseKeyword, this.parseListMore);
}
}
parseListMore(keyword) {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else if (this.char === CHAR_RSQB) {
if (!hasKey(this.ctx, keyword)) {
this.ctx[keyword] = List();
}
if (isInlineList(this.ctx[keyword])) {
throw this.error(new TomlError("Can't extend an inline array"));
} else if (isList(this.ctx[keyword])) {
const next = Table();
this.ctx[keyword].push(next);
this.ctx = next;
} else {
throw this.error(new TomlError("Can't redefine an existing key"));
}
return this.next(this.parseListEnd);
} else if (this.char === CHAR_PERIOD) {
if (!hasKey(this.ctx, keyword)) {
this.ctx = this.ctx[keyword] = Table();
} else if (isInlineList(this.ctx[keyword])) {
throw this.error(new TomlError("Can't extend an inline array"));
} else if (isInlineTable(this.ctx[keyword])) {
throw this.error(new TomlError("Can't extend an inline table"));
} else if (isList(this.ctx[keyword])) {
this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
} else if (isTable(this.ctx[keyword])) {
this.ctx = this.ctx[keyword];
} else {
throw this.error(new TomlError("Can't redefine an existing key"));
}
return this.next(this.parseListNext);
} else {
throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
}
}
parseListEnd(keyword) {
if (this.char === CHAR_RSQB) {
return this.next(this.parseWhitespaceToEOL);
} else {
throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
}
}
/* VALUE string, number, boolean, inline list, inline object */
parseValue() {
if (this.char === Parser2.END) {
throw this.error(new TomlError("Key without value"));
} else if (this.char === CHAR_QUOT) {
return this.next(this.parseDoubleString);
}
if (this.char === CHAR_APOS) {
return this.next(this.parseSingleString);
} else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
return this.goto(this.parseNumberSign);
} else if (this.char === CHAR_i) {
return this.next(this.parseInf);
} else if (this.char === CHAR_n) {
return this.next(this.parseNan);
} else if (isDigit(this.char)) {
return this.goto(this.parseNumberOrDateTime);
} else if (this.char === CHAR_t || this.char === CHAR_f) {
return this.goto(this.parseBoolean);
} else if (this.char === CHAR_LSQB) {
return this.call(this.parseInlineList, this.recordValue);
} else if (this.char === CHAR_LCUB) {
return this.call(this.parseInlineTable, this.recordValue);
} else {
throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"));
}
}
recordValue(value) {
return this.returnNow(value);
}
parseInf() {
if (this.char === CHAR_n) {
return this.next(this.parseInf2);
} else {
throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
}
}
parseInf2() {
if (this.char === CHAR_f) {
if (this.state.buf === "-") {
return this.return(-Infinity);
} else {
return this.return(Infinity);
}
} else {
throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
}
}
parseNan() {
if (this.char === CHAR_a) {
return this.next(this.parseNan2);
} else {
throw this.error(new TomlError('Unexpected character, expected "nan"'));
}
}
parseNan2() {
if (this.char === CHAR_n) {
return this.return(NaN);
} else {
throw this.error(new TomlError('Unexpected character, expected "nan"'));
}
}
/* KEYS, barewords or basic, literal, or dotted */
parseKeyword() {
if (this.char === CHAR_QUOT) {
return this.next(this.parseBasicString);
} else if (this.char === CHAR_APOS) {
return this.next(this.parseLiteralString);
} else {
return this.goto(this.parseBareKey);
}
}
/* KEYS: barewords */
parseBareKey() {
do {
if (this.char === Parser2.END) {
throw this.error(new TomlError("Key ended without value"));
} else if (isAlphaNumHyphen(this.char)) {
this.consume();
} else if (this.state.buf.length === 0) {
throw this.error(new TomlError("Empty bare keys are not allowed"));
} else {
return this.returnNow();
}
} while (this.nextChar());
}
/* STRINGS, single quoted (literal) */
parseSingleString() {
if (this.char === CHAR_APOS) {
return this.next(this.parseLiteralMultiStringMaybe);
} else {
return this.goto(this.parseLiteralString);
}
}
parseLiteralString() {
do {
if (this.char === CHAR_APOS) {
return this.return();
} else if (this.atEndOfLine()) {
throw this.error(new TomlError("Unterminated string"));
} else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
throw this.errorControlCharIn("strings");
} else {
this.consume();
}
} while (this.nextChar());
}
parseLiteralMultiStringMaybe() {
if (this.char === CHAR_APOS) {
return this.next(this.parseLiteralMultiString);
} else {
return this.returnNow();
}
}
parseLiteralMultiString() {
if (this.char === CTRL_M) {
return null;
} else if (this.char === CTRL_J) {
return this.next(this.parseLiteralMultiStringContent);
} else {
return this.goto(this.parseLiteralMultiStringContent);
}
}
parseLiteralMultiStringContent() {
do {
if (this.char === CHAR_APOS) {
return this.next(this.parseLiteralMultiEnd);
} else if (this.char === Parser2.END) {
throw this.error(new TomlError("Unterminated multi-line string"));
} else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
throw this.errorControlCharIn("strings");
} else {
this.consume();
}
} while (this.nextChar());
}
parseLiteralMultiEnd() {
if (this.char === CHAR_APOS) {
return this.next(this.parseLiteralMultiEnd2);
} else {
this.state.buf += "'";
return this.goto(this.parseLiteralMultiStringContent);
}
}
parseLiteralMultiEnd2() {
if (this.char === CHAR_APOS) {
return this.next(this.parseLiteralMultiEnd3);
} else {
this.state.buf += "''";
return this.goto(this.parseLiteralMultiStringContent);
}
}
parseLiteralMultiEnd3() {
if (this.char === CHAR_APOS) {
this.state.buf += "'";
return this.next(this.parseLiteralMultiEnd4);
} else {
return this.returnNow();
}
}
parseLiteralMultiEnd4() {
if (this.char === CHAR_APOS) {
this.state.buf += "'";
return this.return();
} else {
return this.returnNow();
}
}
/* STRINGS double quoted */
parseDoubleString() {
if (this.char === CHAR_QUOT) {
return this.next(this.parseMultiStringMaybe);
} else {
return this.goto(this.parseBasicString);
}
}
parseBasicString() {
do {
if (this.char === CHAR_BSOL) {
return this.call(this.parseEscape, this.recordEscapeReplacement);
} else if (this.char === CHAR_QUOT) {
return this.return();
} else if (this.atEndOfLine()) {
throw this.error(new TomlError("Unterminated string"));
} else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
throw this.errorControlCharIn("strings");
} else {
this.consume();
}
} while (this.nextChar());
}
recordEscapeReplacement(replacement) {
this.state.buf += replacement;
return this.goto(this.parseBasicString);
}
parseMultiStringMaybe() {
if (this.char === CHAR_QUOT) {
return this.next(this.parseMultiString);
} else {
return this.returnNow();
}
}
parseMultiString() {
if (this.char === CTRL_M) {
return null;
} else if (this.char === CTRL_J) {
return this.next(this.parseMultiStringContent);
} else {
return this.goto(this.parseMultiStringContent);
}
}
parseMultiStringContent() {
do {
if (this.char === CHAR_BSOL) {
return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
} else if (this.char === CHAR_QUOT) {
return this.next(this.parseMultiEnd);
} else if (this.char === Parser2.END) {
throw this.error(new TomlError("Unterminated multi-line string"));
} else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
throw this.errorControlCharIn("strings");
} else {
this.consume();
}
} while (this.nextChar());
}
errorControlCharIn(type) {
let displayCode = "\\u00";
if (this.char < 16) {
displayCode += "0";
}
displayCode += this.char.toString(16);
return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in ${type}, use ${displayCode} instead`));
}
recordMultiEscapeReplacement(replacement) {
this.state.buf += replacement;
return this.goto(this.parseMultiStringContent);
}
parseMultiEnd() {
if (this.char === CHAR_QUOT) {
return this.next(this.parseMultiEnd2);
} else {
this.state.buf += '"';
return this.goto(this.parseMultiStringContent);
}
}
parseMultiEnd2() {
if (this.char === CHAR_QUOT) {
return this.next(this.parseMultiEnd3);
} else {
this.state.buf += '""';
return this.goto(this.parseMultiStringContent);
}
}
parseMultiEnd3() {
if (this.char === CHAR_QUOT) {
this.state.buf += '"';
return this.next(this.parseMultiEnd4);
} else {
return this.returnNow();
}
}
parseMultiEnd4() {
if (this.char === CHAR_QUOT) {
this.state.buf += '"';
return this.return();
} else {
return this.returnNow();
}
}
parseMultiEscape() {
if (this.char === CTRL_M || this.char === CTRL_J) {
return this.next(this.parseMultiTrim);
} else if (this.char === CHAR_SP || this.char === CTRL_I) {
return this.next(this.parsePreMultiTrim);
} else {
return this.goto(this.parseEscape);
}
}
parsePreMultiTrim() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else if (this.char === CTRL_M || this.char === CTRL_J) {
return this.next(this.parseMultiTrim);
} else {
throw this.error(new TomlError("Can't escape whitespace"));
}
}
parseMultiTrim() {
if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
return null;
} else {
return this.returnNow();
}
}
parseEscape() {
if (this.char in escapes) {
return this.return(escapes[this.char]);
} else if (this.char === CHAR_u) {
return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
} else if (this.char === CHAR_U) {
return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
} else {
throw this.error(new TomlError("Unknown escape character: " + this.char));
}
}
parseUnicodeReturn(char) {
try {
const codePoint = parseInt(char, 16);
if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));
}
return this.returnNow(String.fromCodePoint(codePoint));
} catch (err) {
throw this.error(TomlError.wrap(err));
}
}
parseSmallUnicode() {
if (!isHexit(this.char)) {
throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
} else {
this.consume();
if (this.state.buf.length >= 4) return this.return();
}
}
parseLargeUnicode() {
if (!isHexit(this.char)) {
throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
} else {
this.consume();
if (this.state.buf.length >= 8) return this.return();
}
}
/* NUMBERS */
parseNumberSign() {
this.consume();
return this.next(this.parseMaybeSignedInfOrNan);
}
parseMaybeSignedInfOrNan() {
if (this.char === CHAR_i) {
return this.next(this.parseInf);
} else if (this.char === CHAR_n) {
return this.next(this.parseNan);
} else {
return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
}
}
parseNumberIntegerStart() {
if (this.char === CHAR_0) {
this.consume();
return this.next(this.parseNumberIntegerExponentOrDecimal);
} else {
return this.goto(this.parseNumberInteger);
}
}
parseNumberIntegerExponentOrDecimal() {
if (this.char === CHAR_PERIOD) {
this.consume();
return this.call(this.parseNoUnder, this.parseNumberFloat);
} else if (this.char === CHAR_E || this.char === CHAR_e) {
this.consume();
return this.next(this.parseNumberExponentSign);
} else {
return this.returnNow(Integer(this.state.buf));
}
}
parseNumberInteger() {
if (isDigit(this.char)) {
this.consume();
} else if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnder);
} else if (this.char === CHAR_E || this.char === CHAR_e) {
this.consume();
return this.next(this.parseNumberExponentSign);
} else if (this.char === CHAR_PERIOD) {
this.consume();
return this.call(this.parseNoUnder, this.parseNumberFloat);
} else {
const result = Integer(this.state.buf);
if (result.isNaN()) {
throw this.error(new TomlError("Invalid number"));
} else {
return this.returnNow(result);
}
}
}
parseNoUnder() {
if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
throw this.error(new TomlError("Unexpected character, expected digit"));
} else if (this.atEndOfWord()) {
throw this.error(new TomlError("Incomplete number"));
}
return this.returnNow();
}
parseNoUnderHexOctBinLiteral() {
if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {
throw this.error(new TomlError("Unexpected character, expected digit"));
} else if (this.atEndOfWord()) {
throw this.error(new TomlError("Incomplete number"));
}
return this.returnNow();
}
parseNumberFloat() {
if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnder, this.parseNumberFloat);
} else if (isDigit(this.char)) {
this.consume();
} else if (this.char === CHAR_E || this.char === CHAR_e) {
this.consume();
return this.next(this.parseNumberExponentSign);
} else {
return this.returnNow(Float(this.state.buf));
}
}
parseNumberExponentSign() {
if (isDigit(this.char)) {
return this.goto(this.parseNumberExponent);
} else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
this.consume();
this.call(this.parseNoUnder, this.parseNumberExponent);
} else {
throw this.error(new TomlError("Unexpected character, expected -, + or digit"));
}
}
parseNumberExponent() {
if (isDigit(this.char)) {
this.consume();
} else if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnder);
} else {
return this.returnNow(Float(this.state.buf));
}
}
/* NUMBERS or DATETIMES */
parseNumberOrDateTime() {
if (this.char === CHAR_0) {
this.consume();
return this.next(this.parseNumberBaseOrDateTime);
} else {
return this.goto(this.parseNumberOrDateTimeOnly);
}
}
parseNumberOrDateTimeOnly() {
if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnder, this.parseNumberInteger);
} else if (isDigit(this.char)) {
this.consume();
if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
} else if (this.char === CHAR_E || this.char === CHAR_e) {
this.consume();
return this.next(this.parseNumberExponentSign);
} else if (this.char === CHAR_PERIOD) {
this.consume();
return this.call(this.parseNoUnder, this.parseNumberFloat);
} else if (this.char === CHAR_HYPHEN) {
return this.goto(this.parseDateTime);
} else if (this.char === CHAR_COLON) {
return this.goto(this.parseOnlyTimeHour);
} else {
return this.returnNow(Integer(this.state.buf));
}
}
parseDateTimeOnly() {
if (this.state.buf.length < 4) {
if (isDigit(this.char)) {
return this.consume();
} else if (this.char === CHAR_COLON) {
return this.goto(this.parseOnlyTimeHour);
} else {
throw this.error(new TomlError("Expected digit while parsing year part of a date"));
}
} else {
if (this.char === CHAR_HYPHEN) {
return this.goto(this.parseDateTime);
} else {
throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"));
}
}
}
parseNumberBaseOrDateTime() {
if (this.char === CHAR_b) {
this.consume();
return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin);
} else if (this.char === CHAR_o) {
this.consume();
return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct);
} else if (this.char === CHAR_x) {
this.consume();
return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex);
} else if (this.char === CHAR_PERIOD) {
return this.goto(this.parseNumberInteger);
} else if (isDigit(this.char)) {
return this.goto(this.parseDateTimeOnly);
} else {
return this.returnNow(Integer(this.state.buf));
}
}
parseIntegerHex() {
if (isHexit(this.char)) {
this.consume();
} else if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnderHexOctBinLiteral);
} else {
const result = Integer(this.state.buf);
if (result.isNaN()) {
throw this.error(new TomlError("Invalid number"));
} else {
return this.returnNow(result);
}
}
}
parseIntegerOct() {
if (isOctit(this.char)) {
this.consume();
} else if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnderHexOctBinLiteral);
} else {
const result = Integer(this.state.buf);
if (result.isNaN()) {
throw this.error(new TomlError("Invalid number"));
} else {
return this.returnNow(result);
}
}
}
parseIntegerBin() {
if (isBit(this.char)) {
this.consume();
} else if (this.char === CHAR_LOWBAR) {
return this.call(this.parseNoUnderHexOctBinLiteral);
} else {
const result = Integer(this.state.buf);
if (result.isNaN()) {
throw this.error(new TomlError("Invalid number"));
} else {
return this.returnNow(result);
}
}
}
/* DATETIME */
parseDateTime() {
if (this.state.buf.length < 4) {
throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));
}
this.state.result = this.state.buf;
this.state.buf = "";
return this.next(this.parseDateMonth);
}
parseDateMonth() {
if (this.char === CHAR_HYPHEN) {
if (this.state.buf.length < 2) {
throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));
}
this.state.result += "-" + this.state.buf;
this.state.buf = "";
return this.next(this.parseDateDay);
} else if (isDigit(this.char)) {
this.consume();
} else {
throw this.error(new TomlError("Incomplete datetime"));
}
}
parseDateDay() {
if (this.char === CHAR_T || this.char === CHAR_SP) {
if (this.state.buf.length < 2) {
throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));
}
this.state.result += "-" + this.state.buf;
this.state.buf = "";
return this.next(this.parseStartTimeHour);
} else if (this.atEndOfWord()) {
return this.returnNow(createDate(this.state.result + "-" + this.state.buf));
} else if (isDigit(this.char)) {
this.consume();
} else {
throw this.error(new TomlError("Incomplete datetime"));
}
}
parseStartTimeHour() {
if (this.atEndOfWord()) {
return this.returnNow(createDate(this.state.result));
} else {
return this.goto(this.parseTimeHour);
}
}
parseTimeHour() {
if (this.char === CHAR_COLON) {
if (this.state.buf.length < 2) {
throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
}
this.state.result += "T" + this.state.buf;
this.state.buf = "";
return this.next(this.parseTimeMin);
} else if (isDigit(this.char)) {
this.consume();
} else {
throw this.error(new TomlError("Incomplete datetime"));
}
}
parseTimeMin() {
if (this.state.buf.length < 2 && isDigit(this.char)) {
this.consume();
} else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
this.state.result += ":" + this.state.buf;
this.state.buf = "";
return this.next(this.parseTimeSec);
} else {
throw this.error(new TomlError("Incomplete datetime"));
}
}
parseTimeSec() {
if (isDigit(this.char)) {
this.consume();
if (this.state.buf.length === 2) {
this.state.result += ":" + this.state.buf;
this.state.buf = "";
return this.next(this.parseTimeZoneOrFraction);
}
} else {
throw this.error(new TomlError("Incomplete datetime"));
}
}
parseOnlyTimeHour() {
if (this.char === CHAR_COLON) {
if (this.state.buf.length < 2) {
throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
}
this.state.result = this.state.buf;
this.state.buf = "";
return this.next(this.parseOnlyTimeMin);
} else {
throw this.error(new TomlError("Incomplete time"));
}
}
parseOnlyTimeMin() {
if (this.state.buf.length < 2 && isDigit(this.char)) {
this.consume();
} else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
this.state.result += ":" + this.state.buf;
this.state.buf = "";
return this.next(this.parseOnlyTimeSec);
} else {
throw this.error(new TomlError("Incomplete time"));
}
}
parseOnlyTimeSec() {
if (isDigit(this.char)) {
this.consume();
if (this.state.buf.length === 2) {
return this.next(this.parseOnlyTimeFractionMaybe);
}
} else {
throw this.error(new TomlError("Incomplete time"));
}
}
parseOnlyTimeFractionMaybe() {
this.state.result += ":" + this.state.buf;
if (this.char === CHAR_PERIOD) {
this.state.buf = "";
this.next(this.parseOnlyTimeFraction);
} else {
return this.return(createTime(this.state.result));
}
}
parseOnlyTimeFraction() {
if (isDigit(this.char)) {
this.consume();
} else if (this.atEndOfWord()) {
if (this.state.buf.length === 0) throw this.error(new TomlError("Expected digit in milliseconds"));
return this.returnNow(createTime(this.state.result + "." + this.state.buf));
} else {
throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
}
}
parseTimeZoneOrFraction() {
if (this.char === CHAR_PERIOD) {
this.consume();
this.next(this.parseDateTimeFraction);
} else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
this.consume();
this.next(this.parseTimeZoneHour);
} else if (this.char === CHAR_Z) {
this.consume();
return this.return(createDateTime(this.state.result + this.state.buf));
} else if (this.atEndOfWord()) {
return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
} else {
throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
}
}
parseDateTimeFraction() {
if (isDigit(this.char)) {
this.consume();
} else if (this.state.buf.length === 1) {
throw this.error(new TomlError("Expected digit in milliseconds"));
} else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
this.consume();
this.next(this.parseTimeZoneHour);
} else if (this.char === CHAR_Z) {
this.consume();
return this.return(createDateTime(this.state.result + this.state.buf));
} else if (this.atEndOfWord()) {
return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
} else {
throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
}
}
parseTimeZoneHour() {
if (isDigit(this.char)) {
this.consume();
if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
} else {
throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
}
}
parseTimeZoneSep() {
if (this.char === CHAR_COLON) {
this.consume();
this.next(this.parseTimeZoneMin);
} else {
throw this.error(new TomlError("Unexpected character in datetime, expected colon"));
}
}
parseTimeZoneMin() {
if (isDigit(this.char)) {
this.consume();
if (/\d\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf));
} else {
throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
}
}
/* BOOLEAN */
parseBoolean() {
if (this.char === CHAR_t) {
this.consume();
return this.next(this.parseTrue_r);
} else if (this.char === CHAR_f) {
this.consume();
return this.next(this.parseFalse_a);
}
}
parseTrue_r() {
if (this.char === CHAR_r) {
this.consume();
return this.next(this.parseTrue_u);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
parseTrue_u() {
if (this.char === CHAR_u) {
this.consume();
return this.next(this.parseTrue_e);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
parseTrue_e() {
if (this.char === CHAR_e) {
return this.return(true);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
parseFalse_a() {
if (this.char === CHAR_a) {
this.consume();
return this.next(this.parseFalse_l);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
parseFalse_l() {
if (this.char === CHAR_l) {
this.consume();
return this.next(this.parseFalse_s);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
parseFalse_s() {
if (this.char === CHAR_s) {
this.consume();
return this.next(this.parseFalse_e);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
parseFalse_e() {
if (this.char === CHAR_e) {
return this.return(false);
} else {
throw this.error(new TomlError("Invalid boolean, expected true or false"));
}
}
/* INLINE LISTS */
parseInlineList() {
if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
return null;
} else if (this.char === Parser2.END) {
throw this.error(new TomlError("Unterminated inline array"));
} else if (this.char === CHAR_NUM) {
return this.call(this.parseComment);
} else if (this.char === CHAR_RSQB) {
return this.return(this.state.resultArr || InlineList());
} else {
return this.callNow(this.parseValue, this.recordInlineListValue);
}
}
recordInlineListValue(value) {
if (!this.state.resultArr) {
this.state.resultArr = InlineList(tomlType(value));
}
if (isFloat(value) || isInteger(value)) {
this.state.resultArr.push(value.valueOf());
} else {
this.state.resultArr.push(value);
}
return this.goto(this.parseInlineListNext);
}
parseInlineListNext() {
if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
return null;
} else if (this.char === CHAR_NUM) {
return this.call(this.parseComment);
} else if (this.char === CHAR_COMMA) {
return this.next(this.parseInlineList);
} else if (this.char === CHAR_RSQB) {
return this.goto(this.parseInlineList);
} else {
throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
}
}
/* INLINE TABLE */
parseInlineTable() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else if (this.char === Parser2.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
throw this.error(new TomlError("Unterminated inline array"));
} else if (this.char === CHAR_RCUB) {
return this.return(this.state.resultTable || InlineTable());
} else {
if (!this.state.resultTable) this.state.resultTable = InlineTable();
return this.callNow(this.parseAssign, this.recordInlineTableValue);
}
}
recordInlineTableValue(kv) {
let target = this.state.resultTable;
let finalKey = kv.key.pop();
for (let kw of kv.key) {
if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
throw this.error(new TomlError("Can't redefine existing key"));
}
target = target[kw] = target[kw] || Table();
}
if (hasKey(target, finalKey)) {
throw this.error(new TomlError("Can't redefine existing key"));
}
if (isInteger(kv.value) || isFloat(kv.value)) {
target[finalKey] = kv.value.valueOf();
} else {
target[finalKey] = kv.value;
}
return this.goto(this.parseInlineTableNext);
}
parseInlineTableNext() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else if (this.char === Parser2.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
throw this.error(new TomlError("Unterminated inline array"));
} else if (this.char === CHAR_COMMA) {
return this.next(this.parseInlineTablePostComma);
} else if (this.char === CHAR_RCUB) {
return this.goto(this.parseInlineTable);
} else {
throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
}
}
parseInlineTablePostComma() {
if (this.char === CHAR_SP || this.char === CTRL_I) {
return null;
} else if (this.char === Parser2.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
throw this.error(new TomlError("Unterminated inline array"));
} else if (this.char === CHAR_COMMA) {
throw this.error(new TomlError("Empty elements in inline tables are not permitted"));
} else if (this.char === CHAR_RCUB) {
throw this.error(new TomlError("Trailing commas in inline tables are not permitted"));
} else {
return this.goto(this.parseInlineTable);
}
}
}
return TOMLParser;
}
__name(makeParserClass, "makeParserClass");
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-pretty-error.js
var require_parse_pretty_error = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-pretty-error.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = prettyError;
function prettyError(err, buf) {
if (err.pos == null || err.line == null) return err;
let msg = err.message;
msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:
`;
if (buf && buf.split) {
const lines = buf.split(/\n/);
const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
let linePadding = " ";
while (linePadding.length < lineNumWidth) linePadding += " ";
for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
let lineNum = String(ii + 1);
if (lineNum.length < lineNumWidth) lineNum = " " + lineNum;
if (err.line === ii) {
msg += lineNum + "> " + lines[ii] + "\n";
msg += linePadding + " ";
for (let hh = 0; hh < err.col; ++hh) {
msg += " ";
}
msg += "^\n";
} else {
msg += lineNum + ": " + lines[ii] + "\n";
}
}
}
err.message = msg + "\n";
return err;
}
__name(prettyError, "prettyError");
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-string.js
var require_parse_string = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-string.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = parseString;
var TOMLParser = require_toml_parser();
var prettyError = require_parse_pretty_error();
function parseString(str) {
if (global.Buffer && global.Buffer.isBuffer(str)) {
str = str.toString("utf8");
}
const parser2 = new TOMLParser();
try {
parser2.parse(str);
return parser2.finish();
} catch (err) {
throw prettyError(err, str);
}
}
__name(parseString, "parseString");
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-async.js
var require_parse_async = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-async.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = parseAsync;
var TOMLParser = require_toml_parser();
var prettyError = require_parse_pretty_error();
function parseAsync(str, opts) {
if (!opts) opts = {};
const index = 0;
const blocksize = opts.blocksize || 40960;
const parser2 = new TOMLParser();
return new Promise((resolve25, reject) => {
setImmediate(parseAsyncNext, index, blocksize, resolve25, reject);
});
function parseAsyncNext(index2, blocksize2, resolve25, reject) {
if (index2 >= str.length) {
try {
return resolve25(parser2.finish());
} catch (err) {
return reject(prettyError(err, str));
}
}
try {
parser2.parse(str.slice(index2, index2 + blocksize2));
setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve25, reject);
} catch (err) {
reject(prettyError(err, str));
}
}
__name(parseAsyncNext, "parseAsyncNext");
}
__name(parseAsync, "parseAsync");
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-stream.js
var require_parse_stream = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse-stream.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = parseStream;
var stream2 = require("stream");
var TOMLParser = require_toml_parser();
function parseStream(stm) {
if (stm) {
return parseReadable(stm);
} else {
return parseTransform2(stm);
}
}
__name(parseStream, "parseStream");
function parseReadable(stm) {
const parser2 = new TOMLParser();
stm.setEncoding("utf8");
return new Promise((resolve25, reject) => {
let readable;
let ended = false;
let errored = false;
function finish() {
ended = true;
if (readable) return;
try {
resolve25(parser2.finish());
} catch (err) {
reject(err);
}
}
__name(finish, "finish");
function error2(err) {
errored = true;
reject(err);
}
__name(error2, "error");
stm.once("end", finish);
stm.once("error", error2);
readNext();
function readNext() {
readable = true;
let data;
while ((data = stm.read()) !== null) {
try {
parser2.parse(data);
} catch (err) {
return error2(err);
}
}
readable = false;
if (ended) return finish();
if (errored) return;
stm.once("readable", readNext);
}
__name(readNext, "readNext");
});
}
__name(parseReadable, "parseReadable");
function parseTransform2() {
const parser2 = new TOMLParser();
return new stream2.Transform({
objectMode: true,
transform(chunk, encoding, cb2) {
try {
parser2.parse(chunk.toString(encoding));
} catch (err) {
this.emit("error", err);
}
cb2();
},
flush(cb2) {
try {
this.push(parser2.finish());
} catch (err) {
this.emit("error", err);
}
cb2();
}
});
}
__name(parseTransform2, "parseTransform");
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse.js
var require_parse2 = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/parse.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = require_parse_string();
module3.exports.async = require_parse_async();
module3.exports.stream = require_parse_stream();
module3.exports.prettyError = require_parse_pretty_error();
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/stringify.js
var require_stringify = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/stringify.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = stringify;
module3.exports.value = stringifyInline;
function stringify(obj) {
if (obj === null) throw typeError("null");
if (obj === void 0) throw typeError("undefined");
if (typeof obj !== "object") throw typeError(typeof obj);
if (typeof obj.toJSON === "function") obj = obj.toJSON();
if (obj == null) return null;
const type = tomlType2(obj);
if (type !== "table") throw typeError(type);
return stringifyObject("", "", obj);
}
__name(stringify, "stringify");
function typeError(type) {
return new Error("Can only stringify objects, not " + type);
}
__name(typeError, "typeError");
function getInlineKeys(obj) {
return Object.keys(obj).filter((key) => isInline(obj[key]));
}
__name(getInlineKeys, "getInlineKeys");
function getComplexKeys(obj) {
return Object.keys(obj).filter((key) => !isInline(obj[key]));
}
__name(getComplexKeys, "getComplexKeys");
function toJSON(obj) {
let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, "__proto__") ? { ["__proto__"]: void 0 } : {};
for (let prop of Object.keys(obj)) {
if (obj[prop] && typeof obj[prop].toJSON === "function" && !("toISOString" in obj[prop])) {
nobj[prop] = obj[prop].toJSON();
} else {
nobj[prop] = obj[prop];
}
}
return nobj;
}
__name(toJSON, "toJSON");
function stringifyObject(prefix, indent, obj) {
obj = toJSON(obj);
let inlineKeys;
let complexKeys;
inlineKeys = getInlineKeys(obj);
complexKeys = getComplexKeys(obj);
const result = [];
const inlineIndent = indent || "";
inlineKeys.forEach((key) => {
var type = tomlType2(obj[key]);
if (type !== "undefined" && type !== "null") {
result.push(inlineIndent + stringifyKey(key) + " = " + stringifyAnyInline(obj[key], true));
}
});
if (result.length > 0) result.push("");
const complexIndent = prefix && inlineKeys.length > 0 ? indent + " " : "";
complexKeys.forEach((key) => {
result.push(stringifyComplex(prefix, complexIndent, key, obj[key]));
});
return result.join("\n");
}
__name(stringifyObject, "stringifyObject");
function isInline(value) {
switch (tomlType2(value)) {
case "undefined":
case "null":
case "integer":
case "nan":
case "float":
case "boolean":
case "string":
case "datetime":
return true;
case "array":
return value.length === 0 || tomlType2(value[0]) !== "table";
case "table":
return Object.keys(value).length === 0;
/* istanbul ignore next */
default:
return false;
}
}
__name(isInline, "isInline");
function tomlType2(value) {
if (value === void 0) {
return "undefined";
} else if (value === null) {
return "null";
} else if (typeof value === "bigint" || Number.isInteger(value) && !Object.is(value, -0)) {
return "integer";
} else if (typeof value === "number") {
return "float";
} else if (typeof value === "boolean") {
return "boolean";
} else if (typeof value === "string") {
return "string";
} else if ("toISOString" in value) {
return isNaN(value) ? "undefined" : "datetime";
} else if (Array.isArray(value)) {
return "array";
} else {
return "table";
}
}
__name(tomlType2, "tomlType");
function stringifyKey(key) {
const keyStr = String(key);
if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {
return keyStr;
} else {
return stringifyBasicString(keyStr);
}
}
__name(stringifyKey, "stringifyKey");
function stringifyBasicString(str) {
return '"' + escapeString(str).replace(/"/g, '\\"') + '"';
}
__name(stringifyBasicString, "stringifyBasicString");
function stringifyLiteralString(str) {
return "'" + str + "'";
}
__name(stringifyLiteralString, "stringifyLiteralString");
function numpad(num, str) {
while (str.length < num) str = "0" + str;
return str;
}
__name(numpad, "numpad");
function escapeString(str) {
return str.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c6) => "\\u" + numpad(4, c6.codePointAt(0).toString(16)));
}
__name(escapeString, "escapeString");
function stringifyMultilineString(str) {
let escaped = str.split(/\n/).map((str2) => {
return escapeString(str2).replace(/"(?="")/g, '\\"');
}).join("\n");
if (escaped.slice(-1) === '"') escaped += "\\\n";
return '"""\n' + escaped + '"""';
}
__name(stringifyMultilineString, "stringifyMultilineString");
function stringifyAnyInline(value, multilineOk) {
let type = tomlType2(value);
if (type === "string") {
if (multilineOk && /\n/.test(value)) {
type = "string-multiline";
} else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) {
type = "string-literal";
}
}
return stringifyInline(value, type);
}
__name(stringifyAnyInline, "stringifyAnyInline");
function stringifyInline(value, type) {
if (!type) type = tomlType2(value);
switch (type) {
case "string-multiline":
return stringifyMultilineString(value);
case "string":
return stringifyBasicString(value);
case "string-literal":
return stringifyLiteralString(value);
case "integer":
return stringifyInteger(value);
case "float":
return stringifyFloat(value);
case "boolean":
return stringifyBoolean(value);
case "datetime":
return stringifyDatetime(value);
case "array":
return stringifyInlineArray(value.filter((_4) => tomlType2(_4) !== "null" && tomlType2(_4) !== "undefined" && tomlType2(_4) !== "nan"));
case "table":
return stringifyInlineTable(value);
/* istanbul ignore next */
default:
throw typeError(type);
}
}
__name(stringifyInline, "stringifyInline");
function stringifyInteger(value) {
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, "_");
}
__name(stringifyInteger, "stringifyInteger");
function stringifyFloat(value) {
if (value === Infinity) {
return "inf";
} else if (value === -Infinity) {
return "-inf";
} else if (Object.is(value, NaN)) {
return "nan";
} else if (Object.is(value, -0)) {
return "-0.0";
}
const [int, dec] = String(value).split(".");
return stringifyInteger(int) + "." + dec;
}
__name(stringifyFloat, "stringifyFloat");
function stringifyBoolean(value) {
return String(value);
}
__name(stringifyBoolean, "stringifyBoolean");
function stringifyDatetime(value) {
return value.toISOString();
}
__name(stringifyDatetime, "stringifyDatetime");
function stringifyInlineArray(values) {
values = toJSON(values);
let result = "[";
const stringified = values.map((_4) => stringifyInline(_4));
if (stringified.join(", ").length > 60 || /\n/.test(stringified)) {
result += "\n " + stringified.join(",\n ") + "\n";
} else {
result += " " + stringified.join(", ") + (stringified.length > 0 ? " " : "");
}
return result + "]";
}
__name(stringifyInlineArray, "stringifyInlineArray");
function stringifyInlineTable(value) {
value = toJSON(value);
const result = [];
Object.keys(value).forEach((key) => {
result.push(stringifyKey(key) + " = " + stringifyAnyInline(value[key], false));
});
return "{ " + result.join(", ") + (result.length > 0 ? " " : "") + "}";
}
__name(stringifyInlineTable, "stringifyInlineTable");
function stringifyComplex(prefix, indent, key, value) {
const valueType = tomlType2(value);
if (valueType === "array") {
return stringifyArrayOfTables(prefix, indent, key, value);
} else if (valueType === "table") {
return stringifyComplexTable(prefix, indent, key, value);
} else {
throw typeError(valueType);
}
}
__name(stringifyComplex, "stringifyComplex");
function stringifyArrayOfTables(prefix, indent, key, values) {
values = toJSON(values);
const firstValueType = tomlType2(values[0]);
if (firstValueType !== "table") throw typeError(firstValueType);
const fullKey = prefix + stringifyKey(key);
let result = "";
values.forEach((table) => {
if (result.length > 0) result += "\n";
result += indent + "[[" + fullKey + "]]\n";
result += stringifyObject(fullKey + ".", indent, table);
});
return result;
}
__name(stringifyArrayOfTables, "stringifyArrayOfTables");
function stringifyComplexTable(prefix, indent, key, value) {
const fullKey = prefix + stringifyKey(key);
let result = "";
if (getInlineKeys(value).length > 0) {
result += indent + "[" + fullKey + "]\n";
}
return result + stringifyObject(fullKey + ".", indent, value);
}
__name(stringifyComplexTable, "stringifyComplexTable");
}
});
// ../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/toml.js
var require_toml = __commonJS({
"../../node_modules/.pnpm/@iarna+toml@3.0.0/node_modules/@iarna/toml/toml.js"(exports2) {
"use strict";
init_import_meta_url();
exports2.parse = require_parse2();
exports2.stringify = require_stringify();
}
});
// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/scanner.js
function createScanner(text, ignoreTrivia = false) {
const len = text.length;
let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
function scanHexDigits(count, exact) {
let digits = 0;
let value2 = 0;
while (digits < count || !exact) {
let ch2 = text.charCodeAt(pos);
if (ch2 >= 48 && ch2 <= 57) {
value2 = value2 * 16 + ch2 - 48;
} else if (ch2 >= 65 && ch2 <= 70) {
value2 = value2 * 16 + ch2 - 65 + 10;
} else if (ch2 >= 97 && ch2 <= 102) {
value2 = value2 * 16 + ch2 - 97 + 10;
} else {
break;
}
pos++;
digits++;
}
if (digits < count) {
value2 = -1;
}
return value2;
}
__name(scanHexDigits, "scanHexDigits");
function setPosition(newPosition) {
pos = newPosition;
value = "";
tokenOffset = 0;
token = 16;
scanError = 0;
}
__name(setPosition, "setPosition");
function scanNumber() {
let start = pos;
if (text.charCodeAt(pos) === 48) {
pos++;
} else {
pos++;
while (pos < text.length && isDigit2(text.charCodeAt(pos))) {
pos++;
}
}
if (pos < text.length && text.charCodeAt(pos) === 46) {
pos++;
if (pos < text.length && isDigit2(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit2(text.charCodeAt(pos))) {
pos++;
}
} else {
scanError = 3;
return text.substring(start, pos);
}
}
let end = pos;
if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
pos++;
if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
pos++;
}
if (pos < text.length && isDigit2(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit2(text.charCodeAt(pos))) {
pos++;
}
end = pos;
} else {
scanError = 3;
}
}
return text.substring(start, end);
}
__name(scanNumber, "scanNumber");
function scanString() {
let result = "", start = pos;
while (true) {
if (pos >= len) {
result += text.substring(start, pos);
scanError = 2;
break;
}
const ch2 = text.charCodeAt(pos);
if (ch2 === 34) {
result += text.substring(start, pos);
pos++;
break;
}
if (ch2 === 92) {
result += text.substring(start, pos);
pos++;
if (pos >= len) {
scanError = 2;
break;
}
const ch22 = text.charCodeAt(pos++);
switch (ch22) {
case 34:
result += '"';
break;
case 92:
result += "\\";
break;
case 47:
result += "/";
break;
case 98:
result += "\b";
break;
case 102:
result += "\f";
break;
case 110:
result += "\n";
break;
case 114:
result += "\r";
break;
case 116:
result += " ";
break;
case 117:
const ch3 = scanHexDigits(4, true);
if (ch3 >= 0) {
result += String.fromCharCode(ch3);
} else {
scanError = 4;
}
break;
default:
scanError = 5;
}
start = pos;
continue;
}
if (ch2 >= 0 && ch2 <= 31) {
if (isLineBreak(ch2)) {
result += text.substring(start, pos);
scanError = 2;
break;
} else {
scanError = 6;
}
}
pos++;
}
return result;
}
__name(scanString, "scanString");
function scanNext() {
value = "";
scanError = 0;
tokenOffset = pos;
lineStartOffset = lineNumber;
prevTokenLineStartOffset = tokenLineStartOffset;
if (pos >= len) {
tokenOffset = len;
return token = 17;
}
let code = text.charCodeAt(pos);
if (isWhiteSpace(code)) {
do {
pos++;
value += String.fromCharCode(code);
code = text.charCodeAt(pos);
} while (isWhiteSpace(code));
return token = 15;
}
if (isLineBreak(code)) {
pos++;
value += String.fromCharCode(code);
if (code === 13 && text.charCodeAt(pos) === 10) {
pos++;
value += "\n";
}
lineNumber++;
tokenLineStartOffset = pos;
return token = 14;
}
switch (code) {
// tokens: []{}:,
case 123:
pos++;
return token = 1;
case 125:
pos++;
return token = 2;
case 91:
pos++;
return token = 3;
case 93:
pos++;
return token = 4;
case 58:
pos++;
return token = 6;
case 44:
pos++;
return token = 5;
// strings
case 34:
pos++;
value = scanString();
return token = 10;
// comments
case 47:
const start = pos - 1;
if (text.charCodeAt(pos + 1) === 47) {
pos += 2;
while (pos < len) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
value = text.substring(start, pos);
return token = 12;
}
if (text.charCodeAt(pos + 1) === 42) {
pos += 2;
const safeLength = len - 1;
let commentClosed = false;
while (pos < safeLength) {
const ch2 = text.charCodeAt(pos);
if (ch2 === 42 && text.charCodeAt(pos + 1) === 47) {
pos += 2;
commentClosed = true;
break;
}
pos++;
if (isLineBreak(ch2)) {
if (ch2 === 13 && text.charCodeAt(pos) === 10) {
pos++;
}
lineNumber++;
tokenLineStartOffset = pos;
}
}
if (!commentClosed) {
pos++;
scanError = 1;
}
value = text.substring(start, pos);
return token = 13;
}
value += String.fromCharCode(code);
pos++;
return token = 16;
// numbers
case 45:
value += String.fromCharCode(code);
pos++;
if (pos === len || !isDigit2(text.charCodeAt(pos))) {
return token = 16;
}
// found a minus, followed by a number so
// we fall through to proceed with scanning
// numbers
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
value += scanNumber();
return token = 11;
// literals and unknown symbols
default:
while (pos < len && isUnknownContentCharacter(code)) {
pos++;
code = text.charCodeAt(pos);
}
if (tokenOffset !== pos) {
value = text.substring(tokenOffset, pos);
switch (value) {
case "true":
return token = 8;
case "false":
return token = 9;
case "null":
return token = 7;
}
return token = 16;
}
value += String.fromCharCode(code);
pos++;
return token = 16;
}
}
__name(scanNext, "scanNext");
function isUnknownContentCharacter(code) {
if (isWhiteSpace(code) || isLineBreak(code)) {
return false;
}
switch (code) {
case 125:
case 93:
case 123:
case 91:
case 34:
case 58:
case 44:
case 47:
return false;
}
return true;
}
__name(isUnknownContentCharacter, "isUnknownContentCharacter");
function scanNextNonTrivia() {
let result;
do {
result = scanNext();
} while (result >= 12 && result <= 15);
return result;
}
__name(scanNextNonTrivia, "scanNextNonTrivia");
return {
setPosition,
getPosition: /* @__PURE__ */ __name(() => pos, "getPosition"),
scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
getToken: /* @__PURE__ */ __name(() => token, "getToken"),
getTokenValue: /* @__PURE__ */ __name(() => value, "getTokenValue"),
getTokenOffset: /* @__PURE__ */ __name(() => tokenOffset, "getTokenOffset"),
getTokenLength: /* @__PURE__ */ __name(() => pos - tokenOffset, "getTokenLength"),
getTokenStartLine: /* @__PURE__ */ __name(() => lineStartOffset, "getTokenStartLine"),
getTokenStartCharacter: /* @__PURE__ */ __name(() => tokenOffset - prevTokenLineStartOffset, "getTokenStartCharacter"),
getTokenError: /* @__PURE__ */ __name(() => scanError, "getTokenError")
};
}
function isWhiteSpace(ch2) {
return ch2 === 32 || ch2 === 9;
}
function isLineBreak(ch2) {
return ch2 === 10 || ch2 === 13;
}
function isDigit2(ch2) {
return ch2 >= 48 && ch2 <= 57;
}
var CharacterCodes;
var init_scanner = __esm({
"../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/scanner.js"() {
"use strict";
init_import_meta_url();
__name(createScanner, "createScanner");
__name(isWhiteSpace, "isWhiteSpace");
__name(isLineBreak, "isLineBreak");
__name(isDigit2, "isDigit");
(function(CharacterCodes2) {
CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
})(CharacterCodes || (CharacterCodes = {}));
}
});
// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/format.js
function format3(documentText, range, options) {
let initialIndentLevel;
let formatText;
let formatTextStart;
let rangeStart;
let rangeEnd;
if (range) {
rangeStart = range.offset;
rangeEnd = rangeStart + range.length;
formatTextStart = rangeStart;
while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
formatTextStart--;
}
let endOffset = rangeEnd;
while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
endOffset++;
}
formatText = documentText.substring(formatTextStart, endOffset);
initialIndentLevel = computeIndentLevel(formatText, options);
} else {
formatText = documentText;
initialIndentLevel = 0;
formatTextStart = 0;
rangeStart = 0;
rangeEnd = documentText.length;
}
const eol = getEOL(options, documentText);
let numberLineBreaks = 0;
let indentLevel = 0;
let indentValue;
if (options.insertSpaces) {
indentValue = repeat(" ", options.tabSize || 4);
} else {
indentValue = " ";
}
let scanner = createScanner(formatText, false);
let hasError = false;
function newLinesAndIndent() {
if (numberLineBreaks > 1) {
return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
} else {
return eol + repeat(indentValue, initialIndentLevel + indentLevel);
}
}
__name(newLinesAndIndent, "newLinesAndIndent");
function scanNext() {
let token = scanner.scan();
numberLineBreaks = 0;
while (token === 15 || token === 14) {
if (token === 14 && options.keepLines) {
numberLineBreaks += 1;
} else if (token === 14) {
numberLineBreaks = 1;
}
token = scanner.scan();
}
hasError = token === 16 || scanner.getTokenError() !== 0;
return token;
}
__name(scanNext, "scanNext");
const editOperations = [];
function addEdit(text, startOffset, endOffset) {
if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
}
}
__name(addEdit, "addEdit");
let firstToken = scanNext();
if (options.keepLines && numberLineBreaks > 0) {
addEdit(repeat(eol, numberLineBreaks), 0, 0);
}
if (firstToken !== 17) {
let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
let initialIndent = repeat(indentValue, initialIndentLevel);
addEdit(initialIndent, formatTextStart, firstTokenStart);
}
while (firstToken !== 17) {
let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
let secondToken = scanNext();
let replaceContent = "";
let needsLineBreak = false;
while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(" ", firstTokenEnd, commentTokenStart);
firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
needsLineBreak = secondToken === 12;
replaceContent = needsLineBreak ? newLinesAndIndent() : "";
secondToken = scanNext();
}
if (secondToken === 2) {
if (firstToken !== 1) {
indentLevel--;
}
;
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
replaceContent = newLinesAndIndent();
} else if (options.keepLines) {
replaceContent = " ";
}
} else if (secondToken === 4) {
if (firstToken !== 3) {
indentLevel--;
}
;
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
replaceContent = newLinesAndIndent();
} else if (options.keepLines) {
replaceContent = " ";
}
} else {
switch (firstToken) {
case 3:
case 1:
indentLevel++;
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
replaceContent = newLinesAndIndent();
} else {
replaceContent = " ";
}
break;
case 5:
if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
replaceContent = newLinesAndIndent();
} else {
replaceContent = " ";
}
break;
case 12:
replaceContent = newLinesAndIndent();
break;
case 13:
if (numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else if (!needsLineBreak) {
replaceContent = " ";
}
break;
case 6:
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else if (!needsLineBreak) {
replaceContent = " ";
}
break;
case 10:
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else if (secondToken === 6 && !needsLineBreak) {
replaceContent = "";
}
break;
case 7:
case 8:
case 9:
case 11:
case 2:
case 4:
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else {
if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
replaceContent = " ";
} else if (secondToken !== 5 && secondToken !== 17) {
hasError = true;
}
}
break;
case 16:
hasError = true;
break;
}
if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
replaceContent = newLinesAndIndent();
}
}
if (secondToken === 17) {
if (options.keepLines && numberLineBreaks > 0) {
replaceContent = newLinesAndIndent();
} else {
replaceContent = options.insertFinalNewline ? eol : "";
}
}
const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(replaceContent, firstTokenEnd, secondTokenStart);
firstToken = secondToken;
}
return editOperations;
}
function repeat(s5, count) {
let result = "";
for (let i5 = 0; i5 < count; i5++) {
result += s5;
}
return result;
}
function computeIndentLevel(content, options) {
let i5 = 0;
let nChars = 0;
const tabSize = options.tabSize || 4;
while (i5 < content.length) {
let ch2 = content.charAt(i5);
if (ch2 === " ") {
nChars++;
} else if (ch2 === " ") {
nChars += tabSize;
} else {
break;
}
i5++;
}
return Math.floor(nChars / tabSize);
}
function getEOL(options, text) {
for (let i5 = 0; i5 < text.length; i5++) {
const ch2 = text.charAt(i5);
if (ch2 === "\r") {
if (i5 + 1 < text.length && text.charAt(i5 + 1) === "\n") {
return "\r\n";
}
return "\r";
} else if (ch2 === "\n") {
return "\n";
}
}
return options && options.eol || "\n";
}
function isEOL(text, offset) {
return "\r\n".indexOf(text.charAt(offset)) !== -1;
}
var init_format = __esm({
"../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/format.js"() {
"use strict";
init_import_meta_url();
init_scanner();
__name(format3, "format");
__name(repeat, "repeat");
__name(computeIndentLevel, "computeIndentLevel");
__name(getEOL, "getEOL");
__name(isEOL, "isEOL");
}
});
// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/parser.js
function parse(text, errors = [], options = ParseOptions.DEFAULT) {
let currentProperty = null;
let currentParent = [];
const previousParents = [];
function onValue(value) {
if (Array.isArray(currentParent)) {
currentParent.push(value);
} else if (currentProperty !== null) {
currentParent[currentProperty] = value;
}
}
__name(onValue, "onValue");
const visitor = {
onObjectBegin: /* @__PURE__ */ __name(() => {
const object = {};
onValue(object);
previousParents.push(currentParent);
currentParent = object;
currentProperty = null;
}, "onObjectBegin"),
onObjectProperty: /* @__PURE__ */ __name((name2) => {
currentProperty = name2;
}, "onObjectProperty"),
onObjectEnd: /* @__PURE__ */ __name(() => {
currentParent = previousParents.pop();
}, "onObjectEnd"),
onArrayBegin: /* @__PURE__ */ __name(() => {
const array = [];
onValue(array);
previousParents.push(currentParent);
currentParent = array;
currentProperty = null;
}, "onArrayBegin"),
onArrayEnd: /* @__PURE__ */ __name(() => {
currentParent = previousParents.pop();
}, "onArrayEnd"),
onLiteralValue: onValue,
onError: /* @__PURE__ */ __name((error2, offset, length) => {
errors.push({ error: error2, offset, length });
}, "onError")
};
visit(text, visitor, options);
return currentParent[0];
}
function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
function ensurePropertyComplete(endOffset) {
if (currentParent.type === "property") {
currentParent.length = endOffset - currentParent.offset;
currentParent = currentParent.parent;
}
}
__name(ensurePropertyComplete, "ensurePropertyComplete");
function onValue(valueNode) {
currentParent.children.push(valueNode);
return valueNode;
}
__name(onValue, "onValue");
const visitor = {
onObjectBegin: /* @__PURE__ */ __name((offset) => {
currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
}, "onObjectBegin"),
onObjectProperty: /* @__PURE__ */ __name((name2, offset, length) => {
currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
currentParent.children.push({ type: "string", value: name2, offset, length, parent: currentParent });
}, "onObjectProperty"),
onObjectEnd: /* @__PURE__ */ __name((offset, length) => {
ensurePropertyComplete(offset + length);
currentParent.length = offset + length - currentParent.offset;
currentParent = currentParent.parent;
ensurePropertyComplete(offset + length);
}, "onObjectEnd"),
onArrayBegin: /* @__PURE__ */ __name((offset, length) => {
currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
}, "onArrayBegin"),
onArrayEnd: /* @__PURE__ */ __name((offset, length) => {
currentParent.length = offset + length - currentParent.offset;
currentParent = currentParent.parent;
ensurePropertyComplete(offset + length);
}, "onArrayEnd"),
onLiteralValue: /* @__PURE__ */ __name((value, offset, length) => {
onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
ensurePropertyComplete(offset + length);
}, "onLiteralValue"),
onSeparator: /* @__PURE__ */ __name((sep5, offset, length) => {
if (currentParent.type === "property") {
if (sep5 === ":") {
currentParent.colonOffset = offset;
} else if (sep5 === ",") {
ensurePropertyComplete(offset);
}
}
}, "onSeparator"),
onError: /* @__PURE__ */ __name((error2, offset, length) => {
errors.push({ error: error2, offset, length });
}, "onError")
};
visit(text, visitor, options);
const result = currentParent.children[0];
if (result) {
delete result.parent;
}
return result;
}
function findNodeAtLocation(root, path72) {
if (!root) {
return void 0;
}
let node2 = root;
for (let segment of path72) {
if (typeof segment === "string") {
if (node2.type !== "object" || !Array.isArray(node2.children)) {
return void 0;
}
let found = false;
for (const propertyNode of node2.children) {
if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
node2 = propertyNode.children[1];
found = true;
break;
}
}
if (!found) {
return void 0;
}
} else {
const index = segment;
if (node2.type !== "array" || index < 0 || !Array.isArray(node2.children) || index >= node2.children.length) {
return void 0;
}
node2 = node2.children[index];
}
}
return node2;
}
function visit(text, visitor, options = ParseOptions.DEFAULT) {
const _scanner = createScanner(text, false);
const _jsonPath = [];
function toNoArgVisit(visitFunction) {
return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
}
__name(toNoArgVisit, "toNoArgVisit");
function toNoArgVisitWithPath(visitFunction) {
return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
}
__name(toNoArgVisitWithPath, "toNoArgVisitWithPath");
function toOneArgVisit(visitFunction) {
return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
}
__name(toOneArgVisit, "toOneArgVisit");
function toOneArgVisitWithPath(visitFunction) {
return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
}
__name(toOneArgVisitWithPath, "toOneArgVisitWithPath");
const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
const disallowComments = options && options.disallowComments;
const allowTrailingComma = options && options.allowTrailingComma;
function scanNext() {
while (true) {
const token = _scanner.scan();
switch (_scanner.getTokenError()) {
case 4:
handleError(
14
/* ParseErrorCode.InvalidUnicode */
);
break;
case 5:
handleError(
15
/* ParseErrorCode.InvalidEscapeCharacter */
);
break;
case 3:
handleError(
13
/* ParseErrorCode.UnexpectedEndOfNumber */
);
break;
case 1:
if (!disallowComments) {
handleError(
11
/* ParseErrorCode.UnexpectedEndOfComment */
);
}
break;
case 2:
handleError(
12
/* ParseErrorCode.UnexpectedEndOfString */
);
break;
case 6:
handleError(
16
/* ParseErrorCode.InvalidCharacter */
);
break;
}
switch (token) {
case 12:
case 13:
if (disallowComments) {
handleError(
10
/* ParseErrorCode.InvalidCommentToken */
);
} else {
onComment();
}
break;
case 16:
handleError(
1
/* ParseErrorCode.InvalidSymbol */
);
break;
case 15:
case 14:
break;
default:
return token;
}
}
}
__name(scanNext, "scanNext");
function handleError(error2, skipUntilAfter = [], skipUntil = []) {
onError(error2);
if (skipUntilAfter.length + skipUntil.length > 0) {
let token = _scanner.getToken();
while (token !== 17) {
if (skipUntilAfter.indexOf(token) !== -1) {
scanNext();
break;
} else if (skipUntil.indexOf(token) !== -1) {
break;
}
token = scanNext();
}
}
}
__name(handleError, "handleError");
function parseString(isValue) {
const value = _scanner.getTokenValue();
if (isValue) {
onLiteralValue(value);
} else {
onObjectProperty(value);
_jsonPath.push(value);
}
scanNext();
return true;
}
__name(parseString, "parseString");
function parseLiteral() {
switch (_scanner.getToken()) {
case 11:
const tokenValue = _scanner.getTokenValue();
let value = Number(tokenValue);
if (isNaN(value)) {
handleError(
2
/* ParseErrorCode.InvalidNumberFormat */
);
value = 0;
}
onLiteralValue(value);
break;
case 7:
onLiteralValue(null);
break;
case 8:
onLiteralValue(true);
break;
case 9:
onLiteralValue(false);
break;
default:
return false;
}
scanNext();
return true;
}
__name(parseLiteral, "parseLiteral");
function parseProperty() {
if (_scanner.getToken() !== 10) {
handleError(3, [], [
2,
5
/* SyntaxKind.CommaToken */
]);
return false;
}
parseString(false);
if (_scanner.getToken() === 6) {
onSeparator(":");
scanNext();
if (!parseValue()) {
handleError(4, [], [
2,
5
/* SyntaxKind.CommaToken */
]);
}
} else {
handleError(5, [], [
2,
5
/* SyntaxKind.CommaToken */
]);
}
_jsonPath.pop();
return true;
}
__name(parseProperty, "parseProperty");
function parseObject() {
onObjectBegin();
scanNext();
let needsComma = false;
while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
if (_scanner.getToken() === 5) {
if (!needsComma) {
handleError(4, [], []);
}
onSeparator(",");
scanNext();
if (_scanner.getToken() === 2 && allowTrailingComma) {
break;
}
} else if (needsComma) {
handleError(6, [], []);
}
if (!parseProperty()) {
handleError(4, [], [
2,
5
/* SyntaxKind.CommaToken */
]);
}
needsComma = true;
}
onObjectEnd();
if (_scanner.getToken() !== 2) {
handleError(7, [
2
/* SyntaxKind.CloseBraceToken */
], []);
} else {
scanNext();
}
return true;
}
__name(parseObject, "parseObject");
function parseArray() {
onArrayBegin();
scanNext();
let isFirstElement = true;
let needsComma = false;
while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
if (_scanner.getToken() === 5) {
if (!needsComma) {
handleError(4, [], []);
}
onSeparator(",");
scanNext();
if (_scanner.getToken() === 4 && allowTrailingComma) {
break;
}
} else if (needsComma) {
handleError(6, [], []);
}
if (isFirstElement) {
_jsonPath.push(0);
isFirstElement = false;
} else {
_jsonPath[_jsonPath.length - 1]++;
}
if (!parseValue()) {
handleError(4, [], [
4,
5
/* SyntaxKind.CommaToken */
]);
}
needsComma = true;
}
onArrayEnd();
if (!isFirstElement) {
_jsonPath.pop();
}
if (_scanner.getToken() !== 4) {
handleError(8, [
4
/* SyntaxKind.CloseBracketToken */
], []);
} else {
scanNext();
}
return true;
}
__name(parseArray, "parseArray");
function parseValue() {
switch (_scanner.getToken()) {
case 3:
return parseArray();
case 1:
return parseObject();
case 10:
return parseString(true);
default:
return parseLiteral();
}
}
__name(parseValue, "parseValue");
scanNext();
if (_scanner.getToken() === 17) {
if (options.allowEmptyContent) {
return true;
}
handleError(4, [], []);
return false;
}
if (!parseValue()) {
handleError(4, [], []);
return false;
}
if (_scanner.getToken() !== 17) {
handleError(9, [], []);
}
return true;
}
function getNodeType(value) {
switch (typeof value) {
case "boolean":
return "boolean";
case "number":
return "number";
case "string":
return "string";
case "object": {
if (!value) {
return "null";
} else if (Array.isArray(value)) {
return "array";
}
return "object";
}
default:
return "null";
}
}
var ParseOptions;
var init_parser = __esm({
"../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/parser.js"() {
"use strict";
init_import_meta_url();
init_scanner();
(function(ParseOptions2) {
ParseOptions2.DEFAULT = {
allowTrailingComma: false
};
})(ParseOptions || (ParseOptions = {}));
__name(parse, "parse");
__name(parseTree, "parseTree");
__name(findNodeAtLocation, "findNodeAtLocation");
__name(visit, "visit");
__name(getNodeType, "getNodeType");
}
});
// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/edit.js
function setProperty(text, originalPath, value, options) {
const path72 = originalPath.slice();
const errors = [];
const root = parseTree(text, errors);
let parent = void 0;
let lastSegment = void 0;
while (path72.length > 0) {
lastSegment = path72.pop();
parent = findNodeAtLocation(root, path72);
if (parent === void 0 && value !== void 0) {
if (typeof lastSegment === "string") {
value = { [lastSegment]: value };
} else {
value = [value];
}
} else {
break;
}
}
if (!parent) {
if (value === void 0) {
throw new Error("Can not delete in empty document");
}
return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
} else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
const existing = findNodeAtLocation(parent, [lastSegment]);
if (existing !== void 0) {
if (value === void 0) {
if (!existing.parent) {
throw new Error("Malformed AST");
}
const propertyIndex = parent.children.indexOf(existing.parent);
let removeBegin;
let removeEnd = existing.parent.offset + existing.parent.length;
if (propertyIndex > 0) {
let previous = parent.children[propertyIndex - 1];
removeBegin = previous.offset + previous.length;
} else {
removeBegin = parent.offset + 1;
if (parent.children.length > 1) {
let next = parent.children[1];
removeEnd = next.offset;
}
}
return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
} else {
return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
}
} else {
if (value === void 0) {
return [];
}
const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p6) => p6.children[0].value)) : parent.children.length;
let edit;
if (index > 0) {
let previous = parent.children[index - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
} else if (parent.children.length === 0) {
edit = { offset: parent.offset + 1, length: 0, content: newProperty };
} else {
edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
}
return withFormatting(text, edit, options);
}
} else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
const insertIndex = lastSegment;
if (insertIndex === -1) {
const newProperty = `${JSON.stringify(value)}`;
let edit;
if (parent.children.length === 0) {
edit = { offset: parent.offset + 1, length: 0, content: newProperty };
} else {
const previous = parent.children[parent.children.length - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
}
return withFormatting(text, edit, options);
} else if (value === void 0 && parent.children.length >= 0) {
const removalIndex = lastSegment;
const toRemove = parent.children[removalIndex];
let edit;
if (parent.children.length === 1) {
edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
} else if (parent.children.length - 1 === removalIndex) {
let previous = parent.children[removalIndex - 1];
let offset = previous.offset + previous.length;
let parentEndOffset = parent.offset + parent.length;
edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
} else {
edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
}
return withFormatting(text, edit, options);
} else if (value !== void 0) {
let edit;
const newProperty = `${JSON.stringify(value)}`;
if (!options.isArrayInsertion && parent.children.length > lastSegment) {
const toModify = parent.children[lastSegment];
edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
} else if (parent.children.length === 0 || lastSegment === 0) {
edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
} else {
const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
const previous = parent.children[index - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
}
return withFormatting(text, edit, options);
} else {
throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
}
} else {
throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
}
}
function withFormatting(text, edit, options) {
if (!options.formattingOptions) {
return [edit];
}
let newText = applyEdit(text, edit);
let begin = edit.offset;
let end = edit.offset + edit.content.length;
if (edit.length === 0 || edit.content.length === 0) {
while (begin > 0 && !isEOL(newText, begin - 1)) {
begin--;
}
while (end < newText.length && !isEOL(newText, end)) {
end++;
}
}
const edits = format3(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
for (let i5 = edits.length - 1; i5 >= 0; i5--) {
const edit2 = edits[i5];
newText = applyEdit(newText, edit2);
begin = Math.min(begin, edit2.offset);
end = Math.max(end, edit2.offset + edit2.length);
end += edit2.content.length - edit2.length;
}
const editLength = text.length - (newText.length - end) - begin;
return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
function applyEdit(text, edit) {
return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
var init_edit = __esm({
"../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/edit.js"() {
"use strict";
init_import_meta_url();
init_format();
init_parser();
__name(setProperty, "setProperty");
__name(withFormatting, "withFormatting");
__name(applyEdit, "applyEdit");
}
});
// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/main.js
function printParseErrorCode(code) {
switch (code) {
case 1:
return "InvalidSymbol";
case 2:
return "InvalidNumberFormat";
case 3:
return "PropertyNameExpected";
case 4:
return "ValueExpected";
case 5:
return "ColonExpected";
case 6:
return "CommaExpected";
case 7:
return "CloseBraceExpected";
case 8:
return "CloseBracketExpected";
case 9:
return "EndOfFileExpected";
case 10:
return "InvalidCommentToken";
case 11:
return "UnexpectedEndOfComment";
case 12:
return "UnexpectedEndOfString";
case 13:
return "UnexpectedEndOfNumber";
case 14:
return "InvalidUnicode";
case 15:
return "InvalidEscapeCharacter";
case 16:
return "InvalidCharacter";
}
return "<unknown ParseErrorCode>";
}
function format4(documentText, range, options) {
return format3(documentText, range, options);
}
function modify(text, path72, value, options) {
return setProperty(text, path72, value, options);
}
function applyEdits(text, edits) {
let sortedEdits = edits.slice(0).sort((a5, b6) => {
const diff = a5.offset - b6.offset;
if (diff === 0) {
return a5.length - b6.length;
}
return diff;
});
let lastModifiedOffset = text.length;
for (let i5 = sortedEdits.length - 1; i5 >= 0; i5--) {
let e7 = sortedEdits[i5];
if (e7.offset + e7.length <= lastModifiedOffset) {
text = applyEdit(text, e7);
} else {
throw new Error("Overlapping edit");
}
lastModifiedOffset = e7.offset;
}
return text;
}
var ScanError, SyntaxKind, parse2, ParseErrorCode;
var init_main = __esm({
"../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/main.js"() {
"use strict";
init_import_meta_url();
init_format();
init_edit();
init_scanner();
init_parser();
(function(ScanError2) {
ScanError2[ScanError2["None"] = 0] = "None";
ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
(function(SyntaxKind2) {
SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
parse2 = parse;
(function(ParseErrorCode2) {
ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
})(ParseErrorCode || (ParseErrorCode = {}));
__name(printParseErrorCode, "printParseErrorCode");
__name(format4, "format");
__name(modify, "modify");
__name(applyEdits, "applyEdits");
}
});
// src/errors.ts
function createFatalError(message, isJson, code, telemetryMessage) {
if (isJson) {
return new JsonFriendlyFatalError(
JSON.stringify(message),
code,
telemetryMessage
);
} else {
return new FatalError(`${message}`, code, telemetryMessage);
}
}
var UserError, FatalError, CommandLineArgsError, JsonFriendlyFatalError, MissingConfigError;
var init_errors = __esm({
"src/errors.ts"() {
init_import_meta_url();
UserError = class extends Error {
static {
__name(this, "UserError");
}
telemetryMessage;
constructor(message, options) {
super(message, options);
Object.setPrototypeOf(this, new.target.prototype);
this.telemetryMessage = options?.telemetryMessage === true ? message : options?.telemetryMessage;
}
};
FatalError = class extends UserError {
constructor(message, code, options) {
super(message, options);
this.code = code;
}
static {
__name(this, "FatalError");
}
};
CommandLineArgsError = class extends UserError {
static {
__name(this, "CommandLineArgsError");
}
};
JsonFriendlyFatalError = class extends FatalError {
constructor(message, code, options) {
super(message, code, options);
this.code = code;
}
static {
__name(this, "JsonFriendlyFatalError");
}
};
MissingConfigError = class extends Error {
static {
__name(this, "MissingConfigError");
}
telemetryMessage;
constructor(key) {
super(`Missing config value for ${key}`);
this.telemetryMessage = `Missing config value for ${key}`;
}
};
__name(createFatalError, "createFatalError");
}
});
// ../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/debug.js
var require_debug = __commonJS({
"../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/debug.js"(exports2, module3) {
init_import_meta_url();
var messages = [];
var level = 0;
var debug = /* @__PURE__ */ __name((msg, min) => {
if (level >= min) {
messages.push(msg);
}
}, "debug");
debug.WARN = 1;
debug.INFO = 2;
debug.DEBUG = 3;
debug.reset = () => {
messages = [];
};
debug.setDebugLevel = (v7) => {
level = v7;
};
debug.warn = (msg) => debug(msg, debug.WARN);
debug.info = (msg) => debug(msg, debug.INFO);
debug.debug = (msg) => debug(msg, debug.DEBUG);
debug.debugMessages = () => messages;
module3.exports = debug;
}
});
// ../../node_modules/.pnpm/ansi-regex@5.0.1/node_modules/ansi-regex/index.js
var require_ansi_regex = __commonJS({
"../../node_modules/.pnpm/ansi-regex@5.0.1/node_modules/ansi-regex/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = ({ onlyFirst = false } = {}) => {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
].join("|");
return new RegExp(pattern, onlyFirst ? void 0 : "g");
};
}
});
// ../../node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js
var require_strip_ansi = __commonJS({
"../../node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var ansiRegex2 = require_ansi_regex();
module3.exports = (string) => typeof string === "string" ? string.replace(ansiRegex2(), "") : string;
}
});
// ../../node_modules/.pnpm/is-fullwidth-code-point@3.0.0/node_modules/is-fullwidth-code-point/index.js
var require_is_fullwidth_code_point = __commonJS({
"../../node_modules/.pnpm/is-fullwidth-code-point@3.0.0/node_modules/is-fullwidth-code-point/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var isFullwidthCodePoint2 = /* @__PURE__ */ __name((codePoint) => {
if (Number.isNaN(codePoint)) {
return false;
}
if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
// CJK Radicals Supplement .. Enclosed CJK Letters and Months
11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
131072 <= codePoint && codePoint <= 262141)) {
return true;
}
return false;
}, "isFullwidthCodePoint");
module3.exports = isFullwidthCodePoint2;
module3.exports.default = isFullwidthCodePoint2;
}
});
// ../../node_modules/.pnpm/emoji-regex@8.0.0/node_modules/emoji-regex/index.js
var require_emoji_regex = __commonJS({
"../../node_modules/.pnpm/emoji-regex@8.0.0/node_modules/emoji-regex/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = function() {
return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
};
}
});
// ../../node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js
var require_string_width = __commonJS({
"../../node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var stripAnsi4 = require_strip_ansi();
var isFullwidthCodePoint2 = require_is_fullwidth_code_point();
var emojiRegex3 = require_emoji_regex();
var stringWidth2 = /* @__PURE__ */ __name((string) => {
if (typeof string !== "string" || string.length === 0) {
return 0;
}
string = stripAnsi4(string);
if (string.length === 0) {
return 0;
}
string = string.replace(emojiRegex3(), " ");
let width = 0;
for (let i5 = 0; i5 < string.length; i5++) {
const code = string.codePointAt(i5);
if (code <= 31 || code >= 127 && code <= 159) {
continue;
}
if (code >= 768 && code <= 879) {
continue;
}
if (code > 65535) {
i5++;
}
width += isFullwidthCodePoint2(code) ? 2 : 1;
}
return width;
}, "stringWidth");
module3.exports = stringWidth2;
module3.exports.default = stringWidth2;
}
});
// ../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/utils.js
var require_utils2 = __commonJS({
"../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/utils.js"(exports2, module3) {
init_import_meta_url();
var stringWidth2 = require_string_width();
function codeRegex(capture) {
return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g;
}
__name(codeRegex, "codeRegex");
function strlen(str) {
let code = codeRegex();
let stripped = ("" + str).replace(code, "");
let split = stripped.split("\n");
return split.reduce(function(memo, s5) {
return stringWidth2(s5) > memo ? stringWidth2(s5) : memo;
}, 0);
}
__name(strlen, "strlen");
function repeat2(str, times) {
return Array(times + 1).join(str);
}
__name(repeat2, "repeat");
function pad2(str, len, pad3, dir) {
let length = strlen(str);
if (len + 1 >= length) {
let padlen = len - length;
switch (dir) {
case "right": {
str = repeat2(pad3, padlen) + str;
break;
}
case "center": {
let right2 = Math.ceil(padlen / 2);
let left2 = padlen - right2;
str = repeat2(pad3, left2) + str + repeat2(pad3, right2);
break;
}
default: {
str = str + repeat2(pad3, padlen);
break;
}
}
}
return str;
}
__name(pad2, "pad");
var codeCache = {};
function addToCodeCache(name2, on, off) {
on = "\x1B[" + on + "m";
off = "\x1B[" + off + "m";
codeCache[on] = { set: name2, to: true };
codeCache[off] = { set: name2, to: false };
codeCache[name2] = { on, off };
}
__name(addToCodeCache, "addToCodeCache");
addToCodeCache("bold", 1, 22);
addToCodeCache("italics", 3, 23);
addToCodeCache("underline", 4, 24);
addToCodeCache("inverse", 7, 27);
addToCodeCache("strikethrough", 9, 29);
function updateState(state2, controlChars) {
let controlCode = controlChars[1] ? parseInt(controlChars[1].split(";")[0]) : 0;
if (controlCode >= 30 && controlCode <= 39 || controlCode >= 90 && controlCode <= 97) {
state2.lastForegroundAdded = controlChars[0];
return;
}
if (controlCode >= 40 && controlCode <= 49 || controlCode >= 100 && controlCode <= 107) {
state2.lastBackgroundAdded = controlChars[0];
return;
}
if (controlCode === 0) {
for (let i5 in state2) {
if (Object.prototype.hasOwnProperty.call(state2, i5)) {
delete state2[i5];
}
}
return;
}
let info = codeCache[controlChars[0]];
if (info) {
state2[info.set] = info.to;
}
}
__name(updateState, "updateState");
function readState(line) {
let code = codeRegex(true);
let controlChars = code.exec(line);
let state2 = {};
while (controlChars !== null) {
updateState(state2, controlChars);
controlChars = code.exec(line);
}
return state2;
}
__name(readState, "readState");
function unwindState(state2, ret) {
let lastBackgroundAdded = state2.lastBackgroundAdded;
let lastForegroundAdded = state2.lastForegroundAdded;
delete state2.lastBackgroundAdded;
delete state2.lastForegroundAdded;
Object.keys(state2).forEach(function(key) {
if (state2[key]) {
ret += codeCache[key].off;
}
});
if (lastBackgroundAdded && lastBackgroundAdded != "\x1B[49m") {
ret += "\x1B[49m";
}
if (lastForegroundAdded && lastForegroundAdded != "\x1B[39m") {
ret += "\x1B[39m";
}
return ret;
}
__name(unwindState, "unwindState");
function rewindState(state2, ret) {
let lastBackgroundAdded = state2.lastBackgroundAdded;
let lastForegroundAdded = state2.lastForegroundAdded;
delete state2.lastBackgroundAdded;
delete state2.lastForegroundAdded;
Object.keys(state2).forEach(function(key) {
if (state2[key]) {
ret = codeCache[key].on + ret;
}
});
if (lastBackgroundAdded && lastBackgroundAdded != "\x1B[49m") {
ret = lastBackgroundAdded + ret;
}
if (lastForegroundAdded && lastForegroundAdded != "\x1B[39m") {
ret = lastForegroundAdded + ret;
}
return ret;
}
__name(rewindState, "rewindState");
function truncateWidth(str, desiredLength) {
if (str.length === strlen(str)) {
return str.substr(0, desiredLength);
}
while (strlen(str) > desiredLength) {
str = str.slice(0, -1);
}
return str;
}
__name(truncateWidth, "truncateWidth");
function truncateWidthWithAnsi(str, desiredLength) {
let code = codeRegex(true);
let split = str.split(codeRegex());
let splitIndex = 0;
let retLen = 0;
let ret = "";
let myArray;
let state2 = {};
while (retLen < desiredLength) {
myArray = code.exec(str);
let toAdd = split[splitIndex];
splitIndex++;
if (retLen + strlen(toAdd) > desiredLength) {
toAdd = truncateWidth(toAdd, desiredLength - retLen);
}
ret += toAdd;
retLen += strlen(toAdd);
if (retLen < desiredLength) {
if (!myArray) {
break;
}
ret += myArray[0];
updateState(state2, myArray);
}
}
return unwindState(state2, ret);
}
__name(truncateWidthWithAnsi, "truncateWidthWithAnsi");
function truncate4(str, desiredLength, truncateChar) {
truncateChar = truncateChar || "\u2026";
let lengthOfStr = strlen(str);
if (lengthOfStr <= desiredLength) {
return str;
}
desiredLength -= strlen(truncateChar);
let ret = truncateWidthWithAnsi(str, desiredLength);
return ret + truncateChar;
}
__name(truncate4, "truncate");
function defaultOptions3() {
return {
chars: {
top: "\u2500",
"top-mid": "\u252C",
"top-left": "\u250C",
"top-right": "\u2510",
bottom: "\u2500",
"bottom-mid": "\u2534",
"bottom-left": "\u2514",
"bottom-right": "\u2518",
left: "\u2502",
"left-mid": "\u251C",
mid: "\u2500",
"mid-mid": "\u253C",
right: "\u2502",
"right-mid": "\u2524",
middle: "\u2502"
},
truncate: "\u2026",
colWidths: [],
rowHeights: [],
colAligns: [],
rowAligns: [],
style: {
"padding-left": 1,
"padding-right": 1,
head: ["red"],
border: ["grey"],
compact: false
},
head: []
};
}
__name(defaultOptions3, "defaultOptions");
function mergeOptions(options, defaults) {
options = options || {};
defaults = defaults || defaultOptions3();
let ret = Object.assign({}, defaults, options);
ret.chars = Object.assign({}, defaults.chars, options.chars);
ret.style = Object.assign({}, defaults.style, options.style);
return ret;
}
__name(mergeOptions, "mergeOptions");
function wordWrap(maxLength, input) {
let lines = [];
let split = input.split(/(\s+)/g);
let line = [];
let lineLength = 0;
let whitespace;
for (let i5 = 0; i5 < split.length; i5 += 2) {
let word = split[i5];
let newLength = lineLength + strlen(word);
if (lineLength > 0 && whitespace) {
newLength += whitespace.length;
}
if (newLength > maxLength) {
if (lineLength !== 0) {
lines.push(line.join(""));
}
line = [word];
lineLength = strlen(word);
} else {
line.push(whitespace || "", word);
lineLength = newLength;
}
whitespace = split[i5 + 1];
}
if (lineLength) {
lines.push(line.join(""));
}
return lines;
}
__name(wordWrap, "wordWrap");
function textWrap(maxLength, input) {
let lines = [];
let line = "";
function pushLine(str, ws) {
if (line.length && ws) line += ws;
line += str;
while (line.length > maxLength) {
lines.push(line.slice(0, maxLength));
line = line.slice(maxLength);
}
}
__name(pushLine, "pushLine");
let split = input.split(/(\s+)/g);
for (let i5 = 0; i5 < split.length; i5 += 2) {
pushLine(split[i5], i5 && split[i5 - 1]);
}
if (line.length) lines.push(line);
return lines;
}
__name(textWrap, "textWrap");
function multiLineWordWrap(maxLength, input, wrapOnWordBoundary = true) {
let output = [];
input = input.split("\n");
const handler = wrapOnWordBoundary ? wordWrap : textWrap;
for (let i5 = 0; i5 < input.length; i5++) {
output.push.apply(output, handler(maxLength, input[i5]));
}
return output;
}
__name(multiLineWordWrap, "multiLineWordWrap");
function colorizeLines(input) {
let state2 = {};
let output = [];
for (let i5 = 0; i5 < input.length; i5++) {
let line = rewindState(state2, input[i5]);
state2 = readState(line);
let temp = Object.assign({}, state2);
output.push(unwindState(temp, line));
}
return output;
}
__name(colorizeLines, "colorizeLines");
function hyperlink(url4, text) {
const OSC2 = "\x1B]";
const BEL2 = "\x07";
const SEP2 = ";";
return [OSC2, "8", SEP2, SEP2, url4 || text, BEL2, text, OSC2, "8", SEP2, SEP2, BEL2].join("");
}
__name(hyperlink, "hyperlink");
module3.exports = {
strlen,
repeat: repeat2,
pad: pad2,
truncate: truncate4,
mergeOptions,
wordWrap: multiLineWordWrap,
colorizeLines,
hyperlink
};
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/styles.js
var require_styles = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/styles.js"(exports2, module3) {
init_import_meta_url();
var styles4 = {};
module3["exports"] = styles4;
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
grey: [90, 39],
brightRed: [91, 39],
brightGreen: [92, 39],
brightYellow: [93, 39],
brightBlue: [94, 39],
brightMagenta: [95, 39],
brightCyan: [96, 39],
brightWhite: [97, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
// legacy styles for colors pre v1.0.0
blackBG: [40, 49],
redBG: [41, 49],
greenBG: [42, 49],
yellowBG: [43, 49],
blueBG: [44, 49],
magentaBG: [45, 49],
cyanBG: [46, 49],
whiteBG: [47, 49]
};
Object.keys(codes).forEach(function(key) {
var val2 = codes[key];
var style = styles4[key] = [];
style.open = "\x1B[" + val2[0] + "m";
style.close = "\x1B[" + val2[1] + "m";
});
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/system/has-flag.js
var require_has_flag = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/system/has-flag.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.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/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/system/supports-colors.js
var require_supports_colors = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/system/supports-colors.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var os12 = require("os");
var hasFlag3 = require_has_flag();
var env6 = process.env;
var forceColor = void 0;
if (hasFlag3("no-color") || hasFlag3("no-colors") || hasFlag3("color=false")) {
forceColor = false;
} else if (hasFlag3("color") || hasFlag3("colors") || hasFlag3("color=true") || hasFlag3("color=always")) {
forceColor = true;
}
if ("FORCE_COLOR" in env6) {
forceColor = env6.FORCE_COLOR.length === 0 || parseInt(env6.FORCE_COLOR, 10) !== 0;
}
function translateLevel3(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
__name(translateLevel3, "translateLevel");
function supportsColor3(stream2) {
if (forceColor === false) {
return 0;
}
if (hasFlag3("color=16m") || hasFlag3("color=full") || hasFlag3("color=truecolor")) {
return 3;
}
if (hasFlag3("color=256")) {
return 2;
}
if (stream2 && !stream2.isTTY && forceColor !== true) {
return 0;
}
var min = forceColor ? 1 : 0;
if (process.platform === "win32") {
var osRelease = os12.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 env6) {
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
return sign in env6;
}) || env6.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env6) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env6.TEAMCITY_VERSION) ? 1 : 0;
}
if ("TERM_PROGRAM" in env6) {
var version5 = parseInt((env6.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env6.TERM_PROGRAM) {
case "iTerm.app":
return version5 >= 3 ? 3 : 2;
case "Hyper":
return 3;
case "Apple_Terminal":
return 2;
}
}
if (/-256(color)?$/i.test(env6.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env6.TERM)) {
return 1;
}
if ("COLORTERM" in env6) {
return 1;
}
if (env6.TERM === "dumb") {
return min;
}
return min;
}
__name(supportsColor3, "supportsColor");
function getSupportLevel(stream2) {
var level = supportsColor3(stream2);
return translateLevel3(level);
}
__name(getSupportLevel, "getSupportLevel");
module3.exports = {
supportsColor: getSupportLevel,
stdout: getSupportLevel(process.stdout),
stderr: getSupportLevel(process.stderr)
};
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/custom/trap.js
var require_trap = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/custom/trap.js"(exports2, module3) {
init_import_meta_url();
module3["exports"] = /* @__PURE__ */ __name(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(c6) {
c6 = c6.toLowerCase();
var chars = trap[c6] || [" "];
var rand = Math.floor(Math.random() * chars.length);
if (typeof trap[c6] !== "undefined") {
result += trap[c6][rand];
} else {
result += c6;
}
});
return result;
}, "runTheTrap");
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/custom/zalgo.js
var require_zalgo = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/custom/zalgo.js"(exports2, module3) {
init_import_meta_url();
module3["exports"] = /* @__PURE__ */ __name(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 all2 = [].concat(soul.up, soul.down, soul.mid);
function randomNumber(range) {
var r7 = Math.floor(Math.random() * range);
return r7;
}
__name(randomNumber, "randomNumber");
function isChar(character) {
var bool = false;
all2.filter(function(i5) {
bool = i5 === character;
});
return bool;
}
__name(isChar, "isChar");
function heComes(text2, options2) {
var result = "";
var counts;
var l6;
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 (l6 in text2) {
if (isChar(l6)) {
continue;
}
result = result + text2[l6];
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 d6 in arr) {
var index = arr[d6];
for (var i5 = 0; i5 <= counts[index]; i5++) {
if (options2[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
__name(heComes, "heComes");
return heComes(text, options);
}, "zalgo");
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/america.js
var require_america = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/america.js"(exports2, module3) {
init_import_meta_url();
module3["exports"] = function(colors) {
return function(letter, i5, exploded) {
if (letter === " ") return letter;
switch (i5 % 3) {
case 0:
return colors.red(letter);
case 1:
return colors.white(letter);
case 2:
return colors.blue(letter);
}
};
};
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/zebra.js
var require_zebra = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/zebra.js"(exports2, module3) {
init_import_meta_url();
module3["exports"] = function(colors) {
return function(letter, i5, exploded) {
return i5 % 2 === 0 ? letter : colors.inverse(letter);
};
};
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/rainbow.js
var require_rainbow = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/rainbow.js"(exports2, module3) {
init_import_meta_url();
module3["exports"] = function(colors) {
var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
return function(letter, i5, exploded) {
if (letter === " ") {
return letter;
} else {
return colors[rainbowColors[i5++ % rainbowColors.length]](letter);
}
};
};
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/random.js
var require_random = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/maps/random.js"(exports2, module3) {
init_import_meta_url();
module3["exports"] = function(colors) {
var available = [
"underline",
"inverse",
"grey",
"yellow",
"red",
"green",
"blue",
"white",
"cyan",
"magenta",
"brightYellow",
"brightRed",
"brightGreen",
"brightBlue",
"brightWhite",
"brightCyan",
"brightMagenta"
];
return function(letter, i5, exploded) {
return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter);
};
};
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/colors.js
var require_colors = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/lib/colors.js"(exports2, module3) {
init_import_meta_url();
var colors = {};
module3["exports"] = colors;
colors.themes = {};
var util3 = require("util");
var ansiStyles3 = colors.styles = require_styles();
var defineProps = Object.defineProperties;
var newLineRegex = new RegExp(/[\r\n]+/g);
colors.supportsColor = require_supports_colors().supportsColor;
if (typeof colors.enabled === "undefined") {
colors.enabled = colors.supportsColor() !== false;
}
colors.enable = function() {
colors.enabled = true;
};
colors.disable = function() {
colors.enabled = false;
};
colors.stripColors = colors.strip = function(str) {
return ("" + str).replace(/\x1B\[\d+m/g, "");
};
var stylize = colors.stylize = /* @__PURE__ */ __name(function stylize2(str, style) {
if (!colors.enabled) {
return str + "";
}
var styleMap = ansiStyles3[style];
if (!styleMap && style in colors) {
return colors[style](str);
}
return styleMap.open + str + styleMap.close;
}, "stylize");
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = /* @__PURE__ */ __name(function(str) {
if (typeof str !== "string") {
throw new TypeError("Expected a string");
}
return str.replace(matchOperatorsRe, "\\$&");
}, "escapeStringRegexp");
function build5(_styles) {
var builder = /* @__PURE__ */ __name(function builder2() {
return applyStyle2.apply(builder2, arguments);
}, "builder");
builder._styles = _styles;
builder.__proto__ = proto2;
return builder;
}
__name(build5, "build");
var styles4 = function() {
var ret = {};
ansiStyles3.grey = ansiStyles3.gray;
Object.keys(ansiStyles3).forEach(function(key) {
ansiStyles3[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles3[key].close), "g");
ret[key] = {
get: /* @__PURE__ */ __name(function() {
return build5(this._styles.concat(key));
}, "get")
};
});
return ret;
}();
var proto2 = defineProps(/* @__PURE__ */ __name(function colors2() {
}, "colors"), styles4);
function applyStyle2() {
var args = Array.prototype.slice.call(arguments);
var str = args.map(function(arg) {
if (arg != null && arg.constructor === String) {
return arg;
} else {
return util3.inspect(arg);
}
}).join(" ");
if (!colors.enabled || !str) {
return str;
}
var newLinesPresent = str.indexOf("\n") != -1;
var nestedStyles = this._styles;
var i5 = nestedStyles.length;
while (i5--) {
var code = ansiStyles3[nestedStyles[i5]];
str = code.open + str.replace(code.closeRe, code.open) + code.close;
if (newLinesPresent) {
str = str.replace(newLineRegex, function(match2) {
return code.close + match2 + code.open;
});
}
}
return str;
}
__name(applyStyle2, "applyStyle");
colors.setTheme = function(theme) {
if (typeof theme === "string") {
console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
return;
}
for (var style in theme) {
(function(style2) {
colors[style2] = function(str) {
if (typeof theme[style2] === "object") {
var out = str;
for (var i5 in theme[style2]) {
out = colors[theme[style2][i5]](out);
}
return out;
}
return colors[theme[style2]](str);
};
})(style);
}
};
function init3() {
var ret = {};
Object.keys(styles4).forEach(function(name2) {
ret[name2] = {
get: /* @__PURE__ */ __name(function() {
return build5([name2]);
}, "get")
};
});
return ret;
}
__name(init3, "init");
var sequencer = /* @__PURE__ */ __name(function sequencer2(map3, str) {
var exploded = str.split("");
exploded = exploded.map(map3);
return exploded.join("");
}, "sequencer");
colors.trap = require_trap();
colors.zalgo = require_zalgo();
colors.maps = {};
colors.maps.america = require_america()(colors);
colors.maps.zebra = require_zebra()(colors);
colors.maps.rainbow = require_rainbow()(colors);
colors.maps.random = require_random()(colors);
for (map2 in colors.maps) {
(function(map3) {
colors[map3] = function(str) {
return sequencer(colors.maps[map3], str);
};
})(map2);
}
var map2;
defineProps(colors, init3());
}
});
// ../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/safe.js
var require_safe = __commonJS({
"../../node_modules/.pnpm/@colors+colors@1.5.0/node_modules/@colors/colors/safe.js"(exports2, module3) {
init_import_meta_url();
var colors = require_colors();
module3["exports"] = colors;
}
});
// ../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/cell.js
var require_cell = __commonJS({
"../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/cell.js"(exports2, module3) {
init_import_meta_url();
var { info, debug } = require_debug();
var utils = require_utils2();
var Cell = class _Cell {
static {
__name(this, "Cell");
}
/**
* A representation of a cell within the table.
* Implementations must have `init` and `draw` methods,
* as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties.
* @param options
* @constructor
*/
constructor(options) {
this.setOptions(options);
this.x = null;
this.y = null;
}
setOptions(options) {
if (["boolean", "number", "string"].indexOf(typeof options) !== -1) {
options = { content: "" + options };
}
options = options || {};
this.options = options;
let content = options.content;
if (["boolean", "number", "string"].indexOf(typeof content) !== -1) {
this.content = String(content);
} else if (!content) {
this.content = this.options.href || "";
} else {
throw new Error("Content needs to be a primitive, got: " + typeof content);
}
this.colSpan = options.colSpan || 1;
this.rowSpan = options.rowSpan || 1;
if (this.options.href) {
Object.defineProperty(this, "href", {
get() {
return this.options.href;
}
});
}
}
mergeTableOptions(tableOptions, cells) {
this.cells = cells;
let optionsChars = this.options.chars || {};
let tableChars = tableOptions.chars;
let chars = this.chars = {};
CHAR_NAMES.forEach(function(name2) {
setOption(optionsChars, tableChars, name2, chars);
});
this.truncate = this.options.truncate || tableOptions.truncate;
let style = this.options.style = this.options.style || {};
let tableStyle = tableOptions.style;
setOption(style, tableStyle, "padding-left", this);
setOption(style, tableStyle, "padding-right", this);
this.head = style.head || tableStyle.head;
this.border = style.border || tableStyle.border;
this.fixedWidth = tableOptions.colWidths[this.x];
this.lines = this.computeLines(tableOptions);
this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight;
this.desiredHeight = this.lines.length;
}
computeLines(tableOptions) {
const tableWordWrap = tableOptions.wordWrap || tableOptions.textWrap;
const { wordWrap = tableWordWrap } = this.options;
if (this.fixedWidth && wordWrap) {
this.fixedWidth -= this.paddingLeft + this.paddingRight;
if (this.colSpan) {
let i5 = 1;
while (i5 < this.colSpan) {
this.fixedWidth += tableOptions.colWidths[this.x + i5];
i5++;
}
}
const { wrapOnWordBoundary: tableWrapOnWordBoundary = true } = tableOptions;
const { wrapOnWordBoundary = tableWrapOnWordBoundary } = this.options;
return this.wrapLines(utils.wordWrap(this.fixedWidth, this.content, wrapOnWordBoundary));
}
return this.wrapLines(this.content.split("\n"));
}
wrapLines(computedLines) {
const lines = utils.colorizeLines(computedLines);
if (this.href) {
return lines.map((line) => utils.hyperlink(this.href, line));
}
return lines;
}
/**
* Initializes the Cells data structure.
*
* @param tableOptions - A fully populated set of tableOptions.
* In addition to the standard default values, tableOptions must have fully populated the
* `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number
* of columns or rows (respectively) in this table, and each array item must be a Number.
*
*/
init(tableOptions) {
let x6 = this.x;
let y4 = this.y;
this.widths = tableOptions.colWidths.slice(x6, x6 + this.colSpan);
this.heights = tableOptions.rowHeights.slice(y4, y4 + this.rowSpan);
this.width = this.widths.reduce(sumPlusOne, -1);
this.height = this.heights.reduce(sumPlusOne, -1);
this.hAlign = this.options.hAlign || tableOptions.colAligns[x6];
this.vAlign = this.options.vAlign || tableOptions.rowAligns[y4];
this.drawRight = x6 + this.colSpan == tableOptions.colWidths.length;
}
/**
* Draws the given line of the cell.
* This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`.
* @param lineNum - can be `top`, `bottom` or a numerical line number.
* @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how
* many rows below it's being called from. Otherwise it's undefined.
* @returns {String} The representation of this line.
*/
draw(lineNum, spanningCell) {
if (lineNum == "top") return this.drawTop(this.drawRight);
if (lineNum == "bottom") return this.drawBottom(this.drawRight);
let content = utils.truncate(this.content, 10, this.truncate);
if (!lineNum) {
info(`${this.y}-${this.x}: ${this.rowSpan - lineNum}x${this.colSpan} Cell ${content}`);
} else {
}
let padLen = Math.max(this.height - this.lines.length, 0);
let padTop;
switch (this.vAlign) {
case "center":
padTop = Math.ceil(padLen / 2);
break;
case "bottom":
padTop = padLen;
break;
default:
padTop = 0;
}
if (lineNum < padTop || lineNum >= padTop + this.lines.length) {
return this.drawEmpty(this.drawRight, spanningCell);
}
let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height;
return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell);
}
/**
* Renders the top line of the cell.
* @param drawRight - true if this method should render the right edge of the cell.
* @returns {String}
*/
drawTop(drawRight) {
let content = [];
if (this.cells) {
this.widths.forEach(function(width, index) {
content.push(this._topLeftChar(index));
content.push(utils.repeat(this.chars[this.y == 0 ? "top" : "mid"], width));
}, this);
} else {
content.push(this._topLeftChar(0));
content.push(utils.repeat(this.chars[this.y == 0 ? "top" : "mid"], this.width));
}
if (drawRight) {
content.push(this.chars[this.y == 0 ? "topRight" : "rightMid"]);
}
return this.wrapWithStyleColors("border", content.join(""));
}
_topLeftChar(offset) {
let x6 = this.x + offset;
let leftChar;
if (this.y == 0) {
leftChar = x6 == 0 ? "topLeft" : offset == 0 ? "topMid" : "top";
} else {
if (x6 == 0) {
leftChar = "leftMid";
} else {
leftChar = offset == 0 ? "midMid" : "bottomMid";
if (this.cells) {
let spanAbove = this.cells[this.y - 1][x6] instanceof _Cell.ColSpanCell;
if (spanAbove) {
leftChar = offset == 0 ? "topMid" : "mid";
}
if (offset == 0) {
let i5 = 1;
while (this.cells[this.y][x6 - i5] instanceof _Cell.ColSpanCell) {
i5++;
}
if (this.cells[this.y][x6 - i5] instanceof _Cell.RowSpanCell) {
leftChar = "leftMid";
}
}
}
}
}
return this.chars[leftChar];
}
wrapWithStyleColors(styleProperty, content) {
if (this[styleProperty] && this[styleProperty].length) {
try {
let colors = require_safe();
for (let i5 = this[styleProperty].length - 1; i5 >= 0; i5--) {
colors = colors[this[styleProperty][i5]];
}
return colors(content);
} catch (e7) {
return content;
}
} else {
return content;
}
}
/**
* Renders a line of text.
* @param lineNum - Which line of text to render. This is not necessarily the line within the cell.
* There may be top-padding above the first line of text.
* @param drawRight - true if this method should render the right edge of the cell.
* @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even
* if the text fits. This is used when the cell is vertically truncated. If `false` the text should
* only include the truncation symbol if the text will not fit horizontally within the cell width.
* @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.
* @returns {String}
*/
drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) {
let left2 = this.chars[this.x == 0 ? "left" : "middle"];
if (this.x && spanningCell && this.cells) {
let cellLeft = this.cells[this.y + spanningCell][this.x - 1];
while (cellLeft instanceof ColSpanCell) {
cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];
}
if (!(cellLeft instanceof RowSpanCell)) {
left2 = this.chars["rightMid"];
}
}
let leftPadding = utils.repeat(" ", this.paddingLeft);
let right2 = drawRight ? this.chars["right"] : "";
let rightPadding = utils.repeat(" ", this.paddingRight);
let line = this.lines[lineNum];
let len = this.width - (this.paddingLeft + this.paddingRight);
if (forceTruncationSymbol) line += this.truncate || "\u2026";
let content = utils.truncate(line, len, this.truncate);
content = utils.pad(content, len, " ", this.hAlign);
content = leftPadding + content + rightPadding;
return this.stylizeLine(left2, content, right2);
}
stylizeLine(left2, content, right2) {
left2 = this.wrapWithStyleColors("border", left2);
right2 = this.wrapWithStyleColors("border", right2);
if (this.y === 0) {
content = this.wrapWithStyleColors("head", content);
}
return left2 + content + right2;
}
/**
* Renders the bottom line of the cell.
* @param drawRight - true if this method should render the right edge of the cell.
* @returns {String}
*/
drawBottom(drawRight) {
let left2 = this.chars[this.x == 0 ? "bottomLeft" : "bottomMid"];
let content = utils.repeat(this.chars.bottom, this.width);
let right2 = drawRight ? this.chars["bottomRight"] : "";
return this.wrapWithStyleColors("border", left2 + content + right2);
}
/**
* Renders a blank line of text within the cell. Used for top and/or bottom padding.
* @param drawRight - true if this method should render the right edge of the cell.
* @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.
* @returns {String}
*/
drawEmpty(drawRight, spanningCell) {
let left2 = this.chars[this.x == 0 ? "left" : "middle"];
if (this.x && spanningCell && this.cells) {
let cellLeft = this.cells[this.y + spanningCell][this.x - 1];
while (cellLeft instanceof ColSpanCell) {
cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];
}
if (!(cellLeft instanceof RowSpanCell)) {
left2 = this.chars["rightMid"];
}
}
let right2 = drawRight ? this.chars["right"] : "";
let content = utils.repeat(" ", this.width);
return this.stylizeLine(left2, content, right2);
}
};
var ColSpanCell = class {
static {
__name(this, "ColSpanCell");
}
/**
* A Cell that doesn't do anything. It just draws empty lines.
* Used as a placeholder in column spanning.
* @constructor
*/
constructor() {
}
draw(lineNum) {
if (typeof lineNum === "number") {
debug(`${this.y}-${this.x}: 1x1 ColSpanCell`);
}
return "";
}
init() {
}
mergeTableOptions() {
}
};
var RowSpanCell = class {
static {
__name(this, "RowSpanCell");
}
/**
* A placeholder Cell for a Cell that spans multiple rows.
* It delegates rendering to the original cell, but adds the appropriate offset.
* @param originalCell
* @constructor
*/
constructor(originalCell) {
this.originalCell = originalCell;
}
init(tableOptions) {
let y4 = this.y;
let originalY = this.originalCell.y;
this.cellOffset = y4 - originalY;
this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset);
}
draw(lineNum) {
if (lineNum == "top") {
return this.originalCell.draw(this.offset, this.cellOffset);
}
if (lineNum == "bottom") {
return this.originalCell.draw("bottom");
}
debug(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`);
return this.originalCell.draw(this.offset + 1 + lineNum);
}
mergeTableOptions() {
}
};
function firstDefined(...args) {
return args.filter((v7) => v7 !== void 0 && v7 !== null).shift();
}
__name(firstDefined, "firstDefined");
function setOption(objA, objB, nameB, targetObj) {
let nameA = nameB.split("-");
if (nameA.length > 1) {
nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1);
nameA = nameA.join("");
targetObj[nameA] = firstDefined(objA[nameA], objA[nameB], objB[nameA], objB[nameB]);
} else {
targetObj[nameB] = firstDefined(objA[nameB], objB[nameB]);
}
}
__name(setOption, "setOption");
function findDimension(dimensionTable, startingIndex, span) {
let ret = dimensionTable[startingIndex];
for (let i5 = 1; i5 < span; i5++) {
ret += 1 + dimensionTable[startingIndex + i5];
}
return ret;
}
__name(findDimension, "findDimension");
function sumPlusOne(a5, b6) {
return a5 + b6 + 1;
}
__name(sumPlusOne, "sumPlusOne");
var CHAR_NAMES = [
"top",
"top-mid",
"top-left",
"top-right",
"bottom",
"bottom-mid",
"bottom-left",
"bottom-right",
"left",
"left-mid",
"mid",
"mid-mid",
"right",
"right-mid",
"middle"
];
module3.exports = Cell;
module3.exports.ColSpanCell = ColSpanCell;
module3.exports.RowSpanCell = RowSpanCell;
}
});
// ../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/layout-manager.js
var require_layout_manager = __commonJS({
"../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/layout-manager.js"(exports2, module3) {
init_import_meta_url();
var { warn: warn2, debug } = require_debug();
var Cell = require_cell();
var { ColSpanCell, RowSpanCell } = Cell;
(function() {
function next(alloc, col) {
if (alloc[col] > 0) {
return next(alloc, col + 1);
}
return col;
}
__name(next, "next");
function layoutTable(table) {
let alloc = {};
table.forEach(function(row, rowIndex) {
let col = 0;
row.forEach(function(cell) {
cell.y = rowIndex;
cell.x = rowIndex ? next(alloc, col) : col;
const rowSpan = cell.rowSpan || 1;
const colSpan = cell.colSpan || 1;
if (rowSpan > 1) {
for (let cs2 = 0; cs2 < colSpan; cs2++) {
alloc[cell.x + cs2] = rowSpan;
}
}
col = cell.x + colSpan;
});
Object.keys(alloc).forEach((idx) => {
alloc[idx]--;
if (alloc[idx] < 1) delete alloc[idx];
});
});
}
__name(layoutTable, "layoutTable");
function maxWidth(table) {
let mw = 0;
table.forEach(function(row) {
row.forEach(function(cell) {
mw = Math.max(mw, cell.x + (cell.colSpan || 1));
});
});
return mw;
}
__name(maxWidth, "maxWidth");
function maxHeight(table) {
return table.length;
}
__name(maxHeight, "maxHeight");
function cellsConflict(cell1, cell2) {
let yMin1 = cell1.y;
let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1);
let yMin2 = cell2.y;
let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1);
let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1);
let xMin1 = cell1.x;
let xMax1 = cell1.x - 1 + (cell1.colSpan || 1);
let xMin2 = cell2.x;
let xMax2 = cell2.x - 1 + (cell2.colSpan || 1);
let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1);
return yConflict && xConflict;
}
__name(cellsConflict, "cellsConflict");
function conflictExists(rows, x6, y4) {
let i_max = Math.min(rows.length - 1, y4);
let cell = { x: x6, y: y4 };
for (let i5 = 0; i5 <= i_max; i5++) {
let row = rows[i5];
for (let j6 = 0; j6 < row.length; j6++) {
if (cellsConflict(cell, row[j6])) {
return true;
}
}
}
return false;
}
__name(conflictExists, "conflictExists");
function allBlank(rows, y4, xMin, xMax) {
for (let x6 = xMin; x6 < xMax; x6++) {
if (conflictExists(rows, x6, y4)) {
return false;
}
}
return true;
}
__name(allBlank, "allBlank");
function addRowSpanCells(table) {
table.forEach(function(row, rowIndex) {
row.forEach(function(cell) {
for (let i5 = 1; i5 < cell.rowSpan; i5++) {
let rowSpanCell = new RowSpanCell(cell);
rowSpanCell.x = cell.x;
rowSpanCell.y = cell.y + i5;
rowSpanCell.colSpan = cell.colSpan;
insertCell(rowSpanCell, table[rowIndex + i5]);
}
});
});
}
__name(addRowSpanCells, "addRowSpanCells");
function addColSpanCells(cellRows) {
for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) {
let cellColumns = cellRows[rowIndex];
for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) {
let cell = cellColumns[columnIndex];
for (let k6 = 1; k6 < cell.colSpan; k6++) {
let colSpanCell = new ColSpanCell();
colSpanCell.x = cell.x + k6;
colSpanCell.y = cell.y;
cellColumns.splice(columnIndex + 1, 0, colSpanCell);
}
}
}
}
__name(addColSpanCells, "addColSpanCells");
function insertCell(cell, row) {
let x6 = 0;
while (x6 < row.length && row[x6].x < cell.x) {
x6++;
}
row.splice(x6, 0, cell);
}
__name(insertCell, "insertCell");
function fillInTable(table) {
let h_max = maxHeight(table);
let w_max = maxWidth(table);
debug(`Max rows: ${h_max}; Max cols: ${w_max}`);
for (let y4 = 0; y4 < h_max; y4++) {
for (let x6 = 0; x6 < w_max; x6++) {
if (!conflictExists(table, x6, y4)) {
let opts = { x: x6, y: y4, colSpan: 1, rowSpan: 1 };
x6++;
while (x6 < w_max && !conflictExists(table, x6, y4)) {
opts.colSpan++;
x6++;
}
let y22 = y4 + 1;
while (y22 < h_max && allBlank(table, y22, opts.x, opts.x + opts.colSpan)) {
opts.rowSpan++;
y22++;
}
let cell = new Cell(opts);
cell.x = opts.x;
cell.y = opts.y;
warn2(`Missing cell at ${cell.y}-${cell.x}.`);
insertCell(cell, table[y4]);
}
}
}
}
__name(fillInTable, "fillInTable");
function generateCells(rows) {
return rows.map(function(row) {
if (!Array.isArray(row)) {
let key = Object.keys(row)[0];
row = row[key];
if (Array.isArray(row)) {
row = row.slice();
row.unshift(key);
} else {
row = [key, row];
}
}
return row.map(function(cell) {
return new Cell(cell);
});
});
}
__name(generateCells, "generateCells");
function makeTableLayout(rows) {
let cellRows = generateCells(rows);
layoutTable(cellRows);
fillInTable(cellRows);
addRowSpanCells(cellRows);
addColSpanCells(cellRows);
return cellRows;
}
__name(makeTableLayout, "makeTableLayout");
module3.exports = {
makeTableLayout,
layoutTable,
addRowSpanCells,
maxWidth,
fillInTable,
computeWidths: makeComputeWidths("colSpan", "desiredWidth", "x", 1),
computeHeights: makeComputeWidths("rowSpan", "desiredHeight", "y", 1)
};
})();
function makeComputeWidths(colSpan, desiredWidth, x6, forcedMin) {
return function(vals, table) {
let result = [];
let spanners = [];
let auto = {};
table.forEach(function(row) {
row.forEach(function(cell) {
if ((cell[colSpan] || 1) > 1) {
spanners.push(cell);
} else {
result[cell[x6]] = Math.max(result[cell[x6]] || 0, cell[desiredWidth] || 0, forcedMin);
}
});
});
vals.forEach(function(val2, index) {
if (typeof val2 === "number") {
result[index] = val2;
}
});
for (let k6 = spanners.length - 1; k6 >= 0; k6--) {
let cell = spanners[k6];
let span = cell[colSpan];
let col = cell[x6];
let existingWidth = result[col];
let editableCols = typeof vals[col] === "number" ? 0 : 1;
if (typeof existingWidth === "number") {
for (let i5 = 1; i5 < span; i5++) {
existingWidth += 1 + result[col + i5];
if (typeof vals[col + i5] !== "number") {
editableCols++;
}
}
} else {
existingWidth = desiredWidth === "desiredWidth" ? cell.desiredWidth - 1 : 1;
if (!auto[col] || auto[col] < existingWidth) {
auto[col] = existingWidth;
}
}
if (cell[desiredWidth] > existingWidth) {
let i5 = 0;
while (editableCols > 0 && cell[desiredWidth] > existingWidth) {
if (typeof vals[col + i5] !== "number") {
let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols);
existingWidth += dif;
result[col + i5] += dif;
editableCols--;
}
i5++;
}
}
}
Object.assign(vals, result, auto);
for (let j6 = 0; j6 < vals.length; j6++) {
vals[j6] = Math.max(forcedMin, vals[j6] || 0);
}
};
}
__name(makeComputeWidths, "makeComputeWidths");
}
});
// ../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/table.js
var require_table = __commonJS({
"../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/src/table.js"(exports2, module3) {
init_import_meta_url();
var debug = require_debug();
var utils = require_utils2();
var tableLayout = require_layout_manager();
var Table2 = class extends Array {
static {
__name(this, "Table");
}
constructor(opts) {
super();
const options = utils.mergeOptions(opts);
Object.defineProperty(this, "options", {
value: options,
enumerable: options.debug
});
if (options.debug) {
switch (typeof options.debug) {
case "boolean":
debug.setDebugLevel(debug.WARN);
break;
case "number":
debug.setDebugLevel(options.debug);
break;
case "string":
debug.setDebugLevel(parseInt(options.debug, 10));
break;
default:
debug.setDebugLevel(debug.WARN);
debug.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof options.debug}`);
}
Object.defineProperty(this, "messages", {
get() {
return debug.debugMessages();
}
});
}
}
toString() {
let array = this;
let headersPresent = this.options.head && this.options.head.length;
if (headersPresent) {
array = [this.options.head];
if (this.length) {
array.push.apply(array, this);
}
} else {
this.options.style.head = [];
}
let cells = tableLayout.makeTableLayout(array);
cells.forEach(function(row) {
row.forEach(function(cell) {
cell.mergeTableOptions(this.options, cells);
}, this);
}, this);
tableLayout.computeWidths(this.options.colWidths, cells);
tableLayout.computeHeights(this.options.rowHeights, cells);
cells.forEach(function(row) {
row.forEach(function(cell) {
cell.init(this.options);
}, this);
}, this);
let result = [];
for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) {
let row = cells[rowIndex];
let heightOfRow = this.options.rowHeights[rowIndex];
if (rowIndex === 0 || !this.options.style.compact || rowIndex == 1 && headersPresent) {
doDraw(row, "top", result);
}
for (let lineNum = 0; lineNum < heightOfRow; lineNum++) {
doDraw(row, lineNum, result);
}
if (rowIndex + 1 == cells.length) {
doDraw(row, "bottom", result);
}
}
return result.join("\n");
}
get width() {
let str = this.toString().split("\n");
return str[0].length;
}
};
Table2.reset = () => debug.reset();
function doDraw(row, lineNum, result) {
let line = [];
row.forEach(function(cell) {
line.push(cell.draw(lineNum));
});
let str = line.join("");
if (str.length) result.push(str);
}
__name(doDraw, "doDraw");
module3.exports = Table2;
}
});
// ../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/index.js
var require_cli_table3 = __commonJS({
"../../node_modules/.pnpm/cli-table3@0.6.3/node_modules/cli-table3/index.js"(exports2, module3) {
init_import_meta_url();
module3.exports = require_table();
}
});
// src/environment-variables/factory.ts
function getBooleanEnvironmentVariableFactory(options) {
return () => {
if (!(options.variableName in process.env) || process.env[options.variableName] === void 0) {
return typeof options.defaultValue === "function" ? options.defaultValue() : options.defaultValue;
}
switch (process.env[options.variableName]?.toLowerCase()) {
case "true":
return true;
case "false":
return false;
default:
throw new UserError(
`Expected ${options.variableName} to be "true" or "false", but got ${JSON.stringify(
process.env[options.variableName]
)}`
);
}
};
}
function getEnvironmentVariableFactory({
variableName,
deprecatedName,
choices,
defaultValue
}) {
let hasWarned = false;
return () => {
if (variableName in process.env) {
return getProcessEnv(variableName, choices);
}
if (deprecatedName && deprecatedName in process.env) {
if (!hasWarned) {
hasWarned = true;
console.warn(
`Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
);
}
return getProcessEnv(deprecatedName, choices);
}
return defaultValue?.();
};
}
function getProcessEnv(variableName, choices) {
assertOneOf(choices, process.env[variableName]);
return process.env[variableName];
}
function assertOneOf(choices, value) {
if (Array.isArray(choices) && !choices.includes(value)) {
throw new UserError(
`Expected ${JSON.stringify(value)} to be one of ${JSON.stringify(choices)}`
);
}
}
var init_factory = __esm({
"src/environment-variables/factory.ts"() {
init_import_meta_url();
init_errors();
__name(getBooleanEnvironmentVariableFactory, "getBooleanEnvironmentVariableFactory");
__name(getEnvironmentVariableFactory, "getEnvironmentVariableFactory");
__name(getProcessEnv, "getProcessEnv");
__name(assertOneOf, "assertOneOf");
}
});
// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js
var require_XDGAppPaths = __commonJS({
"../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js"(exports2) {
"use strict";
init_import_meta_url();
exports2.__esModule = true;
exports2.Adapt = void 0;
function isBoolean3(t7) {
return typeOf(t7) === "boolean";
}
__name(isBoolean3, "isBoolean");
function isObject3(t7) {
return typeOf(t7) === "object";
}
__name(isObject3, "isObject");
function isString4(t7) {
return typeOf(t7) === "string";
}
__name(isString4, "isString");
function typeOf(t7) {
return typeof t7;
}
__name(typeOf, "typeOf");
function Adapt(adapter_) {
var meta = adapter_.meta, path72 = adapter_.path, xdg = adapter_.xdg;
var XDGAppPaths_ = /* @__PURE__ */ function() {
function XDGAppPaths_2(options_) {
if (options_ === void 0) {
options_ = {};
}
var _a4, _b2, _c3;
function XDGAppPaths(options2) {
if (options2 === void 0) {
options2 = {};
}
return new XDGAppPaths_2(options2);
}
__name(XDGAppPaths, "XDGAppPaths");
var options = isObject3(options_) ? options_ : { name: options_ };
var suffix = (_a4 = options.suffix) !== null && _a4 !== void 0 ? _a4 : "";
var isolated_ = (_b2 = options.isolated) !== null && _b2 !== void 0 ? _b2 : true;
var namePriorityList = [
options.name,
meta.pkgMainFilename(),
meta.mainFilename()
];
var nameFallback = "$eval";
var name2 = path72.parse(((_c3 = namePriorityList.find(function(e7) {
return isString4(e7);
})) !== null && _c3 !== void 0 ? _c3 : nameFallback) + suffix).name;
XDGAppPaths.$name = /* @__PURE__ */ __name(function $name() {
return name2;
}, "$name");
XDGAppPaths.$isolated = /* @__PURE__ */ __name(function $isolated() {
return isolated_;
}, "$isolated");
function isIsolated(dirOptions) {
var _a5;
dirOptions = dirOptions !== null && dirOptions !== void 0 ? dirOptions : { isolated: isolated_ };
var isolated = isBoolean3(dirOptions) ? dirOptions : (_a5 = dirOptions.isolated) !== null && _a5 !== void 0 ? _a5 : isolated_;
return isolated;
}
__name(isIsolated, "isIsolated");
function finalPathSegment(dirOptions) {
return isIsolated(dirOptions) ? name2 : "";
}
__name(finalPathSegment, "finalPathSegment");
XDGAppPaths.cache = /* @__PURE__ */ __name(function cache6(dirOptions) {
return path72.join(xdg.cache(), finalPathSegment(dirOptions));
}, "cache");
XDGAppPaths.config = /* @__PURE__ */ __name(function config(dirOptions) {
return path72.join(xdg.config(), finalPathSegment(dirOptions));
}, "config");
XDGAppPaths.data = /* @__PURE__ */ __name(function data(dirOptions) {
return path72.join(xdg.data(), finalPathSegment(dirOptions));
}, "data");
XDGAppPaths.runtime = /* @__PURE__ */ __name(function runtime(dirOptions) {
return xdg.runtime() ? path72.join(xdg.runtime(), finalPathSegment(dirOptions)) : void 0;
}, "runtime");
XDGAppPaths.state = /* @__PURE__ */ __name(function state2(dirOptions) {
return path72.join(xdg.state(), finalPathSegment(dirOptions));
}, "state");
XDGAppPaths.configDirs = /* @__PURE__ */ __name(function configDirs(dirOptions) {
return xdg.configDirs().map(function(s5) {
return path72.join(s5, finalPathSegment(dirOptions));
});
}, "configDirs");
XDGAppPaths.dataDirs = /* @__PURE__ */ __name(function dataDirs(dirOptions) {
return xdg.dataDirs().map(function(s5) {
return path72.join(s5, finalPathSegment(dirOptions));
});
}, "dataDirs");
return XDGAppPaths;
}
__name(XDGAppPaths_2, "XDGAppPaths_");
return XDGAppPaths_2;
}();
return { XDGAppPaths: new XDGAppPaths_() };
}
__name(Adapt, "Adapt");
exports2.Adapt = Adapt;
}
});
// ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js
var require_XDG = __commonJS({
"../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js"(exports2) {
"use strict";
init_import_meta_url();
var __spreadArray = exports2 && exports2.__spreadArray || function(to, from) {
for (var i5 = 0, il = from.length, j6 = to.length; i5 < il; i5++, j6++)
to[j6] = from[i5];
return to;
};
exports2.__esModule = true;
exports2.Adapt = void 0;
function Adapt(adapter_) {
var env6 = adapter_.env, osPaths = adapter_.osPaths, path72 = adapter_.path;
var isMacOS = /^darwin$/i.test(adapter_.process.platform);
var isWinOS = /^win/i.test(adapter_.process.platform);
function baseDir() {
return osPaths.home() || osPaths.temp();
}
__name(baseDir, "baseDir");
function valOrPath(val2, pathSegments) {
return val2 || path72.join.apply(path72, pathSegments);
}
__name(valOrPath, "valOrPath");
var linux = /* @__PURE__ */ __name(function() {
var cache6 = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
}, "cache");
var config = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
}, "config");
var data = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_DATA_HOME"), [baseDir(), ".local", "share"]);
}, "data");
var runtime = /* @__PURE__ */ __name(function() {
return env6.get("XDG_RUNTIME_DIR") || void 0;
}, "runtime");
var state2 = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_STATE_HOME"), [baseDir(), ".local", "state"]);
}, "state");
return { cache: cache6, config, data, runtime, state: state2 };
}, "linux");
var macos = /* @__PURE__ */ __name(function() {
var cache6 = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_CACHE_HOME"), [baseDir(), "Library", "Caches"]);
}, "cache");
var config = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_CONFIG_HOME"), [baseDir(), "Library", "Preferences"]);
}, "config");
var data = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_DATA_HOME"), [baseDir(), "Library", "Application Support"]);
}, "data");
var runtime = /* @__PURE__ */ __name(function() {
return env6.get("XDG_RUNTIME_DIR") || void 0;
}, "runtime");
var state2 = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_STATE_HOME"), [baseDir(), "Library", "State"]);
}, "state");
return { cache: cache6, config, data, runtime, state: state2 };
}, "macos");
var windows = /* @__PURE__ */ __name(function() {
function appData() {
return valOrPath(env6.get("APPDATA"), [baseDir(), "AppData", "Roaming"]);
}
__name(appData, "appData");
function localAppData() {
return valOrPath(env6.get("LOCALAPPDATA"), [baseDir(), "AppData", "Local"]);
}
__name(localAppData, "localAppData");
var cache6 = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_CACHE_HOME"), [localAppData(), "xdg.cache"]);
}, "cache");
var config = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_CONFIG_HOME"), [appData(), "xdg.config"]);
}, "config");
var data = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_DATA_HOME"), [appData(), "xdg.data"]);
}, "data");
var runtime = /* @__PURE__ */ __name(function() {
return env6.get("XDG_RUNTIME_DIR") || void 0;
}, "runtime");
var state2 = /* @__PURE__ */ __name(function() {
return valOrPath(env6.get("XDG_STATE_HOME"), [localAppData(), "xdg.state"]);
}, "state");
return { cache: cache6, config, data, runtime, state: state2 };
}, "windows");
var XDG_ = /* @__PURE__ */ function() {
function XDG_2() {
function XDG() {
return new XDG_2();
}
__name(XDG, "XDG");
var extension = isMacOS ? macos() : isWinOS ? windows() : linux();
XDG.cache = extension.cache;
XDG.config = extension.config;
XDG.data = extension.data;
XDG.runtime = extension.runtime;
XDG.state = extension.state;
XDG.configDirs = /* @__PURE__ */ __name(function configDirs() {
var pathList = env6.get("XDG_CONFIG_DIRS");
return __spreadArray([extension.config()], pathList ? pathList.split(path72.delimiter) : []);
}, "configDirs");
XDG.dataDirs = /* @__PURE__ */ __name(function dataDirs() {
var pathList = env6.get("XDG_DATA_DIRS");
return __spreadArray([extension.data()], pathList ? pathList.split(path72.delimiter) : []);
}, "dataDirs");
return XDG;
}
__name(XDG_2, "XDG_");
return XDG_2;
}();
return { XDG: new XDG_() };
}
__name(Adapt, "Adapt");
exports2.Adapt = Adapt;
}
});
// ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js
var require_OSPaths = __commonJS({
"../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js"(exports2) {
"use strict";
init_import_meta_url();
var __spreadArray = exports2 && exports2.__spreadArray || function(to, from) {
for (var i5 = 0, il = from.length, j6 = to.length; i5 < il; i5++, j6++)
to[j6] = from[i5];
return to;
};
exports2.__esModule = true;
exports2.Adapt = void 0;
function isEmpty(s5) {
return !s5;
}
__name(isEmpty, "isEmpty");
function Adapt(adapter_) {
var env6 = adapter_.env, os12 = adapter_.os, path72 = adapter_.path;
var isWinOS = /^win/i.test(adapter_.process.platform);
function normalizePath2(path_) {
return path_ ? adapter_.path.normalize(adapter_.path.join(path_, ".")) : void 0;
}
__name(normalizePath2, "normalizePath");
function home() {
var posix2 = /* @__PURE__ */ __name(function() {
return normalizePath2((typeof os12.homedir === "function" ? os12.homedir() : void 0) || env6.get("HOME"));
}, "posix");
var windows = /* @__PURE__ */ __name(function() {
var priorityList = [
typeof os12.homedir === "function" ? os12.homedir() : void 0,
env6.get("USERPROFILE"),
env6.get("HOME"),
env6.get("HOMEDRIVE") || env6.get("HOMEPATH") ? path72.join(env6.get("HOMEDRIVE") || "", env6.get("HOMEPATH") || "") : void 0
];
return normalizePath2(priorityList.find(function(v7) {
return !isEmpty(v7);
}));
}, "windows");
return isWinOS ? windows() : posix2();
}
__name(home, "home");
function temp() {
function joinPathToBase(base, segments) {
return base ? path72.join.apply(path72, __spreadArray([base], segments)) : void 0;
}
__name(joinPathToBase, "joinPathToBase");
function posix2() {
var fallback = "/tmp";
var priorityList = [
typeof os12.tmpdir === "function" ? os12.tmpdir() : void 0,
env6.get("TMPDIR"),
env6.get("TEMP"),
env6.get("TMP")
];
return normalizePath2(priorityList.find(function(v7) {
return !isEmpty(v7);
})) || fallback;
}
__name(posix2, "posix");
function windows() {
var fallback = "C:\\Temp";
var priorityListLazy = [
typeof os12.tmpdir === "function" ? os12.tmpdir : function() {
return void 0;
},
function() {
return env6.get("TEMP");
},
function() {
return env6.get("TMP");
},
function() {
return joinPathToBase(env6.get("LOCALAPPDATA"), ["Temp"]);
},
function() {
return joinPathToBase(home(), ["AppData", "Local", "Temp"]);
},
function() {
return joinPathToBase(env6.get("ALLUSERSPROFILE"), ["Temp"]);
},
function() {
return joinPathToBase(env6.get("SystemRoot"), ["Temp"]);
},
function() {
return joinPathToBase(env6.get("windir"), ["Temp"]);
},
function() {
return joinPathToBase(env6.get("SystemDrive"), ["\\", "Temp"]);
}
];
var v7 = priorityListLazy.find(function(v8) {
return v8 && !isEmpty(v8());
});
return v7 && normalizePath2(v7()) || fallback;
}
__name(windows, "windows");
return isWinOS ? windows() : posix2();
}
__name(temp, "temp");
var OSPaths_ = /* @__PURE__ */ function() {
function OSPaths_2() {
function OSPaths() {
return new OSPaths_2();
}
__name(OSPaths, "OSPaths");
OSPaths.home = home;
OSPaths.temp = temp;
return OSPaths;
}
__name(OSPaths_2, "OSPaths_");
return OSPaths_2;
}();
return { OSPaths: new OSPaths_() };
}
__name(Adapt, "Adapt");
exports2.Adapt = Adapt;
}
});
// ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js
var require_node = __commonJS({
"../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js"(exports2) {
"use strict";
init_import_meta_url();
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
Object.defineProperty(o5, k22, { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m6[k6];
}, "get") });
} : function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
o5[k22] = m6[k6];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v7) {
Object.defineProperty(o5, "default", { enumerable: true, value: v7 });
} : function(o5, v7) {
o5["default"] = v7;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k6 in mod) if (k6 !== "default" && Object.prototype.hasOwnProperty.call(mod, k6)) __createBinding(result, mod, k6);
}
__setModuleDefault(result, mod);
return result;
};
exports2.__esModule = true;
exports2.adapter = void 0;
var os12 = __importStar(require("os"));
var path72 = __importStar(require("path"));
exports2.adapter = {
atImportPermissions: { env: true },
env: {
get: /* @__PURE__ */ __name(function(s5) {
return process.env[s5];
}, "get")
},
os: os12,
path: path72,
process
};
}
});
// ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js
var require_mod_cjs = __commonJS({
"../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var OSPaths_js_1 = require_OSPaths();
var node_js_1 = require_node();
module3.exports = OSPaths_js_1.Adapt(node_js_1.adapter).OSPaths;
}
});
// ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js
var require_node2 = __commonJS({
"../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js"(exports2) {
"use strict";
init_import_meta_url();
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
Object.defineProperty(o5, k22, { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m6[k6];
}, "get") });
} : function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
o5[k22] = m6[k6];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v7) {
Object.defineProperty(o5, "default", { enumerable: true, value: v7 });
} : function(o5, v7) {
o5["default"] = v7;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k6 in mod) if (k6 !== "default" && Object.prototype.hasOwnProperty.call(mod, k6)) __createBinding(result, mod, k6);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
exports2.__esModule = true;
exports2.adapter = void 0;
var path72 = __importStar(require("path"));
var os_paths_1 = __importDefault(require_mod_cjs());
exports2.adapter = {
atImportPermissions: { env: true },
env: {
get: /* @__PURE__ */ __name(function(s5) {
return process.env[s5];
}, "get")
},
osPaths: os_paths_1["default"],
path: path72,
process
};
}
});
// ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js
var require_mod_cjs2 = __commonJS({
"../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var XDG_js_1 = require_XDG();
var node_js_1 = require_node2();
module3.exports = XDG_js_1.Adapt(node_js_1.adapter).XDG;
}
});
// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js
var require_node3 = __commonJS({
"../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js"(exports2) {
"use strict";
init_import_meta_url();
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
Object.defineProperty(o5, k22, { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m6[k6];
}, "get") });
} : function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
o5[k22] = m6[k6];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v7) {
Object.defineProperty(o5, "default", { enumerable: true, value: v7 });
} : function(o5, v7) {
o5["default"] = v7;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k6 in mod) if (k6 !== "default" && Object.prototype.hasOwnProperty.call(mod, k6)) __createBinding(result, mod, k6);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
exports2.__esModule = true;
exports2.adapter = void 0;
var path72 = __importStar(require("path"));
var xdg_portable_1 = __importDefault(require_mod_cjs2());
exports2.adapter = {
atImportPermissions: { env: true, read: true },
meta: {
mainFilename: /* @__PURE__ */ __name(function() {
var requireMain = typeof require !== "undefined" && require !== null && require.main ? require.main : { filename: void 0 };
var requireMainFilename = requireMain.filename;
var filename = (requireMainFilename !== process.execArgv[0] ? requireMainFilename : void 0) || (typeof process._eval === "undefined" ? process.argv[1] : void 0);
return filename;
}, "mainFilename"),
pkgMainFilename: /* @__PURE__ */ __name(function() {
return process.pkg ? process.execPath : void 0;
}, "pkgMainFilename")
},
path: path72,
process,
xdg: xdg_portable_1["default"]
};
}
});
// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js
var require_mod_cjs3 = __commonJS({
"../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var XDGAppPaths_js_1 = require_XDGAppPaths();
var node_js_1 = require_node3();
module3.exports = XDGAppPaths_js_1.Adapt(node_js_1.adapter).XDGAppPaths;
}
});
// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/esm-wrapper/mod.esm.js
var mod_esm_exports = {};
__export(mod_esm_exports, {
default: () => mod_esm_default
});
var import_mod_cjs, mod_esm_default;
var init_mod_esm = __esm({
"../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/esm-wrapper/mod.esm.js"() {
init_import_meta_url();
import_mod_cjs = __toESM(require_mod_cjs3(), 1);
__reExport(mod_esm_exports, __toESM(require_mod_cjs3(), 1));
mod_esm_default = import_mod_cjs.default;
}
});
// src/global-wrangler-config-path.ts
function isDirectory(configPath) {
try {
return import_node_fs.default.statSync(configPath).isDirectory();
} catch {
return false;
}
}
function getGlobalWranglerConfigPath() {
const configDir = mod_esm_default(".wrangler").config();
const legacyConfigDir = import_node_path.default.join(import_node_os2.default.homedir(), ".wrangler");
if (isDirectory(legacyConfigDir)) {
return legacyConfigDir;
} else {
return configDir;
}
}
var import_node_fs, import_node_os2, import_node_path;
var init_global_wrangler_config_path = __esm({
"src/global-wrangler-config-path.ts"() {
init_import_meta_url();
import_node_fs = __toESM(require("fs"));
import_node_os2 = __toESM(require("os"));
import_node_path = __toESM(require("path"));
init_mod_esm();
__name(isDirectory, "isDirectory");
__name(getGlobalWranglerConfigPath, "getGlobalWranglerConfigPath");
}
});
// src/environment-variables/misc-variables.ts
function getComplianceRegionSubdomain(complianceConfig) {
return getCloudflareComplianceRegion(complianceConfig) === "fedramp_high" ? ".fed" : "";
}
function getStagingSubdomain() {
return getCloudflareApiEnvironmentFromEnv() === "staging" ? ".staging" : "";
}
var import_node_path2, getC3CommandFromEnv, getWranglerSendMetricsFromEnv, getCloudflareApiEnvironmentFromEnv, COMPLIANCE_REGION_CONFIG_PUBLIC, COMPLIANCE_REGION_CONFIG_UNKNOWN, getCloudflareComplianceRegionFromEnv, getCloudflareComplianceRegion, getCloudflareApiBaseUrlFromEnv, getCloudflareApiBaseUrl, getSanitizeLogs, getOutputFileDirectoryFromEnv, getOutputFilePathFromEnv, getCIMatchTag, getCIOverrideName, getCIOverrideNetworkModeHost, getCIGeneratePreviewAlias, getWorkersCIBranchName, getBuildConditionsFromEnv, getBuildPlatformFromEnv, getRegistryPath, getD1ExtraLocationChoices, getDockerPath, getCloudflareLoadDevVarsFromDotEnv, getCloudflareIncludeProcessEnvFromEnv;
var init_misc_variables = __esm({
"src/environment-variables/misc-variables.ts"() {
init_import_meta_url();
import_node_path2 = __toESM(require("path"));
init_esm2();
init_errors();
init_global_wrangler_config_path();
init_factory();
getC3CommandFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_C3_COMMAND",
defaultValue: /* @__PURE__ */ __name(() => "create cloudflare@^2.5.0", "defaultValue")
});
getWranglerSendMetricsFromEnv = getBooleanEnvironmentVariableFactory({
variableName: "WRANGLER_SEND_METRICS"
});
getCloudflareApiEnvironmentFromEnv = getEnvironmentVariableFactory(
{
variableName: "WRANGLER_API_ENVIRONMENT",
defaultValue: /* @__PURE__ */ __name(() => "production", "defaultValue"),
choices: ["production", "staging"]
}
);
COMPLIANCE_REGION_CONFIG_PUBLIC = {
compliance_region: "public"
};
COMPLIANCE_REGION_CONFIG_UNKNOWN = {
compliance_region: void 0
};
getCloudflareComplianceRegionFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_COMPLIANCE_REGION",
choices: ["public", "fedramp_high"]
});
getCloudflareComplianceRegion = /* @__PURE__ */ __name((complianceConfig) => {
const complianceRegionFromEnv = getCloudflareComplianceRegionFromEnv();
if (complianceRegionFromEnv !== void 0 && complianceConfig?.compliance_region !== void 0 && complianceRegionFromEnv !== complianceConfig.compliance_region) {
throw new UserError(dedent`
The compliance region has been set to different values in two places:
- \`CLOUDFLARE_COMPLIANCE_REGION\` environment variable: \`${complianceRegionFromEnv}\`
- \`compliance_region\` configuration property: \`${complianceConfig.compliance_region}\`
`);
}
return complianceRegionFromEnv || complianceConfig?.compliance_region || "public";
}, "getCloudflareComplianceRegion");
getCloudflareApiBaseUrlFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_API_BASE_URL",
deprecatedName: "CF_API_BASE_URL"
});
getCloudflareApiBaseUrl = /* @__PURE__ */ __name((complianceConfig) => getCloudflareApiBaseUrlFromEnv() ?? `https://api${getComplianceRegionSubdomain(complianceConfig)}${getStagingSubdomain()}.cloudflare.com/client/v4`, "getCloudflareApiBaseUrl");
__name(getComplianceRegionSubdomain, "getComplianceRegionSubdomain");
__name(getStagingSubdomain, "getStagingSubdomain");
getSanitizeLogs = getBooleanEnvironmentVariableFactory({
variableName: "WRANGLER_LOG_SANITIZE",
defaultValue: true
});
getOutputFileDirectoryFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_OUTPUT_FILE_DIRECTORY"
});
getOutputFilePathFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_OUTPUT_FILE_PATH"
});
getCIMatchTag = getEnvironmentVariableFactory({
variableName: "WRANGLER_CI_MATCH_TAG"
});
getCIOverrideName = getEnvironmentVariableFactory({
variableName: "WRANGLER_CI_OVERRIDE_NAME"
});
getCIOverrideNetworkModeHost = getEnvironmentVariableFactory({
variableName: "WRANGLER_CI_OVERRIDE_NETWORK_MODE_HOST"
});
getCIGeneratePreviewAlias = getEnvironmentVariableFactory({
variableName: "WRANGLER_CI_GENERATE_PREVIEW_ALIAS",
defaultValue: /* @__PURE__ */ __name(() => "false", "defaultValue"),
choices: ["true", "false"]
});
getWorkersCIBranchName = getEnvironmentVariableFactory({
variableName: "WORKERS_CI_BRANCH"
});
getBuildConditionsFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_BUILD_CONDITIONS"
});
getBuildPlatformFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_BUILD_PLATFORM"
});
getRegistryPath = getEnvironmentVariableFactory({
variableName: "WRANGLER_REGISTRY_PATH",
defaultValue() {
return import_node_path2.default.join(getGlobalWranglerConfigPath(), "registry");
}
});
getD1ExtraLocationChoices = getEnvironmentVariableFactory({
variableName: "WRANGLER_D1_EXTRA_LOCATION_CHOICES"
});
getDockerPath = getEnvironmentVariableFactory({
variableName: "WRANGLER_DOCKER_BIN",
defaultValue() {
return "docker";
}
});
getCloudflareLoadDevVarsFromDotEnv = getBooleanEnvironmentVariableFactory({
variableName: "CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV",
defaultValue: true
});
getCloudflareIncludeProcessEnvFromEnv = getBooleanEnvironmentVariableFactory({
variableName: "CLOUDFLARE_INCLUDE_PROCESS_ENV",
defaultValue: false
});
}
});
// ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js
var require_signals = __commonJS({
"../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports2, module3) {
init_import_meta_url();
module3.exports = [
"SIGABRT",
"SIGALRM",
"SIGHUP",
"SIGINT",
"SIGTERM"
];
if (process.platform !== "win32") {
module3.exports.push(
"SIGVTALRM",
"SIGXCPU",
"SIGXFSZ",
"SIGUSR2",
"SIGTRAP",
"SIGSYS",
"SIGQUIT",
"SIGIOT"
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
);
}
if (process.platform === "linux") {
module3.exports.push(
"SIGIO",
"SIGPOLL",
"SIGPWR",
"SIGSTKFLT",
"SIGUNUSED"
);
}
}
});
// ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js
var require_signal_exit = __commonJS({
"../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports2, module3) {
init_import_meta_url();
var process11 = global.process;
var processOk = /* @__PURE__ */ __name(function(process12) {
return process12 && typeof process12 === "object" && typeof process12.removeListener === "function" && typeof process12.emit === "function" && typeof process12.reallyExit === "function" && typeof process12.listeners === "function" && typeof process12.kill === "function" && typeof process12.pid === "number" && typeof process12.on === "function";
}, "processOk");
if (!processOk(process11)) {
module3.exports = function() {
return function() {
};
};
} else {
assert44 = require("assert");
signals = require_signals();
isWin = /^win/i.test(process11.platform);
EE = require("events");
if (typeof EE !== "function") {
EE = EE.EventEmitter;
}
if (process11.__signal_exit_emitter__) {
emitter = process11.__signal_exit_emitter__;
} else {
emitter = process11.__signal_exit_emitter__ = new EE();
emitter.count = 0;
emitter.emitted = {};
}
if (!emitter.infinite) {
emitter.setMaxListeners(Infinity);
emitter.infinite = true;
}
module3.exports = function(cb2, opts) {
if (!processOk(global.process)) {
return function() {
};
}
assert44.equal(typeof cb2, "function", "a callback must be provided for exit handler");
if (loaded === false) {
load();
}
var ev = "exit";
if (opts && opts.alwaysLast) {
ev = "afterexit";
}
var remove = /* @__PURE__ */ __name(function() {
emitter.removeListener(ev, cb2);
if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
unload();
}
}, "remove");
emitter.on(ev, cb2);
return remove;
};
unload = /* @__PURE__ */ __name(function unload2() {
if (!loaded || !processOk(global.process)) {
return;
}
loaded = false;
signals.forEach(function(sig) {
try {
process11.removeListener(sig, sigListeners[sig]);
} catch (er) {
}
});
process11.emit = originalProcessEmit;
process11.reallyExit = originalProcessReallyExit;
emitter.count -= 1;
}, "unload");
module3.exports.unload = unload;
emit = /* @__PURE__ */ __name(function emit2(event, code, signal) {
if (emitter.emitted[event]) {
return;
}
emitter.emitted[event] = true;
emitter.emit(event, code, signal);
}, "emit");
sigListeners = {};
signals.forEach(function(sig) {
sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
if (!processOk(global.process)) {
return;
}
var listeners = process11.listeners(sig);
if (listeners.length === emitter.count) {
unload();
emit("exit", null, sig);
emit("afterexit", null, sig);
if (isWin && sig === "SIGHUP") {
sig = "SIGINT";
}
process11.kill(process11.pid, sig);
}
}, "listener");
});
module3.exports.signals = function() {
return signals;
};
loaded = false;
load = /* @__PURE__ */ __name(function load2() {
if (loaded || !processOk(global.process)) {
return;
}
loaded = true;
emitter.count += 1;
signals = signals.filter(function(sig) {
try {
process11.on(sig, sigListeners[sig]);
return true;
} catch (er) {
return false;
}
});
process11.emit = processEmit;
process11.reallyExit = processReallyExit;
}, "load");
module3.exports.load = load;
originalProcessReallyExit = process11.reallyExit;
processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code) {
if (!processOk(global.process)) {
return;
}
process11.exitCode = code || /* istanbul ignore next */
0;
emit("exit", process11.exitCode, null);
emit("afterexit", process11.exitCode, null);
originalProcessReallyExit.call(process11, process11.exitCode);
}, "processReallyExit");
originalProcessEmit = process11.emit;
processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
if (ev === "exit" && processOk(global.process)) {
if (arg !== void 0) {
process11.exitCode = arg;
}
var ret = originalProcessEmit.apply(this, arguments);
emit("exit", process11.exitCode, null);
emit("afterexit", process11.exitCode, null);
return ret;
} else {
return originalProcessEmit.apply(this, arguments);
}
}, "processEmit");
}
var assert44;
var signals;
var isWin;
var EE;
var emitter;
var unload;
var emit;
var sigListeners;
var loaded;
var load;
var originalProcessReallyExit;
var processReallyExit;
var originalProcessEmit;
var processEmit;
}
});
// ../../node_modules/.pnpm/ansi-regex@6.0.1/node_modules/ansi-regex/index.js
function ansiRegex({ onlyFirst = false } = {}) {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
].join("|");
return new RegExp(pattern, onlyFirst ? void 0 : "g");
}
var init_ansi_regex = __esm({
"../../node_modules/.pnpm/ansi-regex@6.0.1/node_modules/ansi-regex/index.js"() {
init_import_meta_url();
__name(ansiRegex, "ansiRegex");
}
});
// ../../node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js
function stripAnsi2(string) {
if (typeof string !== "string") {
throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
}
return string.replace(regex, "");
}
var regex;
var init_strip_ansi = __esm({
"../../node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js"() {
init_import_meta_url();
init_ansi_regex();
regex = ansiRegex();
__name(stripAnsi2, "stripAnsi");
}
});
// src/utils/filesystem.ts
async function ensureDirectoryExists(filepath) {
const dirpath = import_path6.default.dirname(filepath);
await (0, import_promises.mkdir)(dirpath, { recursive: true });
}
function ensureDirectoryExistsSync(filepath) {
const dirpath = import_path6.default.dirname(filepath);
(0, import_fs7.mkdirSync)(dirpath, { recursive: true });
}
var import_fs7, import_promises, import_path6;
var init_filesystem = __esm({
"src/utils/filesystem.ts"() {
init_import_meta_url();
import_fs7 = require("fs");
import_promises = require("fs/promises");
import_path6 = __toESM(require("path"));
__name(ensureDirectoryExists, "ensureDirectoryExists");
__name(ensureDirectoryExistsSync, "ensureDirectoryExistsSync");
}
});
// src/utils/log-file.ts
function getDebugFilepath() {
const dir = getDebugFileDir();
const date = (/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-").replace(".", "_").replace("T", "_").replace("Z", "");
const filepath = dir.endsWith(".log") ? dir : import_node_path3.default.join(dir, `wrangler-${date}.log`);
return import_node_path3.default.resolve(filepath);
}
async function appendToDebugLogFile(messageLevel, message) {
const entry = `
--- ${(/* @__PURE__ */ new Date()).toISOString()} ${messageLevel}
${stripAnsi2(message)}
---
`;
if (!hasLoggedLocation) {
hasLoggedLocation = true;
logger.debug(`\u{1FAB5} Writing logs to "${debugLogFilepath}"`);
(0, import_signal_exit.default)(() => {
if (hasSeenErrorMessage) {
logger.console(
"warn",
`\u{1FAB5} Logs were written to "${debugLogFilepath}"`
);
}
});
}
if (!hasSeenErrorMessage) {
hasSeenErrorMessage = messageLevel === "error";
}
await mutex.runWith(async () => {
try {
await ensureDirectoryExists(debugLogFilepath);
await (0, import_promises2.appendFile)(debugLogFilepath, entry);
} catch (err) {
if (!hasLoggedError) {
hasLoggedError = true;
logger.error(`Failed to write to log file`, err);
logger.error(`Would have written:`, entry);
}
}
});
}
var import_promises2, import_node_path3, import_miniflare, import_signal_exit, getDebugFileDir, debugLogFilepath, mutex, hasLoggedLocation, hasLoggedError, hasSeenErrorMessage;
var init_log_file = __esm({
"src/utils/log-file.ts"() {
init_import_meta_url();
import_promises2 = require("fs/promises");
import_node_path3 = __toESM(require("path"));
import_miniflare = require("miniflare");
import_signal_exit = __toESM(require_signal_exit());
init_strip_ansi();
init_factory();
init_global_wrangler_config_path();
init_logger();
init_filesystem();
getDebugFileDir = getEnvironmentVariableFactory({
variableName: "WRANGLER_LOG_PATH",
defaultValue() {
const gobalWranglerConfigDir = getGlobalWranglerConfigPath();
return import_node_path3.default.join(gobalWranglerConfigDir, "logs");
}
});
__name(getDebugFilepath, "getDebugFilepath");
debugLogFilepath = getDebugFilepath();
mutex = new import_miniflare.Mutex();
hasLoggedLocation = false;
hasLoggedError = false;
hasSeenErrorMessage = false;
__name(appendToDebugLogFile, "appendToDebugLogFile");
}
});
// src/logger.ts
function getLoggerLevel() {
const fromEnv3 = getLogLevelFromEnv()?.toLowerCase();
if (fromEnv3 !== void 0) {
if (fromEnv3 in LOGGER_LEVELS) {
return fromEnv3;
}
const expected = Object.keys(LOGGER_LEVELS).map((level) => `"${level}"`).join(" | ");
logger.once.warn(
`Unrecognised WRANGLER_LOG value ${JSON.stringify(
fromEnv3
)}, expected ${expected}, defaulting to "log"...`
);
}
return "log";
}
function consoleMethodToLoggerLevel(method) {
if (method in LOGGER_LEVELS) {
return method;
}
return "log";
}
function logBuildWarnings(warnings) {
const logs = (0, import_esbuild.formatMessagesSync)(warnings, { kind: "warning", color: true });
for (const log2 of logs) {
logger.console("warn", log2);
}
}
function logBuildFailure(errors, warnings) {
if (errors.length > 0) {
const logs = (0, import_esbuild.formatMessagesSync)(errors, { kind: "error", color: true });
const errorStr = errors.length > 1 ? "errors" : "error";
logger.error(
`Build failed with ${errors.length} ${errorStr}:
` + logs.join("\n")
);
}
logBuildWarnings(warnings);
}
var import_node_async_hooks, import_node_util, import_cli_table3, import_esbuild, LOGGER_LEVELS, LOGGER_LEVEL_FORMAT_TYPE_MAP, getLogLevelFromEnv, overrideLoggerLevel, runWithLogLevel, Logger, logger;
var init_logger = __esm({
"src/logger.ts"() {
init_import_meta_url();
import_node_async_hooks = require("async_hooks");
import_node_util = require("util");
init_source();
import_cli_table3 = __toESM(require_cli_table3());
import_esbuild = require("esbuild");
init_factory();
init_misc_variables();
init_log_file();
LOGGER_LEVELS = {
none: -1,
error: 0,
warn: 1,
info: 2,
log: 3,
debug: 4
};
LOGGER_LEVEL_FORMAT_TYPE_MAP = {
error: "error",
warn: "warning",
info: void 0,
log: void 0,
debug: void 0
};
getLogLevelFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_LOG"
});
__name(getLoggerLevel, "getLoggerLevel");
overrideLoggerLevel = new import_node_async_hooks.AsyncLocalStorage();
runWithLogLevel = /* @__PURE__ */ __name((overrideLogLevel, cb2) => overrideLoggerLevel.run({ logLevel: overrideLogLevel }, cb2), "runWithLogLevel");
__name(consoleMethodToLoggerLevel, "consoleMethodToLoggerLevel");
Logger = class _Logger {
static {
__name(this, "Logger");
}
constructor() {
}
overrideLoggerLevel;
onceHistory = /* @__PURE__ */ new Set();
get loggerLevel() {
return overrideLoggerLevel.getStore()?.logLevel ?? this.overrideLoggerLevel ?? getLoggerLevel();
}
set loggerLevel(val2) {
this.overrideLoggerLevel = val2;
}
resetLoggerLevel() {
this.overrideLoggerLevel = void 0;
}
columns = process.stdout.columns;
json = /* @__PURE__ */ __name((data) => {
console.log(JSON.stringify(data, null, 4));
}, "json");
debug = /* @__PURE__ */ __name((...args) => this.doLog("debug", args), "debug");
debugWithSanitization = /* @__PURE__ */ __name((label, ...args) => {
if (getSanitizeLogs()) {
this.doLog("debug", [
label,
"omitted; set WRANGLER_LOG_SANITIZE=false to include sanitized data"
]);
} else {
this.doLog("debug", [label, ...args]);
}
}, "debugWithSanitization");
info = /* @__PURE__ */ __name((...args) => this.doLog("info", args), "info");
log = /* @__PURE__ */ __name((...args) => this.doLog("log", args), "log");
warn = /* @__PURE__ */ __name((...args) => this.doLog("warn", args), "warn");
error = /* @__PURE__ */ __name((...args) => this.doLog("error", args), "error");
table(data) {
const keys = data.length === 0 ? [] : Object.keys(data[0]);
const t7 = new import_cli_table3.default({
head: keys,
style: {
head: source_default.level ? ["blue"] : [],
border: source_default.level ? ["gray"] : []
}
});
t7.push(...data.map((row) => keys.map((k6) => row[k6])));
return this.doLog("log", [t7.toString()]);
}
console(method, ...args) {
if (typeof console[method] !== "function") {
throw new Error(`console.${method}() is not a function`);
}
if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[consoleMethodToLoggerLevel(method)]) {
_Logger.#beforeLogHook?.();
console[method].apply(console, args);
_Logger.#afterLogHook?.();
}
}
get once() {
return {
info: /* @__PURE__ */ __name((...args) => this.doLogOnce("info", args), "info"),
log: /* @__PURE__ */ __name((...args) => this.doLogOnce("log", args), "log"),
warn: /* @__PURE__ */ __name((...args) => this.doLogOnce("warn", args), "warn"),
error: /* @__PURE__ */ __name((...args) => this.doLogOnce("error", args), "error")
};
}
clearHistory() {
this.onceHistory.clear();
}
doLogOnce(messageLevel, args) {
const cacheKey = `${messageLevel}: ${args.join(" ")}`;
if (!this.onceHistory.has(cacheKey)) {
this.onceHistory.add(cacheKey);
this.doLog(messageLevel, args);
}
}
doLog(messageLevel, args) {
const message = this.formatMessage(messageLevel, (0, import_node_util.format)(...args));
const inUnitTests = typeof vitest !== "undefined";
if (!inUnitTests) {
void appendToDebugLogFile(messageLevel, message);
}
if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
_Logger.#beforeLogHook?.();
console[messageLevel](message);
_Logger.#afterLogHook?.();
}
}
static #beforeLogHook;
static registerBeforeLogHook(callback) {
this.#beforeLogHook = callback;
}
static #afterLogHook;
static registerAfterLogHook(callback) {
this.#afterLogHook = callback;
}
formatMessage(level, message) {
const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
if (kind) {
const [firstLine, ...otherLines] = message.split("\n");
const notes = otherLines.length > 0 ? otherLines.map((text) => ({ text })) : void 0;
return (0, import_esbuild.formatMessagesSync)([{ text: firstLine, notes }], {
color: true,
kind,
terminalWidth: this.columns
})[0];
} else {
return message;
}
}
};
logger = new Logger();
__name(logBuildWarnings, "logBuildWarnings");
__name(logBuildFailure, "logBuildFailure");
}
});
// src/parse.ts
function formatMessage({ text, notes, location, kind = "error" }, color = true) {
const input = { text, notes, location };
delete input.location?.fileText;
for (const note of notes ?? []) {
delete note.location?.fileText;
}
const lines = (0, import_esbuild2.formatMessagesSync)([input], {
color,
kind,
terminalWidth: logger.columns
});
return lines.join("\n");
}
function parseTOML(input, file) {
try {
const normalizedInput = input.replace(/\r\n/g, "\n");
return import_toml.default.parse(normalizedInput);
} catch (err) {
const { name: name2, message, line, col } = err;
if (name2 !== TOML_ERROR_NAME) {
throw err;
}
const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
const lineText = input.split("\n")[line];
const location = {
lineText,
line: line + 1,
column: col - 1,
file,
fileText: input
};
throw new ParseError({
text,
location,
telemetryMessage: "TOML parse error"
});
}
}
function parseJSON(input, file) {
return parseJSONC(input, file, {
allowEmptyContent: false,
allowTrailingComma: false,
disallowComments: true
});
}
function parseJSONC(input, file, options = { allowTrailingComma: true }) {
const errors = [];
const data = parse2(input, errors, options);
if (errors.length) {
throw new ParseError({
text: printParseErrorCode(errors[0].error),
location: {
...indexLocation({ file, fileText: input }, errors[0].offset + 1),
length: errors[0].length
},
telemetryMessage: "JSON(C) parse error"
});
}
return data;
}
function readFileSyncToBuffer(file) {
try {
return fs2.readFileSync(file);
} catch (err) {
const { message } = err;
throw new ParseError({
text: `Could not read file: ${file}`,
notes: [
{
text: message.replace(file, (0, import_node_path4.resolve)(file))
}
]
});
}
}
function readFileSync6(file) {
try {
const buffer = fs2.readFileSync(file);
return removeBOMAndValidate(buffer, file);
} catch (err) {
if (err instanceof ParseError) {
throw err;
}
const { message } = err;
throw new ParseError({
text: `Could not read file: ${file}`,
notes: [
{
text: message.replace(file, (0, import_node_path4.resolve)(file))
}
],
telemetryMessage: "Could not read file"
});
}
}
function indexLocation(file, index) {
let lineText, line = 0, column = 0, cursor = 0;
const { fileText = "" } = file;
for (const row of fileText.split("\n")) {
line++;
cursor += row.length + 1;
if (cursor >= index) {
lineText = row;
column = row.length - (cursor - index);
break;
}
}
return { lineText, line, column, ...file };
}
function parseHumanDuration(s5) {
const unitsMap = new Map(Object.entries(units));
s5 = s5.trim().toLowerCase();
let base = 1;
for (const [name2, _4] of unitsMap) {
if (s5.endsWith(name2)) {
s5 = s5.substring(0, s5.length - name2.length);
base = unitsMap.get(name2) || 1;
break;
}
}
return Number(s5) * base;
}
function parseNonHyphenedUuid(uuid) {
if (uuid == null || uuid.includes("-")) {
return uuid;
}
if (uuid.length != 32) {
return null;
}
const uuid_parts = [];
uuid_parts.push(uuid.slice(0, 8));
uuid_parts.push(uuid.slice(8, 12));
uuid_parts.push(uuid.slice(12, 16));
uuid_parts.push(uuid.slice(16, 20));
uuid_parts.push(uuid.slice(20));
let hyphenated = "";
uuid_parts.forEach((part) => hyphenated += part + "-");
return hyphenated.slice(0, 36);
}
function parseByteSize(s5, base = void 0) {
const match2 = s5.match(
/^(\d*\.*\d*)\s*([kKmMgGtTpP]{0,1})([i]{0,1}[bB]{0,1})$/
);
if (!match2) {
return NaN;
}
const size = match2[1];
if (size.length === 0 || isNaN(Number(size))) {
return NaN;
}
const unit = match2[2].toLowerCase();
const sizeUnits = {
k: 1,
m: 2,
g: 3,
t: 4,
p: 5
};
if (unit.length !== 0 && !(unit in sizeUnits)) {
return NaN;
}
const binary = match2[3].toLowerCase() == "ib";
if (binary && unit.length === 0) {
return NaN;
}
const pow = sizeUnits[unit] || 0;
return Math.floor(
Number(size) * Math.pow(base ?? (binary ? 1024 : 1e3), pow)
);
}
function removeBOMAndValidate(buffer, file) {
for (const bom of UNSUPPORTED_BOMS) {
if (buffer.length >= bom.buffer.length && buffer.subarray(0, bom.buffer.length).equals(bom.buffer)) {
throw new ParseError({
text: `Configuration file contains ${bom.encoding} byte order marker`,
notes: [
{
text: `The file "${file}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.`
}
],
location: { file, line: 1, column: 0 },
telemetryMessage: `${bom.encoding} BOM detected`
});
}
}
const content = buffer.toString("utf-8");
if (content.charCodeAt(0) === 65279) {
return content.slice(1);
}
return content;
}
var fs2, import_node_path4, import_toml, import_esbuild2, ParseError, APIError, TOML_ERROR_NAME, TOML_ERROR_SUFFIX, units, UNSUPPORTED_BOMS;
var init_parse = __esm({
"src/parse.ts"() {
init_import_meta_url();
fs2 = __toESM(require("fs"));
import_node_path4 = require("path");
import_toml = __toESM(require_toml());
import_esbuild2 = require("esbuild");
init_main();
init_errors();
init_logger();
__name(formatMessage, "formatMessage");
ParseError = class extends UserError {
static {
__name(this, "ParseError");
}
text;
notes;
location;
kind;
constructor({ text, notes, location, kind, telemetryMessage }) {
super(text, { telemetryMessage });
this.name = this.constructor.name;
this.text = text;
this.notes = notes ?? [];
this.location = location;
this.kind = kind ?? "error";
}
};
APIError = class extends ParseError {
static {
__name(this, "APIError");
}
#status;
code;
accountTag;
constructor({ status: status2, ...rest }) {
super(rest);
this.name = this.constructor.name;
this.#status = status2;
}
isGatewayError() {
if (this.#status !== void 0) {
return [524].includes(this.#status);
}
return false;
}
isRetryable() {
return String(this.#status).startsWith("5");
}
// Allow `APIError`s to be marked as handled.
#reportable = true;
get reportable() {
return this.#reportable;
}
preventReport() {
this.#reportable = false;
}
};
TOML_ERROR_NAME = "TomlError";
TOML_ERROR_SUFFIX = " at row ";
__name(parseTOML, "parseTOML");
__name(parseJSON, "parseJSON");
__name(parseJSONC, "parseJSONC");
__name(readFileSyncToBuffer, "readFileSyncToBuffer");
__name(readFileSync6, "readFileSync");
__name(indexLocation, "indexLocation");
units = {
nanoseconds: 1e-9,
nanosecond: 1e-9,
microseconds: 1e-6,
microsecond: 1e-6,
milliseconds: 1e-3,
millisecond: 1e-3,
seconds: 1,
second: 1,
minutes: 60,
minute: 60,
hours: 3600,
hour: 3600,
days: 86400,
day: 86400,
weeks: 604800,
week: 604800,
month: 18144e3,
year: 220752e3,
nsecs: 1e-9,
nsec: 1e-9,
usecs: 1e-6,
usec: 1e-6,
msecs: 1e-3,
msec: 1e-3,
secs: 1,
sec: 1,
mins: 60,
min: 60,
ns: 1e-9,
us: 1e-6,
ms: 1e-3,
mo: 18144e3,
yr: 220752e3,
s: 1,
m: 60,
h: 3600,
d: 86400,
w: 604800,
y: 220752e3
};
__name(parseHumanDuration, "parseHumanDuration");
__name(parseNonHyphenedUuid, "parseNonHyphenedUuid");
__name(parseByteSize, "parseByteSize");
UNSUPPORTED_BOMS = [
{
buffer: Buffer.from([0, 0, 254, 255]),
encoding: "UTF-32 BE"
},
{
buffer: Buffer.from([255, 254, 0, 0]),
encoding: "UTF-32 LE"
},
{
buffer: Buffer.from([254, 255]),
encoding: "UTF-16 BE"
},
{
buffer: Buffer.from([255, 254]),
encoding: "UTF-16 LE"
}
];
__name(removeBOMAndValidate, "removeBOMAndValidate");
}
});
// src/cfetch/errors.ts
function buildDetailedError(message, ...extra) {
return new ParseError({
text: message,
notes: extra.map((text) => ({ text }))
});
}
function maybeThrowFriendlyError(error2) {
if (error2.message === "workers.api.error.email_verification_required") {
throw buildDetailedError(
"Please verify your account's email address and try again.",
"Check your email for a verification link, or login to https://dash.cloudflare.com and request a new one."
);
}
}
var init_errors2 = __esm({
"src/cfetch/errors.ts"() {
init_import_meta_url();
init_parse();
__name(buildDetailedError, "buildDetailedError");
__name(maybeThrowFriendlyError, "maybeThrowFriendlyError");
}
});
// package.json
var name, version;
var init_package = __esm({
"package.json"() {
name = "wrangler";
version = "4.33.1";
}
});
// ../../node_modules/.pnpm/kleur@3.0.3/node_modules/kleur/index.js
var require_kleur = __commonJS({
"../../node_modules/.pnpm/kleur@3.0.3/node_modules/kleur/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env;
var $2 = {
enabled: !NODE_DISABLE_COLORS && TERM !== "dumb" && FORCE_COLOR !== "0",
// modifiers
reset: init3(0, 0),
bold: init3(1, 22),
dim: init3(2, 22),
italic: init3(3, 23),
underline: init3(4, 24),
inverse: init3(7, 27),
hidden: init3(8, 28),
strikethrough: init3(9, 29),
// colors
black: init3(30, 39),
red: init3(31, 39),
green: init3(32, 39),
yellow: init3(33, 39),
blue: init3(34, 39),
magenta: init3(35, 39),
cyan: init3(36, 39),
white: init3(37, 39),
gray: init3(90, 39),
grey: init3(90, 39),
// background colors
bgBlack: init3(40, 49),
bgRed: init3(41, 49),
bgGreen: init3(42, 49),
bgYellow: init3(43, 49),
bgBlue: init3(44, 49),
bgMagenta: init3(45, 49),
bgCyan: init3(46, 49),
bgWhite: init3(47, 49)
};
function run2(arr, str) {
let i5 = 0, tmp, beg = "", end = "";
for (; i5 < arr.length; i5++) {
tmp = arr[i5];
beg += tmp.open;
end += tmp.close;
if (str.includes(tmp.close)) {
str = str.replace(tmp.rgx, tmp.close + tmp.open);
}
}
return beg + str + end;
}
__name(run2, "run");
function chain2(has, keys) {
let ctx = { has, keys };
ctx.reset = $2.reset.bind(ctx);
ctx.bold = $2.bold.bind(ctx);
ctx.dim = $2.dim.bind(ctx);
ctx.italic = $2.italic.bind(ctx);
ctx.underline = $2.underline.bind(ctx);
ctx.inverse = $2.inverse.bind(ctx);
ctx.hidden = $2.hidden.bind(ctx);
ctx.strikethrough = $2.strikethrough.bind(ctx);
ctx.black = $2.black.bind(ctx);
ctx.red = $2.red.bind(ctx);
ctx.green = $2.green.bind(ctx);
ctx.yellow = $2.yellow.bind(ctx);
ctx.blue = $2.blue.bind(ctx);
ctx.magenta = $2.magenta.bind(ctx);
ctx.cyan = $2.cyan.bind(ctx);
ctx.white = $2.white.bind(ctx);
ctx.gray = $2.gray.bind(ctx);
ctx.grey = $2.grey.bind(ctx);
ctx.bgBlack = $2.bgBlack.bind(ctx);
ctx.bgRed = $2.bgRed.bind(ctx);
ctx.bgGreen = $2.bgGreen.bind(ctx);
ctx.bgYellow = $2.bgYellow.bind(ctx);
ctx.bgBlue = $2.bgBlue.bind(ctx);
ctx.bgMagenta = $2.bgMagenta.bind(ctx);
ctx.bgCyan = $2.bgCyan.bind(ctx);
ctx.bgWhite = $2.bgWhite.bind(ctx);
return ctx;
}
__name(chain2, "chain");
function init3(open4, close2) {
let blk = {
open: `\x1B[${open4}m`,
close: `\x1B[${close2}m`,
rgx: new RegExp(`\\x1b\\[${close2}m`, "g")
};
return function(txt) {
if (this !== void 0 && this.has !== void 0) {
this.has.includes(open4) || (this.has.push(open4), this.keys.push(blk));
return txt === void 0 ? this : $2.enabled ? run2(this.keys, txt + "") : txt + "";
}
return txt === void 0 ? chain2([open4], [blk]) : $2.enabled ? run2([blk], txt + "") : txt + "";
};
}
__name(init3, "init");
module3.exports = $2;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/action.js
var require_action = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/action.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (key, isSelect) => {
if (key.meta && key.name !== "escape") return;
if (key.ctrl) {
if (key.name === "a") return "first";
if (key.name === "c") return "abort";
if (key.name === "d") return "abort";
if (key.name === "e") return "last";
if (key.name === "g") return "reset";
}
if (isSelect) {
if (key.name === "j") return "down";
if (key.name === "k") return "up";
}
if (key.name === "return") return "submit";
if (key.name === "enter") return "submit";
if (key.name === "backspace") return "delete";
if (key.name === "delete") return "deleteForward";
if (key.name === "abort") return "abort";
if (key.name === "escape") return "exit";
if (key.name === "tab") return "next";
if (key.name === "pagedown") return "nextPage";
if (key.name === "pageup") return "prevPage";
if (key.name === "home") return "home";
if (key.name === "end") return "end";
if (key.name === "up") return "up";
if (key.name === "down") return "down";
if (key.name === "right") return "right";
if (key.name === "left") return "left";
return false;
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/strip.js
var require_strip = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/strip.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (str) => {
const pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|");
const RGX = new RegExp(pattern, "g");
return typeof str === "string" ? str.replace(RGX, "") : str;
};
}
});
// ../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
var require_src = __commonJS({
"../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var ESC2 = "\x1B";
var CSI = `${ESC2}[`;
var beep = "\x07";
var cursor = {
to(x6, y4) {
if (!y4) return `${CSI}${x6 + 1}G`;
return `${CSI}${y4 + 1};${x6 + 1}H`;
},
move(x6, y4) {
let ret = "";
if (x6 < 0) ret += `${CSI}${-x6}D`;
else if (x6 > 0) ret += `${CSI}${x6}C`;
if (y4 < 0) ret += `${CSI}${-y4}A`;
else if (y4 > 0) ret += `${CSI}${y4}B`;
return ret;
},
up: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}A`, "up"),
down: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}B`, "down"),
forward: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}C`, "forward"),
backward: /* @__PURE__ */ __name((count = 1) => `${CSI}${count}D`, "backward"),
nextLine: /* @__PURE__ */ __name((count = 1) => `${CSI}E`.repeat(count), "nextLine"),
prevLine: /* @__PURE__ */ __name((count = 1) => `${CSI}F`.repeat(count), "prevLine"),
left: `${CSI}G`,
hide: `${CSI}?25l`,
show: `${CSI}?25h`,
save: `${ESC2}7`,
restore: `${ESC2}8`
};
var scroll = {
up: /* @__PURE__ */ __name((count = 1) => `${CSI}S`.repeat(count), "up"),
down: /* @__PURE__ */ __name((count = 1) => `${CSI}T`.repeat(count), "down")
};
var erase = {
screen: `${CSI}2J`,
up: /* @__PURE__ */ __name((count = 1) => `${CSI}1J`.repeat(count), "up"),
down: /* @__PURE__ */ __name((count = 1) => `${CSI}J`.repeat(count), "down"),
line: `${CSI}2K`,
lineEnd: `${CSI}K`,
lineStart: `${CSI}1K`,
lines(count) {
let clear = "";
for (let i5 = 0; i5 < count; i5++)
clear += this.line + (i5 < count - 1 ? cursor.up() : "");
if (count)
clear += cursor.left;
return clear;
}
};
module3.exports = { cursor, scroll, erase, beep };
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/clear.js
var require_clear = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/clear.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function _createForOfIteratorHelper(o5, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o5[Symbol.iterator] || o5["@@iterator"];
if (!it) {
if (Array.isArray(o5) || (it = _unsupportedIterableToArray(o5)) || allowArrayLike && o5 && typeof o5.length === "number") {
if (it) o5 = it;
var i5 = 0;
var F3 = /* @__PURE__ */ __name(function F4() {
}, "F");
return { s: F3, n: /* @__PURE__ */ __name(function n6() {
if (i5 >= o5.length) return { done: true };
return { done: false, value: o5[i5++] };
}, "n"), e: /* @__PURE__ */ __name(function e7(_e2) {
throw _e2;
}, "e"), f: F3 };
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true, didErr = false, err;
return { s: /* @__PURE__ */ __name(function s5() {
it = it.call(o5);
}, "s"), n: /* @__PURE__ */ __name(function n6() {
var step = it.next();
normalCompletion = step.done;
return step;
}, "n"), e: /* @__PURE__ */ __name(function e7(_e2) {
didErr = true;
err = _e2;
}, "e"), f: /* @__PURE__ */ __name(function f6() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}, "f") };
}
__name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
function _unsupportedIterableToArray(o5, minLen) {
if (!o5) return;
if (typeof o5 === "string") return _arrayLikeToArray(o5, minLen);
var n6 = Object.prototype.toString.call(o5).slice(8, -1);
if (n6 === "Object" && o5.constructor) n6 = o5.constructor.name;
if (n6 === "Map" || n6 === "Set") return Array.from(o5);
if (n6 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n6)) return _arrayLikeToArray(o5, minLen);
}
__name(_unsupportedIterableToArray, "_unsupportedIterableToArray");
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i5 = 0, arr2 = new Array(len); i5 < len; i5++) arr2[i5] = arr[i5];
return arr2;
}
__name(_arrayLikeToArray, "_arrayLikeToArray");
var strip = require_strip();
var _require = require_src();
var erase = _require.erase;
var cursor = _require.cursor;
var width = /* @__PURE__ */ __name((str) => [...strip(str)].length, "width");
module3.exports = function(prompt2, perLine) {
if (!perLine) return erase.line + cursor.to(0);
let rows = 0;
const lines = prompt2.split(/\r?\n/);
var _iterator = _createForOfIteratorHelper(lines), _step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done; ) {
let line = _step.value;
rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return erase.lines(rows);
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/figures.js
var require_figures = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/figures.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var main2 = {
arrowUp: "\u2191",
arrowDown: "\u2193",
arrowLeft: "\u2190",
arrowRight: "\u2192",
radioOn: "\u25C9",
radioOff: "\u25EF",
tick: "\u2714",
cross: "\u2716",
ellipsis: "\u2026",
pointerSmall: "\u203A",
line: "\u2500",
pointer: "\u276F"
};
var win = {
arrowUp: main2.arrowUp,
arrowDown: main2.arrowDown,
arrowLeft: main2.arrowLeft,
arrowRight: main2.arrowRight,
radioOn: "(*)",
radioOff: "( )",
tick: "\u221A",
cross: "\xD7",
ellipsis: "...",
pointerSmall: "\xBB",
line: "\u2500",
pointer: ">"
};
var figures = process.platform === "win32" ? win : main2;
module3.exports = figures;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/style.js
var require_style = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/style.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var c6 = require_kleur();
var figures = require_figures();
var styles4 = Object.freeze({
password: {
scale: 1,
render: /* @__PURE__ */ __name((input) => "*".repeat(input.length), "render")
},
emoji: {
scale: 2,
render: /* @__PURE__ */ __name((input) => "\u{1F603}".repeat(input.length), "render")
},
invisible: {
scale: 0,
render: /* @__PURE__ */ __name((input) => "", "render")
},
default: {
scale: 1,
render: /* @__PURE__ */ __name((input) => `${input}`, "render")
}
});
var render2 = /* @__PURE__ */ __name((type) => styles4[type] || styles4.default, "render");
var symbols = Object.freeze({
aborted: c6.red(figures.cross),
done: c6.green(figures.tick),
exited: c6.yellow(figures.cross),
default: c6.cyan("?")
});
var symbol = /* @__PURE__ */ __name((done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default, "symbol");
var delimiter = /* @__PURE__ */ __name((completing) => c6.gray(completing ? figures.ellipsis : figures.pointerSmall), "delimiter");
var item = /* @__PURE__ */ __name((expandable, expanded) => c6.gray(expandable ? expanded ? figures.pointerSmall : "+" : figures.line), "item");
module3.exports = {
styles: styles4,
render: render2,
symbols,
symbol,
delimiter,
item
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/lines.js
var require_lines = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/lines.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var strip = require_strip();
module3.exports = function(msg, perLine) {
let lines = String(strip(msg) || "").split(/\r?\n/);
if (!perLine) return lines.length;
return lines.map((l6) => Math.ceil(l6.length / perLine)).reduce((a5, b6) => a5 + b6);
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/wrap.js
var require_wrap = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/wrap.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (msg, opts = {}) => {
const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(" ").join("") : opts.margin || "";
const width = opts.width;
return (msg || "").split(/\r?\n/g).map((line) => line.split(/\s+/g).reduce((arr, w6) => {
if (w6.length + tab.length >= width || arr[arr.length - 1].length + w6.length + 1 < width) arr[arr.length - 1] += ` ${w6}`;
else arr.push(`${tab}${w6}`);
return arr;
}, [tab]).join("\n")).join("\n");
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/entriesToDisplay.js
var require_entriesToDisplay = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/entriesToDisplay.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (cursor, total, maxVisible) => {
maxVisible = maxVisible || total;
let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2));
if (startIndex < 0) startIndex = 0;
let endIndex = Math.min(startIndex + maxVisible, total);
return {
startIndex,
endIndex
};
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/index.js
var require_util7 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/util/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
action: require_action(),
clear: require_clear(),
style: require_style(),
strip: require_strip(),
figures: require_figures(),
lines: require_lines(),
wrap: require_wrap(),
entriesToDisplay: require_entriesToDisplay()
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/prompt.js
var require_prompt = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/prompt.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var readline3 = require("readline");
var _require = require_util7();
var action = _require.action;
var EventEmitter5 = require("events");
var _require2 = require_src();
var beep = _require2.beep;
var cursor = _require2.cursor;
var color = require_kleur();
var Prompt = class extends EventEmitter5 {
static {
__name(this, "Prompt");
}
constructor(opts = {}) {
super();
this.firstRender = true;
this.in = opts.stdin || process.stdin;
this.out = opts.stdout || process.stdout;
this.onRender = (opts.onRender || (() => void 0)).bind(this);
const rl = readline3.createInterface({
input: this.in,
escapeCodeTimeout: 50
});
readline3.emitKeypressEvents(this.in, rl);
if (this.in.isTTY) this.in.setRawMode(true);
const isSelect = ["SelectPrompt", "MultiselectPrompt"].indexOf(this.constructor.name) > -1;
const keypress = /* @__PURE__ */ __name((str, key) => {
let a5 = action(key, isSelect);
if (a5 === false) {
this._ && this._(str, key);
} else if (typeof this[a5] === "function") {
this[a5](key);
} else {
this.bell();
}
}, "keypress");
this.close = () => {
this.out.write(cursor.show);
this.in.removeListener("keypress", keypress);
if (this.in.isTTY) this.in.setRawMode(false);
rl.close();
this.emit(this.aborted ? "abort" : this.exited ? "exit" : "submit", this.value);
this.closed = true;
};
this.in.on("keypress", keypress);
}
fire() {
this.emit("state", {
value: this.value,
aborted: !!this.aborted,
exited: !!this.exited
});
}
bell() {
this.out.write(beep);
}
render() {
this.onRender(color);
if (this.firstRender) this.firstRender = false;
}
};
module3.exports = Prompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/text.js
var require_text = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/text.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function asyncGeneratorStep(gen, resolve25, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error2) {
reject(error2);
return;
}
if (info.done) {
resolve25(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
__name(asyncGeneratorStep, "asyncGeneratorStep");
function _asyncToGenerator(fn2) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve25, reject) {
var gen = fn2.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "next", value);
}
__name(_next, "_next");
function _throw(err) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "throw", err);
}
__name(_throw, "_throw");
_next(void 0);
});
};
}
__name(_asyncToGenerator, "_asyncToGenerator");
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_src();
var erase = _require.erase;
var cursor = _require.cursor;
var _require2 = require_util7();
var style = _require2.style;
var clear = _require2.clear;
var lines = _require2.lines;
var figures = _require2.figures;
var TextPrompt = class extends Prompt {
static {
__name(this, "TextPrompt");
}
constructor(opts = {}) {
super(opts);
this.transform = style.render(opts.style);
this.scale = this.transform.scale;
this.msg = opts.message;
this.initial = opts.initial || ``;
this.validator = opts.validate || (() => true);
this.value = ``;
this.errorMsg = opts.error || `Please Enter A Valid Value`;
this.cursor = Number(!!this.initial);
this.cursorOffset = 0;
this.clear = clear(``, this.out.columns);
this.render();
}
set value(v7) {
if (!v7 && this.initial) {
this.placeholder = true;
this.rendered = color.gray(this.transform.render(this.initial));
} else {
this.placeholder = false;
this.rendered = this.transform.render(v7);
}
this._value = v7;
this.fire();
}
get value() {
return this._value;
}
reset() {
this.value = ``;
this.cursor = Number(!!this.initial);
this.cursorOffset = 0;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.value = this.value || this.initial;
this.done = this.aborted = true;
this.error = false;
this.red = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
validate() {
var _this = this;
return _asyncToGenerator(function* () {
let valid = yield _this.validator(_this.value);
if (typeof valid === `string`) {
_this.errorMsg = valid;
valid = false;
}
_this.error = !valid;
})();
}
submit() {
var _this2 = this;
return _asyncToGenerator(function* () {
_this2.value = _this2.value || _this2.initial;
_this2.cursorOffset = 0;
_this2.cursor = _this2.rendered.length;
yield _this2.validate();
if (_this2.error) {
_this2.red = true;
_this2.fire();
_this2.render();
return;
}
_this2.done = true;
_this2.aborted = false;
_this2.fire();
_this2.render();
_this2.out.write("\n");
_this2.close();
})();
}
next() {
if (!this.placeholder) return this.bell();
this.value = this.initial;
this.cursor = this.rendered.length;
this.fire();
this.render();
}
moveCursor(n6) {
if (this.placeholder) return;
this.cursor = this.cursor + n6;
this.cursorOffset += n6;
}
_(c6, key) {
let s1 = this.value.slice(0, this.cursor);
let s22 = this.value.slice(this.cursor);
this.value = `${s1}${c6}${s22}`;
this.red = false;
this.cursor = this.placeholder ? 0 : s1.length + 1;
this.render();
}
delete() {
if (this.isCursorAtStart()) return this.bell();
let s1 = this.value.slice(0, this.cursor - 1);
let s22 = this.value.slice(this.cursor);
this.value = `${s1}${s22}`;
this.red = false;
if (this.isCursorAtStart()) {
this.cursorOffset = 0;
} else {
this.cursorOffset++;
this.moveCursor(-1);
}
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
let s1 = this.value.slice(0, this.cursor);
let s22 = this.value.slice(this.cursor + 1);
this.value = `${s1}${s22}`;
this.red = false;
if (this.isCursorAtEnd()) {
this.cursorOffset = 0;
} else {
this.cursorOffset++;
}
this.render();
}
first() {
this.cursor = 0;
this.render();
}
last() {
this.cursor = this.value.length;
this.render();
}
left() {
if (this.cursor <= 0 || this.placeholder) return this.bell();
this.moveCursor(-1);
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
this.moveCursor(1);
this.render();
}
isCursorAtStart() {
return this.cursor === 0 || this.placeholder && this.cursor === 1;
}
isCursorAtEnd() {
return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1;
}
render() {
if (this.closed) return;
if (!this.firstRender) {
if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
this.out.write(clear(this.outputText, this.out.columns));
}
super.render();
this.outputError = "";
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `);
if (this.error) {
this.outputError += this.errorMsg.split(`
`).reduce((a5, l6, i5) => a5 + `
${i5 ? " " : figures.pointerSmall} ${color.red().italic(l6)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
}
};
module3.exports = TextPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/select.js
var require_select = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/select.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_util7();
var style = _require.style;
var clear = _require.clear;
var figures = _require.figures;
var wrap4 = _require.wrap;
var entriesToDisplay = _require.entriesToDisplay;
var _require2 = require_src();
var cursor = _require2.cursor;
var SelectPrompt = class extends Prompt {
static {
__name(this, "SelectPrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.hint = opts.hint || "- Use arrow-keys. Return to submit.";
this.warn = opts.warn || "- This option is disabled";
this.cursor = opts.initial || 0;
this.choices = opts.choices.map((ch2, idx) => {
if (typeof ch2 === "string") ch2 = {
title: ch2,
value: idx
};
return {
title: ch2 && (ch2.title || ch2.value || ch2),
value: ch2 && (ch2.value === void 0 ? idx : ch2.value),
description: ch2 && ch2.description,
selected: ch2 && ch2.selected,
disabled: ch2 && ch2.disabled
};
});
this.optionsPerPage = opts.optionsPerPage || 10;
this.value = (this.choices[this.cursor] || {}).value;
this.clear = clear("", this.out.columns);
this.render();
}
moveCursor(n6) {
this.cursor = n6;
this.value = this.choices[n6].value;
this.fire();
}
reset() {
this.moveCursor(0);
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
if (!this.selection.disabled) {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
} else this.bell();
}
first() {
this.moveCursor(0);
this.render();
}
last() {
this.moveCursor(this.choices.length - 1);
this.render();
}
up() {
if (this.cursor === 0) {
this.moveCursor(this.choices.length - 1);
} else {
this.moveCursor(this.cursor - 1);
}
this.render();
}
down() {
if (this.cursor === this.choices.length - 1) {
this.moveCursor(0);
} else {
this.moveCursor(this.cursor + 1);
}
this.render();
}
next() {
this.moveCursor((this.cursor + 1) % this.choices.length);
this.render();
}
_(c6, key) {
if (c6 === " ") return this.submit();
}
get selection() {
return this.choices[this.cursor];
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage), startIndex = _entriesToDisplay.startIndex, endIndex = _entriesToDisplay.endIndex;
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(" ");
if (!this.done) {
this.outputText += "\n";
for (let i5 = startIndex; i5 < endIndex; i5++) {
let title, prefix, desc = "", v7 = this.choices[i5];
if (i5 === startIndex && startIndex > 0) {
prefix = figures.arrowUp;
} else if (i5 === endIndex - 1 && endIndex < this.choices.length) {
prefix = figures.arrowDown;
} else {
prefix = " ";
}
if (v7.disabled) {
title = this.cursor === i5 ? color.gray().underline(v7.title) : color.strikethrough().gray(v7.title);
prefix = (this.cursor === i5 ? color.bold().gray(figures.pointer) + " " : " ") + prefix;
} else {
title = this.cursor === i5 ? color.cyan().underline(v7.title) : v7.title;
prefix = (this.cursor === i5 ? color.cyan(figures.pointer) + " " : " ") + prefix;
if (v7.description && this.cursor === i5) {
desc = ` - ${v7.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v7.description.split(/\r?\n/).length > 1) {
desc = "\n" + wrap4(v7.description, {
margin: 3,
width: this.out.columns
});
}
}
}
this.outputText += `${prefix} ${title}${color.gray(desc)}
`;
}
}
this.out.write(this.outputText);
}
};
module3.exports = SelectPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/toggle.js
var require_toggle = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/toggle.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_util7();
var style = _require.style;
var clear = _require.clear;
var _require2 = require_src();
var cursor = _require2.cursor;
var erase = _require2.erase;
var TogglePrompt = class extends Prompt {
static {
__name(this, "TogglePrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.value = !!opts.initial;
this.active = opts.active || "on";
this.inactive = opts.inactive || "off";
this.initialValue = this.value;
this.render();
}
reset() {
this.value = this.initialValue;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
deactivate() {
if (this.value === false) return this.bell();
this.value = false;
this.render();
}
activate() {
if (this.value === true) return this.bell();
this.value = true;
this.render();
}
delete() {
this.deactivate();
}
left() {
this.deactivate();
}
right() {
this.activate();
}
down() {
this.deactivate();
}
up() {
this.activate();
}
next() {
this.value = !this.value;
this.fire();
this.render();
}
_(c6, key) {
if (c6 === " ") {
this.value = !this.value;
} else if (c6 === "1") {
this.value = true;
} else if (c6 === "0") {
this.value = false;
} else return this.bell();
this.render();
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray("/"), this.value ? color.cyan().underline(this.active) : this.active].join(" ");
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = TogglePrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/datepart.js
var require_datepart = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/datepart.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = class _DatePart {
static {
__name(this, "DatePart");
}
constructor({
token,
date,
parts,
locales
}) {
this.token = token;
this.date = date || /* @__PURE__ */ new Date();
this.parts = parts || [this];
this.locales = locales || {};
}
up() {
}
down() {
}
next() {
const currentIdx = this.parts.indexOf(this);
return this.parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
}
setTo(val2) {
}
prev() {
let parts = [].concat(this.parts).reverse();
const currentIdx = parts.indexOf(this);
return parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
}
toString() {
return String(this.date);
}
};
module3.exports = DatePart;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/meridiem.js
var require_meridiem = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/meridiem.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Meridiem = class extends DatePart {
static {
__name(this, "Meridiem");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setHours((this.date.getHours() + 12) % 24);
}
down() {
this.up();
}
toString() {
let meridiem = this.date.getHours() > 12 ? "pm" : "am";
return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
}
};
module3.exports = Meridiem;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/day.js
var require_day = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/day.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var pos = /* @__PURE__ */ __name((n6) => {
n6 = n6 % 10;
return n6 === 1 ? "st" : n6 === 2 ? "nd" : n6 === 3 ? "rd" : "th";
}, "pos");
var Day = class extends DatePart {
static {
__name(this, "Day");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setDate(this.date.getDate() + 1);
}
down() {
this.date.setDate(this.date.getDate() - 1);
}
setTo(val2) {
this.date.setDate(parseInt(val2.substr(-2)));
}
toString() {
let date = this.date.getDate();
let day = this.date.getDay();
return this.token === "DD" ? String(date).padStart(2, "0") : this.token === "Do" ? date + pos(date) : this.token === "d" ? day + 1 : this.token === "ddd" ? this.locales.weekdaysShort[day] : this.token === "dddd" ? this.locales.weekdays[day] : date;
}
};
module3.exports = Day;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/hours.js
var require_hours = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/hours.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Hours = class extends DatePart {
static {
__name(this, "Hours");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setHours(this.date.getHours() + 1);
}
down() {
this.date.setHours(this.date.getHours() - 1);
}
setTo(val2) {
this.date.setHours(parseInt(val2.substr(-2)));
}
toString() {
let hours = this.date.getHours();
if (/h/.test(this.token)) hours = hours % 12 || 12;
return this.token.length > 1 ? String(hours).padStart(2, "0") : hours;
}
};
module3.exports = Hours;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/milliseconds.js
var require_milliseconds = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/milliseconds.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Milliseconds = class extends DatePart {
static {
__name(this, "Milliseconds");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMilliseconds(this.date.getMilliseconds() + 1);
}
down() {
this.date.setMilliseconds(this.date.getMilliseconds() - 1);
}
setTo(val2) {
this.date.setMilliseconds(parseInt(val2.substr(-this.token.length)));
}
toString() {
return String(this.date.getMilliseconds()).padStart(4, "0").substr(0, this.token.length);
}
};
module3.exports = Milliseconds;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/minutes.js
var require_minutes = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/minutes.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Minutes = class extends DatePart {
static {
__name(this, "Minutes");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMinutes(this.date.getMinutes() + 1);
}
down() {
this.date.setMinutes(this.date.getMinutes() - 1);
}
setTo(val2) {
this.date.setMinutes(parseInt(val2.substr(-2)));
}
toString() {
let m6 = this.date.getMinutes();
return this.token.length > 1 ? String(m6).padStart(2, "0") : m6;
}
};
module3.exports = Minutes;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/month.js
var require_month = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/month.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Month = class extends DatePart {
static {
__name(this, "Month");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMonth(this.date.getMonth() + 1);
}
down() {
this.date.setMonth(this.date.getMonth() - 1);
}
setTo(val2) {
val2 = parseInt(val2.substr(-2)) - 1;
this.date.setMonth(val2 < 0 ? 0 : val2);
}
toString() {
let month = this.date.getMonth();
let tl = this.token.length;
return tl === 2 ? String(month + 1).padStart(2, "0") : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1);
}
};
module3.exports = Month;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/seconds.js
var require_seconds = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/seconds.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Seconds = class extends DatePart {
static {
__name(this, "Seconds");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setSeconds(this.date.getSeconds() + 1);
}
down() {
this.date.setSeconds(this.date.getSeconds() - 1);
}
setTo(val2) {
this.date.setSeconds(parseInt(val2.substr(-2)));
}
toString() {
let s5 = this.date.getSeconds();
return this.token.length > 1 ? String(s5).padStart(2, "0") : s5;
}
};
module3.exports = Seconds;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/year.js
var require_year = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/year.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart();
var Year = class extends DatePart {
static {
__name(this, "Year");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setFullYear(this.date.getFullYear() + 1);
}
down() {
this.date.setFullYear(this.date.getFullYear() - 1);
}
setTo(val2) {
this.date.setFullYear(val2.substr(-4));
}
toString() {
let year = String(this.date.getFullYear()).padStart(4, "0");
return this.token.length === 2 ? year.substr(-2) : year;
}
};
module3.exports = Year;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/index.js
var require_dateparts = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/dateparts/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
DatePart: require_datepart(),
Meridiem: require_meridiem(),
Day: require_day(),
Hours: require_hours(),
Milliseconds: require_milliseconds(),
Minutes: require_minutes(),
Month: require_month(),
Seconds: require_seconds(),
Year: require_year()
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/date.js
var require_date2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/date.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function asyncGeneratorStep(gen, resolve25, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error2) {
reject(error2);
return;
}
if (info.done) {
resolve25(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
__name(asyncGeneratorStep, "asyncGeneratorStep");
function _asyncToGenerator(fn2) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve25, reject) {
var gen = fn2.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "next", value);
}
__name(_next, "_next");
function _throw(err) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "throw", err);
}
__name(_throw, "_throw");
_next(void 0);
});
};
}
__name(_asyncToGenerator, "_asyncToGenerator");
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_util7();
var style = _require.style;
var clear = _require.clear;
var figures = _require.figures;
var _require2 = require_src();
var erase = _require2.erase;
var cursor = _require2.cursor;
var _require3 = require_dateparts();
var DatePart = _require3.DatePart;
var Meridiem = _require3.Meridiem;
var Day = _require3.Day;
var Hours = _require3.Hours;
var Milliseconds = _require3.Milliseconds;
var Minutes = _require3.Minutes;
var Month = _require3.Month;
var Seconds = _require3.Seconds;
var Year = _require3.Year;
var regex2 = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
var regexGroups = {
1: ({
token
}) => token.replace(/\\(.)/g, "$1"),
2: (opts) => new Day(opts),
// Day // TODO
3: (opts) => new Month(opts),
// Month
4: (opts) => new Year(opts),
// Year
5: (opts) => new Meridiem(opts),
// AM/PM // TODO (special)
6: (opts) => new Hours(opts),
// Hours
7: (opts) => new Minutes(opts),
// Minutes
8: (opts) => new Seconds(opts),
// Seconds
9: (opts) => new Milliseconds(opts)
// Fractional seconds
};
var dfltLocales = {
months: "January,February,March,April,May,June,July,August,September,October,November,December".split(","),
monthsShort: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),
weekdays: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
weekdaysShort: "Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")
};
var DatePrompt = class extends Prompt {
static {
__name(this, "DatePrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.cursor = 0;
this.typed = "";
this.locales = Object.assign(dfltLocales, opts.locales);
this._date = opts.initial || /* @__PURE__ */ new Date();
this.errorMsg = opts.error || "Please Enter A Valid Value";
this.validator = opts.validate || (() => true);
this.mask = opts.mask || "YYYY-MM-DD HH:mm:ss";
this.clear = clear("", this.out.columns);
this.render();
}
get value() {
return this.date;
}
get date() {
return this._date;
}
set date(date) {
if (date) this._date.setTime(date.getTime());
}
set mask(mask) {
let result;
this.parts = [];
while (result = regex2.exec(mask)) {
let match2 = result.shift();
let idx = result.findIndex((gr) => gr != null);
this.parts.push(idx in regexGroups ? regexGroups[idx]({
token: result[idx] || match2,
date: this.date,
parts: this.parts,
locales: this.locales
}) : result[idx] || match2);
}
let parts = this.parts.reduce((arr, i5) => {
if (typeof i5 === "string" && typeof arr[arr.length - 1] === "string") arr[arr.length - 1] += i5;
else arr.push(i5);
return arr;
}, []);
this.parts.splice(0);
this.parts.push(...parts);
this.reset();
}
moveCursor(n6) {
this.typed = "";
this.cursor = n6;
this.fire();
}
reset() {
this.moveCursor(this.parts.findIndex((p6) => p6 instanceof DatePart));
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.error = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
validate() {
var _this = this;
return _asyncToGenerator(function* () {
let valid = yield _this.validator(_this.value);
if (typeof valid === "string") {
_this.errorMsg = valid;
valid = false;
}
_this.error = !valid;
})();
}
submit() {
var _this2 = this;
return _asyncToGenerator(function* () {
yield _this2.validate();
if (_this2.error) {
_this2.color = "red";
_this2.fire();
_this2.render();
return;
}
_this2.done = true;
_this2.aborted = false;
_this2.fire();
_this2.render();
_this2.out.write("\n");
_this2.close();
})();
}
up() {
this.typed = "";
this.parts[this.cursor].up();
this.render();
}
down() {
this.typed = "";
this.parts[this.cursor].down();
this.render();
}
left() {
let prev = this.parts[this.cursor].prev();
if (prev == null) return this.bell();
this.moveCursor(this.parts.indexOf(prev));
this.render();
}
right() {
let next = this.parts[this.cursor].next();
if (next == null) return this.bell();
this.moveCursor(this.parts.indexOf(next));
this.render();
}
next() {
let next = this.parts[this.cursor].next();
this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex((part) => part instanceof DatePart));
this.render();
}
_(c6) {
if (/\d/.test(c6)) {
this.typed += c6;
this.parts[this.cursor].setTo(this.typed);
this.render();
}
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p6, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p6.toString()) : p6), []).join("")].join(" ");
if (this.error) {
this.outputText += this.errorMsg.split("\n").reduce((a5, l6, i5) => a5 + `
${i5 ? ` ` : figures.pointerSmall} ${color.red().italic(l6)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = DatePrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/number.js
var require_number = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/number.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function asyncGeneratorStep(gen, resolve25, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error2) {
reject(error2);
return;
}
if (info.done) {
resolve25(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
__name(asyncGeneratorStep, "asyncGeneratorStep");
function _asyncToGenerator(fn2) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve25, reject) {
var gen = fn2.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "next", value);
}
__name(_next, "_next");
function _throw(err) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "throw", err);
}
__name(_throw, "_throw");
_next(void 0);
});
};
}
__name(_asyncToGenerator, "_asyncToGenerator");
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_src();
var cursor = _require.cursor;
var erase = _require.erase;
var _require2 = require_util7();
var style = _require2.style;
var figures = _require2.figures;
var clear = _require2.clear;
var lines = _require2.lines;
var isNumber = /[0-9]/;
var isDef = /* @__PURE__ */ __name((any) => any !== void 0, "isDef");
var round = /* @__PURE__ */ __name((number, precision) => {
let factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}, "round");
var NumberPrompt = class extends Prompt {
static {
__name(this, "NumberPrompt");
}
constructor(opts = {}) {
super(opts);
this.transform = style.render(opts.style);
this.msg = opts.message;
this.initial = isDef(opts.initial) ? opts.initial : "";
this.float = !!opts.float;
this.round = opts.round || 2;
this.inc = opts.increment || 1;
this.min = isDef(opts.min) ? opts.min : -Infinity;
this.max = isDef(opts.max) ? opts.max : Infinity;
this.errorMsg = opts.error || `Please Enter A Valid Value`;
this.validator = opts.validate || (() => true);
this.color = `cyan`;
this.value = ``;
this.typed = ``;
this.lastHit = 0;
this.render();
}
set value(v7) {
if (!v7 && v7 !== 0) {
this.placeholder = true;
this.rendered = color.gray(this.transform.render(`${this.initial}`));
this._value = ``;
} else {
this.placeholder = false;
this.rendered = this.transform.render(`${round(v7, this.round)}`);
this._value = round(v7, this.round);
}
this.fire();
}
get value() {
return this._value;
}
parse(x6) {
return this.float ? parseFloat(x6) : parseInt(x6);
}
valid(c6) {
return c6 === `-` || c6 === `.` && this.float || isNumber.test(c6);
}
reset() {
this.typed = ``;
this.value = ``;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
let x6 = this.value;
this.value = x6 !== `` ? x6 : this.initial;
this.done = this.aborted = true;
this.error = false;
this.fire();
this.render();
this.out.write(`
`);
this.close();
}
validate() {
var _this = this;
return _asyncToGenerator(function* () {
let valid = yield _this.validator(_this.value);
if (typeof valid === `string`) {
_this.errorMsg = valid;
valid = false;
}
_this.error = !valid;
})();
}
submit() {
var _this2 = this;
return _asyncToGenerator(function* () {
yield _this2.validate();
if (_this2.error) {
_this2.color = `red`;
_this2.fire();
_this2.render();
return;
}
let x6 = _this2.value;
_this2.value = x6 !== `` ? x6 : _this2.initial;
_this2.done = true;
_this2.aborted = false;
_this2.error = false;
_this2.fire();
_this2.render();
_this2.out.write(`
`);
_this2.close();
})();
}
up() {
this.typed = ``;
if (this.value === "") {
this.value = this.min - this.inc;
}
if (this.value >= this.max) return this.bell();
this.value += this.inc;
this.color = `cyan`;
this.fire();
this.render();
}
down() {
this.typed = ``;
if (this.value === "") {
this.value = this.min + this.inc;
}
if (this.value <= this.min) return this.bell();
this.value -= this.inc;
this.color = `cyan`;
this.fire();
this.render();
}
delete() {
let val2 = this.value.toString();
if (val2.length === 0) return this.bell();
this.value = this.parse(val2 = val2.slice(0, -1)) || ``;
if (this.value !== "" && this.value < this.min) {
this.value = this.min;
}
this.color = `cyan`;
this.fire();
this.render();
}
next() {
this.value = this.initial;
this.fire();
this.render();
}
_(c6, key) {
if (!this.valid(c6)) return this.bell();
const now = Date.now();
if (now - this.lastHit > 1e3) this.typed = ``;
this.typed += c6;
this.lastHit = now;
this.color = `cyan`;
if (c6 === `.`) return this.fire();
this.value = Math.min(this.parse(this.typed), this.max);
if (this.value > this.max) this.value = this.max;
if (this.value < this.min) this.value = this.min;
this.fire();
this.render();
}
render() {
if (this.closed) return;
if (!this.firstRender) {
if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
this.out.write(clear(this.outputText, this.out.columns));
}
super.render();
this.outputError = "";
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `);
if (this.error) {
this.outputError += this.errorMsg.split(`
`).reduce((a5, l6, i5) => a5 + `
${i5 ? ` ` : figures.pointerSmall} ${color.red().italic(l6)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
}
};
module3.exports = NumberPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/multiselect.js
var require_multiselect = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/multiselect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var _require = require_src();
var cursor = _require.cursor;
var Prompt = require_prompt();
var _require2 = require_util7();
var clear = _require2.clear;
var figures = _require2.figures;
var style = _require2.style;
var wrap4 = _require2.wrap;
var entriesToDisplay = _require2.entriesToDisplay;
var MultiselectPrompt = class extends Prompt {
static {
__name(this, "MultiselectPrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.cursor = opts.cursor || 0;
this.scrollIndex = opts.cursor || 0;
this.hint = opts.hint || "";
this.warn = opts.warn || "- This option is disabled -";
this.minSelected = opts.min;
this.showMinError = false;
this.maxChoices = opts.max;
this.instructions = opts.instructions;
this.optionsPerPage = opts.optionsPerPage || 10;
this.value = opts.choices.map((ch2, idx) => {
if (typeof ch2 === "string") ch2 = {
title: ch2,
value: idx
};
return {
title: ch2 && (ch2.title || ch2.value || ch2),
description: ch2 && ch2.description,
value: ch2 && (ch2.value === void 0 ? idx : ch2.value),
selected: ch2 && ch2.selected,
disabled: ch2 && ch2.disabled
};
});
this.clear = clear("", this.out.columns);
if (!opts.overrideRender) {
this.render();
}
}
reset() {
this.value.map((v7) => !v7.selected);
this.cursor = 0;
this.fire();
this.render();
}
selected() {
return this.value.filter((v7) => v7.selected);
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
const selected = this.value.filter((e7) => e7.selected);
if (this.minSelected && selected.length < this.minSelected) {
this.showMinError = true;
this.render();
} else {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
}
first() {
this.cursor = 0;
this.render();
}
last() {
this.cursor = this.value.length - 1;
this.render();
}
next() {
this.cursor = (this.cursor + 1) % this.value.length;
this.render();
}
up() {
if (this.cursor === 0) {
this.cursor = this.value.length - 1;
} else {
this.cursor--;
}
this.render();
}
down() {
if (this.cursor === this.value.length - 1) {
this.cursor = 0;
} else {
this.cursor++;
}
this.render();
}
left() {
this.value[this.cursor].selected = false;
this.render();
}
right() {
if (this.value.filter((e7) => e7.selected).length >= this.maxChoices) return this.bell();
this.value[this.cursor].selected = true;
this.render();
}
handleSpaceToggle() {
const v7 = this.value[this.cursor];
if (v7.selected) {
v7.selected = false;
this.render();
} else if (v7.disabled || this.value.filter((e7) => e7.selected).length >= this.maxChoices) {
return this.bell();
} else {
v7.selected = true;
this.render();
}
}
toggleAll() {
if (this.maxChoices !== void 0 || this.value[this.cursor].disabled) {
return this.bell();
}
const newSelected = !this.value[this.cursor].selected;
this.value.filter((v7) => !v7.disabled).forEach((v7) => v7.selected = newSelected);
this.render();
}
_(c6, key) {
if (c6 === " ") {
this.handleSpaceToggle();
} else if (c6 === "a") {
this.toggleAll();
} else {
return this.bell();
}
}
renderInstructions() {
if (this.instructions === void 0 || this.instructions) {
if (typeof this.instructions === "string") {
return this.instructions;
}
return `
Instructions:
${figures.arrowUp}/${figures.arrowDown}: Highlight option
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
` + (this.maxChoices === void 0 ? ` a: Toggle all
` : "") + ` enter/return: Complete answer`;
}
return "";
}
renderOption(cursor2, v7, i5, arrowIndicator) {
const prefix = (v7.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + arrowIndicator + " ";
let title, desc;
if (v7.disabled) {
title = cursor2 === i5 ? color.gray().underline(v7.title) : color.strikethrough().gray(v7.title);
} else {
title = cursor2 === i5 ? color.cyan().underline(v7.title) : v7.title;
if (cursor2 === i5 && v7.description) {
desc = ` - ${v7.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v7.description.split(/\r?\n/).length > 1) {
desc = "\n" + wrap4(v7.description, {
margin: prefix.length,
width: this.out.columns
});
}
}
}
return prefix + title + color.gray(desc || "");
}
// shared with autocompleteMultiselect
paginateOptions(options) {
if (options.length === 0) {
return color.red("No matches for this query.");
}
let _entriesToDisplay = entriesToDisplay(this.cursor, options.length, this.optionsPerPage), startIndex = _entriesToDisplay.startIndex, endIndex = _entriesToDisplay.endIndex;
let prefix, styledOptions = [];
for (let i5 = startIndex; i5 < endIndex; i5++) {
if (i5 === startIndex && startIndex > 0) {
prefix = figures.arrowUp;
} else if (i5 === endIndex - 1 && endIndex < options.length) {
prefix = figures.arrowDown;
} else {
prefix = " ";
}
styledOptions.push(this.renderOption(this.cursor, options[i5], i5, prefix));
}
return "\n" + styledOptions.join("\n");
}
// shared with autocomleteMultiselect
renderOptions(options) {
if (!this.done) {
return this.paginateOptions(options);
}
return "";
}
renderDoneOrInstructions() {
if (this.done) {
return this.value.filter((e7) => e7.selected).map((v7) => v7.title).join(", ");
}
const output = [color.gray(this.hint), this.renderInstructions()];
if (this.value[this.cursor].disabled) {
output.push(color.yellow(this.warn));
}
return output.join(" ");
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
super.render();
let prompt2 = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(" ");
if (this.showMinError) {
prompt2 += color.red(`You must select a minimum of ${this.minSelected} choices.`);
this.showMinError = false;
}
prompt2 += this.renderOptions(this.value);
this.out.write(this.clear + prompt2);
this.clear = clear(prompt2, this.out.columns);
}
};
module3.exports = MultiselectPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/autocomplete.js
var require_autocomplete = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/autocomplete.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function asyncGeneratorStep(gen, resolve25, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error2) {
reject(error2);
return;
}
if (info.done) {
resolve25(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
__name(asyncGeneratorStep, "asyncGeneratorStep");
function _asyncToGenerator(fn2) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve25, reject) {
var gen = fn2.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "next", value);
}
__name(_next, "_next");
function _throw(err) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "throw", err);
}
__name(_throw, "_throw");
_next(void 0);
});
};
}
__name(_asyncToGenerator, "_asyncToGenerator");
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_src();
var erase = _require.erase;
var cursor = _require.cursor;
var _require2 = require_util7();
var style = _require2.style;
var clear = _require2.clear;
var figures = _require2.figures;
var wrap4 = _require2.wrap;
var entriesToDisplay = _require2.entriesToDisplay;
var getVal = /* @__PURE__ */ __name((arr, i5) => arr[i5] && (arr[i5].value || arr[i5].title || arr[i5]), "getVal");
var getTitle = /* @__PURE__ */ __name((arr, i5) => arr[i5] && (arr[i5].title || arr[i5].value || arr[i5]), "getTitle");
var getIndex2 = /* @__PURE__ */ __name((arr, valOrTitle) => {
const index = arr.findIndex((el) => el.value === valOrTitle || el.title === valOrTitle);
return index > -1 ? index : void 0;
}, "getIndex");
var AutocompletePrompt = class extends Prompt {
static {
__name(this, "AutocompletePrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.suggest = opts.suggest;
this.choices = opts.choices;
this.initial = typeof opts.initial === "number" ? opts.initial : getIndex2(opts.choices, opts.initial);
this.select = this.initial || opts.cursor || 0;
this.i18n = {
noMatches: opts.noMatches || "no matches found"
};
this.fallback = opts.fallback || this.initial;
this.clearFirst = opts.clearFirst || false;
this.suggestions = [];
this.input = "";
this.limit = opts.limit || 10;
this.cursor = 0;
this.transform = style.render(opts.style);
this.scale = this.transform.scale;
this.render = this.render.bind(this);
this.complete = this.complete.bind(this);
this.clear = clear("", this.out.columns);
this.complete(this.render);
this.render();
}
set fallback(fb) {
this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
}
get fallback() {
let choice;
if (typeof this._fb === "number") choice = this.choices[this._fb];
else if (typeof this._fb === "string") choice = {
title: this._fb
};
return choice || this._fb || {
title: this.i18n.noMatches
};
}
moveSelect(i5) {
this.select = i5;
if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i5);
else this.value = this.fallback.value;
this.fire();
}
complete(cb2) {
var _this = this;
return _asyncToGenerator(function* () {
const p6 = _this.completing = _this.suggest(_this.input, _this.choices);
const suggestions = yield p6;
if (_this.completing !== p6) return;
_this.suggestions = suggestions.map((s5, i5, arr) => ({
title: getTitle(arr, i5),
value: getVal(arr, i5),
description: s5.description
}));
_this.completing = false;
const l6 = Math.max(suggestions.length - 1, 0);
_this.moveSelect(Math.min(l6, _this.select));
cb2 && cb2();
})();
}
reset() {
this.input = "";
this.complete(() => {
this.moveSelect(this.initial !== void 0 ? this.initial : 0);
this.render();
});
this.render();
}
exit() {
if (this.clearFirst && this.input.length > 0) {
this.reset();
} else {
this.done = this.exited = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
}
abort() {
this.done = this.aborted = true;
this.exited = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
this.done = true;
this.aborted = this.exited = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
_(c6, key) {
let s1 = this.input.slice(0, this.cursor);
let s22 = this.input.slice(this.cursor);
this.input = `${s1}${c6}${s22}`;
this.cursor = s1.length + 1;
this.complete(this.render);
this.render();
}
delete() {
if (this.cursor === 0) return this.bell();
let s1 = this.input.slice(0, this.cursor - 1);
let s22 = this.input.slice(this.cursor);
this.input = `${s1}${s22}`;
this.complete(this.render);
this.cursor = this.cursor - 1;
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
let s1 = this.input.slice(0, this.cursor);
let s22 = this.input.slice(this.cursor + 1);
this.input = `${s1}${s22}`;
this.complete(this.render);
this.render();
}
first() {
this.moveSelect(0);
this.render();
}
last() {
this.moveSelect(this.suggestions.length - 1);
this.render();
}
up() {
if (this.select === 0) {
this.moveSelect(this.suggestions.length - 1);
} else {
this.moveSelect(this.select - 1);
}
this.render();
}
down() {
if (this.select === this.suggestions.length - 1) {
this.moveSelect(0);
} else {
this.moveSelect(this.select + 1);
}
this.render();
}
next() {
if (this.select === this.suggestions.length - 1) {
this.moveSelect(0);
} else this.moveSelect(this.select + 1);
this.render();
}
nextPage() {
this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
this.render();
}
prevPage() {
this.moveSelect(Math.max(this.select - this.limit, 0));
this.render();
}
left() {
if (this.cursor <= 0) return this.bell();
this.cursor = this.cursor - 1;
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
this.cursor = this.cursor + 1;
this.render();
}
renderOption(v7, hovered, isStart, isEnd) {
let desc;
let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : " ";
let title = hovered ? color.cyan().underline(v7.title) : v7.title;
prefix = (hovered ? color.cyan(figures.pointer) + " " : " ") + prefix;
if (v7.description) {
desc = ` - ${v7.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v7.description.split(/\r?\n/).length > 1) {
desc = "\n" + wrap4(v7.description, {
margin: 3,
width: this.out.columns
});
}
}
return prefix + " " + title + color.gray(desc || "");
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
let _entriesToDisplay = entriesToDisplay(this.select, this.choices.length, this.limit), startIndex = _entriesToDisplay.startIndex, endIndex = _entriesToDisplay.endIndex;
this.outputText = [style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(" ");
if (!this.done) {
const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i5) => this.renderOption(item, this.select === i5 + startIndex, i5 === 0 && startIndex > 0, i5 + startIndex === endIndex - 1 && endIndex < this.choices.length)).join("\n");
this.outputText += `
` + (suggestions || color.gray(this.fallback.title));
}
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = AutocompletePrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/autocompleteMultiselect.js
var require_autocompleteMultiselect = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/autocompleteMultiselect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var _require = require_src();
var cursor = _require.cursor;
var MultiselectPrompt = require_multiselect();
var _require2 = require_util7();
var clear = _require2.clear;
var style = _require2.style;
var figures = _require2.figures;
var AutocompleteMultiselectPrompt = class extends MultiselectPrompt {
static {
__name(this, "AutocompleteMultiselectPrompt");
}
constructor(opts = {}) {
opts.overrideRender = true;
super(opts);
this.inputValue = "";
this.clear = clear("", this.out.columns);
this.filteredOptions = this.value;
this.render();
}
last() {
this.cursor = this.filteredOptions.length - 1;
this.render();
}
next() {
this.cursor = (this.cursor + 1) % this.filteredOptions.length;
this.render();
}
up() {
if (this.cursor === 0) {
this.cursor = this.filteredOptions.length - 1;
} else {
this.cursor--;
}
this.render();
}
down() {
if (this.cursor === this.filteredOptions.length - 1) {
this.cursor = 0;
} else {
this.cursor++;
}
this.render();
}
left() {
this.filteredOptions[this.cursor].selected = false;
this.render();
}
right() {
if (this.value.filter((e7) => e7.selected).length >= this.maxChoices) return this.bell();
this.filteredOptions[this.cursor].selected = true;
this.render();
}
delete() {
if (this.inputValue.length) {
this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1);
this.updateFilteredOptions();
}
}
updateFilteredOptions() {
const currentHighlight = this.filteredOptions[this.cursor];
this.filteredOptions = this.value.filter((v7) => {
if (this.inputValue) {
if (typeof v7.title === "string") {
if (v7.title.toLowerCase().includes(this.inputValue.toLowerCase())) {
return true;
}
}
if (typeof v7.value === "string") {
if (v7.value.toLowerCase().includes(this.inputValue.toLowerCase())) {
return true;
}
}
return false;
}
return true;
});
const newHighlightIndex = this.filteredOptions.findIndex((v7) => v7 === currentHighlight);
this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex;
this.render();
}
handleSpaceToggle() {
const v7 = this.filteredOptions[this.cursor];
if (v7.selected) {
v7.selected = false;
this.render();
} else if (v7.disabled || this.value.filter((e7) => e7.selected).length >= this.maxChoices) {
return this.bell();
} else {
v7.selected = true;
this.render();
}
}
handleInputChange(c6) {
this.inputValue = this.inputValue + c6;
this.updateFilteredOptions();
}
_(c6, key) {
if (c6 === " ") {
this.handleSpaceToggle();
} else {
this.handleInputChange(c6);
}
}
renderInstructions() {
if (this.instructions === void 0 || this.instructions) {
if (typeof this.instructions === "string") {
return this.instructions;
}
return `
Instructions:
${figures.arrowUp}/${figures.arrowDown}: Highlight option
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
[a,b,c]/delete: Filter choices
enter/return: Complete answer
`;
}
return "";
}
renderCurrentInput() {
return `
Filtered results for: ${this.inputValue ? this.inputValue : color.gray("Enter something to filter")}
`;
}
renderOption(cursor2, v7, i5) {
let title;
if (v7.disabled) title = cursor2 === i5 ? color.gray().underline(v7.title) : color.strikethrough().gray(v7.title);
else title = cursor2 === i5 ? color.cyan().underline(v7.title) : v7.title;
return (v7.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + title;
}
renderDoneOrInstructions() {
if (this.done) {
return this.value.filter((e7) => e7.selected).map((v7) => v7.title).join(", ");
}
const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()];
if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) {
output.push(color.yellow(this.warn));
}
return output.join(" ");
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
super.render();
let prompt2 = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(" ");
if (this.showMinError) {
prompt2 += color.red(`You must select a minimum of ${this.minSelected} choices.`);
this.showMinError = false;
}
prompt2 += this.renderOptions(this.filteredOptions);
this.out.write(this.clear + prompt2);
this.clear = clear(prompt2, this.out.columns);
}
};
module3.exports = AutocompleteMultiselectPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/confirm.js
var require_confirm = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/confirm.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt();
var _require = require_util7();
var style = _require.style;
var clear = _require.clear;
var _require2 = require_src();
var erase = _require2.erase;
var cursor = _require2.cursor;
var ConfirmPrompt = class extends Prompt {
static {
__name(this, "ConfirmPrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.value = opts.initial;
this.initialValue = !!opts.initial;
this.yesMsg = opts.yes || "yes";
this.yesOption = opts.yesOption || "(Y/n)";
this.noMsg = opts.no || "no";
this.noOption = opts.noOption || "(y/N)";
this.render();
}
reset() {
this.value = this.initialValue;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
this.value = this.value || false;
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
_(c6, key) {
if (c6.toLowerCase() === "y") {
this.value = true;
return this.submit();
}
if (c6.toLowerCase() === "n") {
this.value = false;
return this.submit();
}
return this.bell();
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(" ");
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = ConfirmPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/index.js
var require_elements = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/elements/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
TextPrompt: require_text(),
SelectPrompt: require_select(),
TogglePrompt: require_toggle(),
DatePrompt: require_date2(),
NumberPrompt: require_number(),
MultiselectPrompt: require_multiselect(),
AutocompletePrompt: require_autocomplete(),
AutocompleteMultiselectPrompt: require_autocompleteMultiselect(),
ConfirmPrompt: require_confirm()
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/prompts.js
var require_prompts = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/prompts.js"(exports2) {
"use strict";
init_import_meta_url();
var $2 = exports2;
var el = require_elements();
var noop = /* @__PURE__ */ __name((v7) => v7, "noop");
function toPrompt(type, args, opts = {}) {
return new Promise((res, rej) => {
const p6 = new el[type](args);
const onAbort = opts.onAbort || noop;
const onSubmit = opts.onSubmit || noop;
const onExit6 = opts.onExit || noop;
p6.on("state", args.onState || noop);
p6.on("submit", (x6) => res(onSubmit(x6)));
p6.on("exit", (x6) => res(onExit6(x6)));
p6.on("abort", (x6) => rej(onAbort(x6)));
});
}
__name(toPrompt, "toPrompt");
$2.text = (args) => toPrompt("TextPrompt", args);
$2.password = (args) => {
args.style = "password";
return $2.text(args);
};
$2.invisible = (args) => {
args.style = "invisible";
return $2.text(args);
};
$2.number = (args) => toPrompt("NumberPrompt", args);
$2.date = (args) => toPrompt("DatePrompt", args);
$2.confirm = (args) => toPrompt("ConfirmPrompt", args);
$2.list = (args) => {
const sep5 = args.separator || ",";
return toPrompt("TextPrompt", args, {
onSubmit: /* @__PURE__ */ __name((str) => str.split(sep5).map((s5) => s5.trim()), "onSubmit")
});
};
$2.toggle = (args) => toPrompt("TogglePrompt", args);
$2.select = (args) => toPrompt("SelectPrompt", args);
$2.multiselect = (args) => {
args.choices = [].concat(args.choices || []);
const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
return toPrompt("MultiselectPrompt", args, {
onAbort: toSelected,
onSubmit: toSelected
});
};
$2.autocompleteMultiselect = (args) => {
args.choices = [].concat(args.choices || []);
const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
return toPrompt("AutocompleteMultiselectPrompt", args, {
onAbort: toSelected,
onSubmit: toSelected
});
};
var byTitle = /* @__PURE__ */ __name((input, choices) => Promise.resolve(choices.filter((item) => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())), "byTitle");
$2.autocomplete = (args) => {
args.suggest = args.suggest || byTitle;
args.choices = [].concat(args.choices || []);
return toPrompt("AutocompletePrompt", args);
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/index.js
var require_dist2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/dist/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
__name(ownKeys, "ownKeys");
function _objectSpread(target) {
for (var i5 = 1; i5 < arguments.length; i5++) {
var source = arguments[i5] != null ? arguments[i5] : {};
if (i5 % 2) {
ownKeys(Object(source), true).forEach(function(key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
__name(_objectSpread, "_objectSpread");
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
} else {
obj[key] = value;
}
return obj;
}
__name(_defineProperty, "_defineProperty");
function _createForOfIteratorHelper(o5, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o5[Symbol.iterator] || o5["@@iterator"];
if (!it) {
if (Array.isArray(o5) || (it = _unsupportedIterableToArray(o5)) || allowArrayLike && o5 && typeof o5.length === "number") {
if (it) o5 = it;
var i5 = 0;
var F3 = /* @__PURE__ */ __name(function F4() {
}, "F");
return { s: F3, n: /* @__PURE__ */ __name(function n6() {
if (i5 >= o5.length) return { done: true };
return { done: false, value: o5[i5++] };
}, "n"), e: /* @__PURE__ */ __name(function e7(_e2) {
throw _e2;
}, "e"), f: F3 };
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true, didErr = false, err;
return { s: /* @__PURE__ */ __name(function s5() {
it = it.call(o5);
}, "s"), n: /* @__PURE__ */ __name(function n6() {
var step = it.next();
normalCompletion = step.done;
return step;
}, "n"), e: /* @__PURE__ */ __name(function e7(_e2) {
didErr = true;
err = _e2;
}, "e"), f: /* @__PURE__ */ __name(function f6() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}, "f") };
}
__name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
function _unsupportedIterableToArray(o5, minLen) {
if (!o5) return;
if (typeof o5 === "string") return _arrayLikeToArray(o5, minLen);
var n6 = Object.prototype.toString.call(o5).slice(8, -1);
if (n6 === "Object" && o5.constructor) n6 = o5.constructor.name;
if (n6 === "Map" || n6 === "Set") return Array.from(o5);
if (n6 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n6)) return _arrayLikeToArray(o5, minLen);
}
__name(_unsupportedIterableToArray, "_unsupportedIterableToArray");
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i5 = 0, arr2 = new Array(len); i5 < len; i5++) arr2[i5] = arr[i5];
return arr2;
}
__name(_arrayLikeToArray, "_arrayLikeToArray");
function asyncGeneratorStep(gen, resolve25, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error2) {
reject(error2);
return;
}
if (info.done) {
resolve25(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
__name(asyncGeneratorStep, "asyncGeneratorStep");
function _asyncToGenerator(fn2) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve25, reject) {
var gen = fn2.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "next", value);
}
__name(_next, "_next");
function _throw(err) {
asyncGeneratorStep(gen, resolve25, reject, _next, _throw, "throw", err);
}
__name(_throw, "_throw");
_next(void 0);
});
};
}
__name(_asyncToGenerator, "_asyncToGenerator");
var prompts2 = require_prompts();
var passOn = ["suggest", "format", "onState", "validate", "onRender", "type"];
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
function prompt2() {
return _prompt.apply(this, arguments);
}
__name(prompt2, "prompt");
function _prompt() {
_prompt = _asyncToGenerator(function* (questions = [], {
onSubmit = noop,
onCancel = noop
} = {}) {
const answers = {};
const override2 = prompt2._override || {};
questions = [].concat(questions);
let answer, question, quit, name2, type, lastPrompt;
const getFormattedAnswer = /* @__PURE__ */ function() {
var _ref = _asyncToGenerator(function* (question2, answer2, skipValidation = false) {
if (!skipValidation && question2.validate && question2.validate(answer2) !== true) {
return;
}
return question2.format ? yield question2.format(answer2, answers) : answer2;
});
return /* @__PURE__ */ __name(function getFormattedAnswer2(_x2, _x22) {
return _ref.apply(this, arguments);
}, "getFormattedAnswer");
}();
var _iterator = _createForOfIteratorHelper(questions), _step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done; ) {
question = _step.value;
var _question = question;
name2 = _question.name;
type = _question.type;
if (typeof type === "function") {
type = yield type(answer, _objectSpread({}, answers), question);
question["type"] = type;
}
if (!type) continue;
for (let key in question) {
if (passOn.includes(key)) continue;
let value = question[key];
question[key] = typeof value === "function" ? yield value(answer, _objectSpread({}, answers), lastPrompt) : value;
}
lastPrompt = question;
if (typeof question.message !== "string") {
throw new Error("prompt message is required");
}
var _question2 = question;
name2 = _question2.name;
type = _question2.type;
if (prompts2[type] === void 0) {
throw new Error(`prompt type (${type}) is not defined`);
}
if (override2[question.name] !== void 0) {
answer = yield getFormattedAnswer(question, override2[question.name]);
if (answer !== void 0) {
answers[name2] = answer;
continue;
}
}
try {
answer = prompt2._injected ? getInjectedAnswer(prompt2._injected, question.initial) : yield prompts2[type](question);
answers[name2] = answer = yield getFormattedAnswer(question, answer, true);
quit = yield onSubmit(question, answer, answers);
} catch (err) {
quit = !(yield onCancel(question, answers));
}
if (quit) return answers;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return answers;
});
return _prompt.apply(this, arguments);
}
__name(_prompt, "_prompt");
function getInjectedAnswer(injected, deafultValue) {
const answer = injected.shift();
if (answer instanceof Error) {
throw answer;
}
return answer === void 0 ? deafultValue : answer;
}
__name(getInjectedAnswer, "getInjectedAnswer");
function inject(answers) {
prompt2._injected = (prompt2._injected || []).concat(answers);
}
__name(inject, "inject");
function override(answers) {
prompt2._override = Object.assign({}, answers);
}
__name(override, "override");
module3.exports = Object.assign(prompt2, {
prompt: prompt2,
prompts: prompts2,
inject,
override
});
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/action.js
var require_action2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/action.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (key, isSelect) => {
if (key.meta && key.name !== "escape") return;
if (key.ctrl) {
if (key.name === "a") return "first";
if (key.name === "c") return "abort";
if (key.name === "d") return "abort";
if (key.name === "e") return "last";
if (key.name === "g") return "reset";
}
if (isSelect) {
if (key.name === "j") return "down";
if (key.name === "k") return "up";
}
if (key.name === "return") return "submit";
if (key.name === "enter") return "submit";
if (key.name === "backspace") return "delete";
if (key.name === "delete") return "deleteForward";
if (key.name === "abort") return "abort";
if (key.name === "escape") return "exit";
if (key.name === "tab") return "next";
if (key.name === "pagedown") return "nextPage";
if (key.name === "pageup") return "prevPage";
if (key.name === "home") return "home";
if (key.name === "end") return "end";
if (key.name === "up") return "up";
if (key.name === "down") return "down";
if (key.name === "right") return "right";
if (key.name === "left") return "left";
return false;
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/strip.js
var require_strip2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/strip.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (str) => {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
].join("|");
const RGX = new RegExp(pattern, "g");
return typeof str === "string" ? str.replace(RGX, "") : str;
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/clear.js
var require_clear2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/clear.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var strip = require_strip2();
var { erase, cursor } = require_src();
var width = /* @__PURE__ */ __name((str) => [...strip(str)].length, "width");
module3.exports = function(prompt2, perLine) {
if (!perLine) return erase.line + cursor.to(0);
let rows = 0;
const lines = prompt2.split(/\r?\n/);
for (let line of lines) {
rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
}
return erase.lines(rows);
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/figures.js
var require_figures2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/figures.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var main2 = {
arrowUp: "\u2191",
arrowDown: "\u2193",
arrowLeft: "\u2190",
arrowRight: "\u2192",
radioOn: "\u25C9",
radioOff: "\u25EF",
tick: "\u2714",
cross: "\u2716",
ellipsis: "\u2026",
pointerSmall: "\u203A",
line: "\u2500",
pointer: "\u276F"
};
var win = {
arrowUp: main2.arrowUp,
arrowDown: main2.arrowDown,
arrowLeft: main2.arrowLeft,
arrowRight: main2.arrowRight,
radioOn: "(*)",
radioOff: "( )",
tick: "\u221A",
cross: "\xD7",
ellipsis: "...",
pointerSmall: "\xBB",
line: "\u2500",
pointer: ">"
};
var figures = process.platform === "win32" ? win : main2;
module3.exports = figures;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/style.js
var require_style2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/style.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var c6 = require_kleur();
var figures = require_figures2();
var styles4 = Object.freeze({
password: { scale: 1, render: /* @__PURE__ */ __name((input) => "*".repeat(input.length), "render") },
emoji: { scale: 2, render: /* @__PURE__ */ __name((input) => "\u{1F603}".repeat(input.length), "render") },
invisible: { scale: 0, render: /* @__PURE__ */ __name((input) => "", "render") },
default: { scale: 1, render: /* @__PURE__ */ __name((input) => `${input}`, "render") }
});
var render2 = /* @__PURE__ */ __name((type) => styles4[type] || styles4.default, "render");
var symbols = Object.freeze({
aborted: c6.red(figures.cross),
done: c6.green(figures.tick),
exited: c6.yellow(figures.cross),
default: c6.cyan("?")
});
var symbol = /* @__PURE__ */ __name((done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default, "symbol");
var delimiter = /* @__PURE__ */ __name((completing) => c6.gray(completing ? figures.ellipsis : figures.pointerSmall), "delimiter");
var item = /* @__PURE__ */ __name((expandable, expanded) => c6.gray(expandable ? expanded ? figures.pointerSmall : "+" : figures.line), "item");
module3.exports = {
styles: styles4,
render: render2,
symbols,
symbol,
delimiter,
item
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/lines.js
var require_lines2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/lines.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var strip = require_strip2();
module3.exports = function(msg, perLine) {
let lines = String(strip(msg) || "").split(/\r?\n/);
if (!perLine) return lines.length;
return lines.map((l6) => Math.ceil(l6.length / perLine)).reduce((a5, b6) => a5 + b6);
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/wrap.js
var require_wrap2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/wrap.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (msg, opts = {}) => {
const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(" ").join("") : opts.margin || "";
const width = opts.width;
return (msg || "").split(/\r?\n/g).map((line) => line.split(/\s+/g).reduce((arr, w6) => {
if (w6.length + tab.length >= width || arr[arr.length - 1].length + w6.length + 1 < width)
arr[arr.length - 1] += ` ${w6}`;
else arr.push(`${tab}${w6}`);
return arr;
}, [tab]).join("\n")).join("\n");
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/entriesToDisplay.js
var require_entriesToDisplay2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/entriesToDisplay.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (cursor, total, maxVisible) => {
maxVisible = maxVisible || total;
let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2));
if (startIndex < 0) startIndex = 0;
let endIndex = Math.min(startIndex + maxVisible, total);
return { startIndex, endIndex };
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/index.js
var require_util8 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/util/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
action: require_action2(),
clear: require_clear2(),
style: require_style2(),
strip: require_strip2(),
figures: require_figures2(),
lines: require_lines2(),
wrap: require_wrap2(),
entriesToDisplay: require_entriesToDisplay2()
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/prompt.js
var require_prompt2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/prompt.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var readline3 = require("readline");
var { action } = require_util8();
var EventEmitter5 = require("events");
var { beep, cursor } = require_src();
var color = require_kleur();
var Prompt = class extends EventEmitter5 {
static {
__name(this, "Prompt");
}
constructor(opts = {}) {
super();
this.firstRender = true;
this.in = opts.stdin || process.stdin;
this.out = opts.stdout || process.stdout;
this.onRender = (opts.onRender || (() => void 0)).bind(this);
const rl = readline3.createInterface({ input: this.in, escapeCodeTimeout: 50 });
readline3.emitKeypressEvents(this.in, rl);
if (this.in.isTTY) this.in.setRawMode(true);
const isSelect = ["SelectPrompt", "MultiselectPrompt"].indexOf(this.constructor.name) > -1;
const keypress = /* @__PURE__ */ __name((str, key) => {
let a5 = action(key, isSelect);
if (a5 === false) {
this._ && this._(str, key);
} else if (typeof this[a5] === "function") {
this[a5](key);
} else {
this.bell();
}
}, "keypress");
this.close = () => {
this.out.write(cursor.show);
this.in.removeListener("keypress", keypress);
if (this.in.isTTY) this.in.setRawMode(false);
rl.close();
this.emit(this.aborted ? "abort" : this.exited ? "exit" : "submit", this.value);
this.closed = true;
};
this.in.on("keypress", keypress);
}
fire() {
this.emit("state", {
value: this.value,
aborted: !!this.aborted,
exited: !!this.exited
});
}
bell() {
this.out.write(beep);
}
render() {
this.onRender(color);
if (this.firstRender) this.firstRender = false;
}
};
module3.exports = Prompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/text.js
var require_text2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/text.js"(exports2, module3) {
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { erase, cursor } = require_src();
var { style, clear, lines, figures } = require_util8();
var TextPrompt = class extends Prompt {
static {
__name(this, "TextPrompt");
}
constructor(opts = {}) {
super(opts);
this.transform = style.render(opts.style);
this.scale = this.transform.scale;
this.msg = opts.message;
this.initial = opts.initial || ``;
this.validator = opts.validate || (() => true);
this.value = ``;
this.errorMsg = opts.error || `Please Enter A Valid Value`;
this.cursor = Number(!!this.initial);
this.cursorOffset = 0;
this.clear = clear(``, this.out.columns);
this.render();
}
set value(v7) {
if (!v7 && this.initial) {
this.placeholder = true;
this.rendered = color.gray(this.transform.render(this.initial));
} else {
this.placeholder = false;
this.rendered = this.transform.render(v7);
}
this._value = v7;
this.fire();
}
get value() {
return this._value;
}
reset() {
this.value = ``;
this.cursor = Number(!!this.initial);
this.cursorOffset = 0;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.value = this.value || this.initial;
this.done = this.aborted = true;
this.error = false;
this.red = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
async validate() {
let valid = await this.validator(this.value);
if (typeof valid === `string`) {
this.errorMsg = valid;
valid = false;
}
this.error = !valid;
}
async submit() {
this.value = this.value || this.initial;
this.cursorOffset = 0;
this.cursor = this.rendered.length;
await this.validate();
if (this.error) {
this.red = true;
this.fire();
this.render();
return;
}
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
next() {
if (!this.placeholder) return this.bell();
this.value = this.initial;
this.cursor = this.rendered.length;
this.fire();
this.render();
}
moveCursor(n6) {
if (this.placeholder) return;
this.cursor = this.cursor + n6;
this.cursorOffset += n6;
}
_(c6, key) {
let s1 = this.value.slice(0, this.cursor);
let s22 = this.value.slice(this.cursor);
this.value = `${s1}${c6}${s22}`;
this.red = false;
this.cursor = this.placeholder ? 0 : s1.length + 1;
this.render();
}
delete() {
if (this.isCursorAtStart()) return this.bell();
let s1 = this.value.slice(0, this.cursor - 1);
let s22 = this.value.slice(this.cursor);
this.value = `${s1}${s22}`;
this.red = false;
if (this.isCursorAtStart()) {
this.cursorOffset = 0;
} else {
this.cursorOffset++;
this.moveCursor(-1);
}
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
let s1 = this.value.slice(0, this.cursor);
let s22 = this.value.slice(this.cursor + 1);
this.value = `${s1}${s22}`;
this.red = false;
if (this.isCursorAtEnd()) {
this.cursorOffset = 0;
} else {
this.cursorOffset++;
}
this.render();
}
first() {
this.cursor = 0;
this.render();
}
last() {
this.cursor = this.value.length;
this.render();
}
left() {
if (this.cursor <= 0 || this.placeholder) return this.bell();
this.moveCursor(-1);
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
this.moveCursor(1);
this.render();
}
isCursorAtStart() {
return this.cursor === 0 || this.placeholder && this.cursor === 1;
}
isCursorAtEnd() {
return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1;
}
render() {
if (this.closed) return;
if (!this.firstRender) {
if (this.outputError)
this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
this.out.write(clear(this.outputText, this.out.columns));
}
super.render();
this.outputError = "";
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(this.done),
this.red ? color.red(this.rendered) : this.rendered
].join(` `);
if (this.error) {
this.outputError += this.errorMsg.split(`
`).reduce((a5, l6, i5) => a5 + `
${i5 ? " " : figures.pointerSmall} ${color.red().italic(l6)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
}
};
module3.exports = TextPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/select.js
var require_select2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/select.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { style, clear, figures, wrap: wrap4, entriesToDisplay } = require_util8();
var { cursor } = require_src();
var SelectPrompt = class extends Prompt {
static {
__name(this, "SelectPrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.hint = opts.hint || "- Use arrow-keys. Return to submit.";
this.warn = opts.warn || "- This option is disabled";
this.cursor = opts.initial || 0;
this.choices = opts.choices.map((ch2, idx) => {
if (typeof ch2 === "string")
ch2 = { title: ch2, value: idx };
return {
title: ch2 && (ch2.title || ch2.value || ch2),
value: ch2 && (ch2.value === void 0 ? idx : ch2.value),
description: ch2 && ch2.description,
selected: ch2 && ch2.selected,
disabled: ch2 && ch2.disabled
};
});
this.optionsPerPage = opts.optionsPerPage || 10;
this.value = (this.choices[this.cursor] || {}).value;
this.clear = clear("", this.out.columns);
this.render();
}
moveCursor(n6) {
this.cursor = n6;
this.value = this.choices[n6].value;
this.fire();
}
reset() {
this.moveCursor(0);
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
if (!this.selection.disabled) {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
} else
this.bell();
}
first() {
this.moveCursor(0);
this.render();
}
last() {
this.moveCursor(this.choices.length - 1);
this.render();
}
up() {
if (this.cursor === 0) {
this.moveCursor(this.choices.length - 1);
} else {
this.moveCursor(this.cursor - 1);
}
this.render();
}
down() {
if (this.cursor === this.choices.length - 1) {
this.moveCursor(0);
} else {
this.moveCursor(this.cursor + 1);
}
this.render();
}
next() {
this.moveCursor((this.cursor + 1) % this.choices.length);
this.render();
}
_(c6, key) {
if (c6 === " ") return this.submit();
}
get selection() {
return this.choices[this.cursor];
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage);
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(false),
this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)
].join(" ");
if (!this.done) {
this.outputText += "\n";
for (let i5 = startIndex; i5 < endIndex; i5++) {
let title, prefix, desc = "", v7 = this.choices[i5];
if (i5 === startIndex && startIndex > 0) {
prefix = figures.arrowUp;
} else if (i5 === endIndex - 1 && endIndex < this.choices.length) {
prefix = figures.arrowDown;
} else {
prefix = " ";
}
if (v7.disabled) {
title = this.cursor === i5 ? color.gray().underline(v7.title) : color.strikethrough().gray(v7.title);
prefix = (this.cursor === i5 ? color.bold().gray(figures.pointer) + " " : " ") + prefix;
} else {
title = this.cursor === i5 ? color.cyan().underline(v7.title) : v7.title;
prefix = (this.cursor === i5 ? color.cyan(figures.pointer) + " " : " ") + prefix;
if (v7.description && this.cursor === i5) {
desc = ` - ${v7.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v7.description.split(/\r?\n/).length > 1) {
desc = "\n" + wrap4(v7.description, { margin: 3, width: this.out.columns });
}
}
}
this.outputText += `${prefix} ${title}${color.gray(desc)}
`;
}
}
this.out.write(this.outputText);
}
};
module3.exports = SelectPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/toggle.js
var require_toggle2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/toggle.js"(exports2, module3) {
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { style, clear } = require_util8();
var { cursor, erase } = require_src();
var TogglePrompt = class extends Prompt {
static {
__name(this, "TogglePrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.value = !!opts.initial;
this.active = opts.active || "on";
this.inactive = opts.inactive || "off";
this.initialValue = this.value;
this.render();
}
reset() {
this.value = this.initialValue;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
deactivate() {
if (this.value === false) return this.bell();
this.value = false;
this.render();
}
activate() {
if (this.value === true) return this.bell();
this.value = true;
this.render();
}
delete() {
this.deactivate();
}
left() {
this.deactivate();
}
right() {
this.activate();
}
down() {
this.deactivate();
}
up() {
this.activate();
}
next() {
this.value = !this.value;
this.fire();
this.render();
}
_(c6, key) {
if (c6 === " ") {
this.value = !this.value;
} else if (c6 === "1") {
this.value = true;
} else if (c6 === "0") {
this.value = false;
} else return this.bell();
this.render();
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(this.done),
this.value ? this.inactive : color.cyan().underline(this.inactive),
color.gray("/"),
this.value ? color.cyan().underline(this.active) : this.active
].join(" ");
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = TogglePrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/datepart.js
var require_datepart2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/datepart.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = class _DatePart {
static {
__name(this, "DatePart");
}
constructor({ token, date, parts, locales }) {
this.token = token;
this.date = date || /* @__PURE__ */ new Date();
this.parts = parts || [this];
this.locales = locales || {};
}
up() {
}
down() {
}
next() {
const currentIdx = this.parts.indexOf(this);
return this.parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
}
setTo(val2) {
}
prev() {
let parts = [].concat(this.parts).reverse();
const currentIdx = parts.indexOf(this);
return parts.find((part, idx) => idx > currentIdx && part instanceof _DatePart);
}
toString() {
return String(this.date);
}
};
module3.exports = DatePart;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/meridiem.js
var require_meridiem2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/meridiem.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Meridiem = class extends DatePart {
static {
__name(this, "Meridiem");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setHours((this.date.getHours() + 12) % 24);
}
down() {
this.up();
}
toString() {
let meridiem = this.date.getHours() > 12 ? "pm" : "am";
return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
}
};
module3.exports = Meridiem;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/day.js
var require_day2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/day.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var pos = /* @__PURE__ */ __name((n6) => {
n6 = n6 % 10;
return n6 === 1 ? "st" : n6 === 2 ? "nd" : n6 === 3 ? "rd" : "th";
}, "pos");
var Day = class extends DatePart {
static {
__name(this, "Day");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setDate(this.date.getDate() + 1);
}
down() {
this.date.setDate(this.date.getDate() - 1);
}
setTo(val2) {
this.date.setDate(parseInt(val2.substr(-2)));
}
toString() {
let date = this.date.getDate();
let day = this.date.getDay();
return this.token === "DD" ? String(date).padStart(2, "0") : this.token === "Do" ? date + pos(date) : this.token === "d" ? day + 1 : this.token === "ddd" ? this.locales.weekdaysShort[day] : this.token === "dddd" ? this.locales.weekdays[day] : date;
}
};
module3.exports = Day;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/hours.js
var require_hours2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/hours.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Hours = class extends DatePart {
static {
__name(this, "Hours");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setHours(this.date.getHours() + 1);
}
down() {
this.date.setHours(this.date.getHours() - 1);
}
setTo(val2) {
this.date.setHours(parseInt(val2.substr(-2)));
}
toString() {
let hours = this.date.getHours();
if (/h/.test(this.token))
hours = hours % 12 || 12;
return this.token.length > 1 ? String(hours).padStart(2, "0") : hours;
}
};
module3.exports = Hours;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/milliseconds.js
var require_milliseconds2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/milliseconds.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Milliseconds = class extends DatePart {
static {
__name(this, "Milliseconds");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMilliseconds(this.date.getMilliseconds() + 1);
}
down() {
this.date.setMilliseconds(this.date.getMilliseconds() - 1);
}
setTo(val2) {
this.date.setMilliseconds(parseInt(val2.substr(-this.token.length)));
}
toString() {
return String(this.date.getMilliseconds()).padStart(4, "0").substr(0, this.token.length);
}
};
module3.exports = Milliseconds;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/minutes.js
var require_minutes2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/minutes.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Minutes = class extends DatePart {
static {
__name(this, "Minutes");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMinutes(this.date.getMinutes() + 1);
}
down() {
this.date.setMinutes(this.date.getMinutes() - 1);
}
setTo(val2) {
this.date.setMinutes(parseInt(val2.substr(-2)));
}
toString() {
let m6 = this.date.getMinutes();
return this.token.length > 1 ? String(m6).padStart(2, "0") : m6;
}
};
module3.exports = Minutes;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/month.js
var require_month2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/month.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Month = class extends DatePart {
static {
__name(this, "Month");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMonth(this.date.getMonth() + 1);
}
down() {
this.date.setMonth(this.date.getMonth() - 1);
}
setTo(val2) {
val2 = parseInt(val2.substr(-2)) - 1;
this.date.setMonth(val2 < 0 ? 0 : val2);
}
toString() {
let month = this.date.getMonth();
let tl = this.token.length;
return tl === 2 ? String(month + 1).padStart(2, "0") : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1);
}
};
module3.exports = Month;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/seconds.js
var require_seconds2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/seconds.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Seconds = class extends DatePart {
static {
__name(this, "Seconds");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setSeconds(this.date.getSeconds() + 1);
}
down() {
this.date.setSeconds(this.date.getSeconds() - 1);
}
setTo(val2) {
this.date.setSeconds(parseInt(val2.substr(-2)));
}
toString() {
let s5 = this.date.getSeconds();
return this.token.length > 1 ? String(s5).padStart(2, "0") : s5;
}
};
module3.exports = Seconds;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/year.js
var require_year2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/year.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var DatePart = require_datepart2();
var Year = class extends DatePart {
static {
__name(this, "Year");
}
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setFullYear(this.date.getFullYear() + 1);
}
down() {
this.date.setFullYear(this.date.getFullYear() - 1);
}
setTo(val2) {
this.date.setFullYear(val2.substr(-4));
}
toString() {
let year = String(this.date.getFullYear()).padStart(4, "0");
return this.token.length === 2 ? year.substr(-2) : year;
}
};
module3.exports = Year;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/index.js
var require_dateparts2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/dateparts/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
DatePart: require_datepart2(),
Meridiem: require_meridiem2(),
Day: require_day2(),
Hours: require_hours2(),
Milliseconds: require_milliseconds2(),
Minutes: require_minutes2(),
Month: require_month2(),
Seconds: require_seconds2(),
Year: require_year2()
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/date.js
var require_date3 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/date.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { style, clear, figures } = require_util8();
var { erase, cursor } = require_src();
var { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = require_dateparts2();
var regex2 = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
var regexGroups = {
1: ({ token }) => token.replace(/\\(.)/g, "$1"),
2: (opts) => new Day(opts),
// Day // TODO
3: (opts) => new Month(opts),
// Month
4: (opts) => new Year(opts),
// Year
5: (opts) => new Meridiem(opts),
// AM/PM // TODO (special)
6: (opts) => new Hours(opts),
// Hours
7: (opts) => new Minutes(opts),
// Minutes
8: (opts) => new Seconds(opts),
// Seconds
9: (opts) => new Milliseconds(opts)
// Fractional seconds
};
var dfltLocales = {
months: "January,February,March,April,May,June,July,August,September,October,November,December".split(","),
monthsShort: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),
weekdays: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
weekdaysShort: "Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")
};
var DatePrompt = class extends Prompt {
static {
__name(this, "DatePrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.cursor = 0;
this.typed = "";
this.locales = Object.assign(dfltLocales, opts.locales);
this._date = opts.initial || /* @__PURE__ */ new Date();
this.errorMsg = opts.error || "Please Enter A Valid Value";
this.validator = opts.validate || (() => true);
this.mask = opts.mask || "YYYY-MM-DD HH:mm:ss";
this.clear = clear("", this.out.columns);
this.render();
}
get value() {
return this.date;
}
get date() {
return this._date;
}
set date(date) {
if (date) this._date.setTime(date.getTime());
}
set mask(mask) {
let result;
this.parts = [];
while (result = regex2.exec(mask)) {
let match2 = result.shift();
let idx = result.findIndex((gr) => gr != null);
this.parts.push(idx in regexGroups ? regexGroups[idx]({ token: result[idx] || match2, date: this.date, parts: this.parts, locales: this.locales }) : result[idx] || match2);
}
let parts = this.parts.reduce((arr, i5) => {
if (typeof i5 === "string" && typeof arr[arr.length - 1] === "string")
arr[arr.length - 1] += i5;
else arr.push(i5);
return arr;
}, []);
this.parts.splice(0);
this.parts.push(...parts);
this.reset();
}
moveCursor(n6) {
this.typed = "";
this.cursor = n6;
this.fire();
}
reset() {
this.moveCursor(this.parts.findIndex((p6) => p6 instanceof DatePart));
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.error = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
async validate() {
let valid = await this.validator(this.value);
if (typeof valid === "string") {
this.errorMsg = valid;
valid = false;
}
this.error = !valid;
}
async submit() {
await this.validate();
if (this.error) {
this.color = "red";
this.fire();
this.render();
return;
}
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
up() {
this.typed = "";
this.parts[this.cursor].up();
this.render();
}
down() {
this.typed = "";
this.parts[this.cursor].down();
this.render();
}
left() {
let prev = this.parts[this.cursor].prev();
if (prev == null) return this.bell();
this.moveCursor(this.parts.indexOf(prev));
this.render();
}
right() {
let next = this.parts[this.cursor].next();
if (next == null) return this.bell();
this.moveCursor(this.parts.indexOf(next));
this.render();
}
next() {
let next = this.parts[this.cursor].next();
this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex((part) => part instanceof DatePart));
this.render();
}
_(c6) {
if (/\d/.test(c6)) {
this.typed += c6;
this.parts[this.cursor].setTo(this.typed);
this.render();
}
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(false),
this.parts.reduce((arr, p6, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p6.toString()) : p6), []).join("")
].join(" ");
if (this.error) {
this.outputText += this.errorMsg.split("\n").reduce(
(a5, l6, i5) => a5 + `
${i5 ? ` ` : figures.pointerSmall} ${color.red().italic(l6)}`,
``
);
}
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = DatePrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/number.js
var require_number2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/number.js"(exports2, module3) {
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { cursor, erase } = require_src();
var { style, figures, clear, lines } = require_util8();
var isNumber = /[0-9]/;
var isDef = /* @__PURE__ */ __name((any) => any !== void 0, "isDef");
var round = /* @__PURE__ */ __name((number, precision) => {
let factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}, "round");
var NumberPrompt = class extends Prompt {
static {
__name(this, "NumberPrompt");
}
constructor(opts = {}) {
super(opts);
this.transform = style.render(opts.style);
this.msg = opts.message;
this.initial = isDef(opts.initial) ? opts.initial : "";
this.float = !!opts.float;
this.round = opts.round || 2;
this.inc = opts.increment || 1;
this.min = isDef(opts.min) ? opts.min : -Infinity;
this.max = isDef(opts.max) ? opts.max : Infinity;
this.errorMsg = opts.error || `Please Enter A Valid Value`;
this.validator = opts.validate || (() => true);
this.color = `cyan`;
this.value = ``;
this.typed = ``;
this.lastHit = 0;
this.render();
}
set value(v7) {
if (!v7 && v7 !== 0) {
this.placeholder = true;
this.rendered = color.gray(this.transform.render(`${this.initial}`));
this._value = ``;
} else {
this.placeholder = false;
this.rendered = this.transform.render(`${round(v7, this.round)}`);
this._value = round(v7, this.round);
}
this.fire();
}
get value() {
return this._value;
}
parse(x6) {
return this.float ? parseFloat(x6) : parseInt(x6);
}
valid(c6) {
return c6 === `-` || c6 === `.` && this.float || isNumber.test(c6);
}
reset() {
this.typed = ``;
this.value = ``;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
let x6 = this.value;
this.value = x6 !== `` ? x6 : this.initial;
this.done = this.aborted = true;
this.error = false;
this.fire();
this.render();
this.out.write(`
`);
this.close();
}
async validate() {
let valid = await this.validator(this.value);
if (typeof valid === `string`) {
this.errorMsg = valid;
valid = false;
}
this.error = !valid;
}
async submit() {
await this.validate();
if (this.error) {
this.color = `red`;
this.fire();
this.render();
return;
}
let x6 = this.value;
this.value = x6 !== `` ? x6 : this.initial;
this.done = true;
this.aborted = false;
this.error = false;
this.fire();
this.render();
this.out.write(`
`);
this.close();
}
up() {
this.typed = ``;
if (this.value === "") {
this.value = this.min - this.inc;
}
if (this.value >= this.max) return this.bell();
this.value += this.inc;
this.color = `cyan`;
this.fire();
this.render();
}
down() {
this.typed = ``;
if (this.value === "") {
this.value = this.min + this.inc;
}
if (this.value <= this.min) return this.bell();
this.value -= this.inc;
this.color = `cyan`;
this.fire();
this.render();
}
delete() {
let val2 = this.value.toString();
if (val2.length === 0) return this.bell();
this.value = this.parse(val2 = val2.slice(0, -1)) || ``;
if (this.value !== "" && this.value < this.min) {
this.value = this.min;
}
this.color = `cyan`;
this.fire();
this.render();
}
next() {
this.value = this.initial;
this.fire();
this.render();
}
_(c6, key) {
if (!this.valid(c6)) return this.bell();
const now = Date.now();
if (now - this.lastHit > 1e3) this.typed = ``;
this.typed += c6;
this.lastHit = now;
this.color = `cyan`;
if (c6 === `.`) return this.fire();
this.value = Math.min(this.parse(this.typed), this.max);
if (this.value > this.max) this.value = this.max;
if (this.value < this.min) this.value = this.min;
this.fire();
this.render();
}
render() {
if (this.closed) return;
if (!this.firstRender) {
if (this.outputError)
this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
this.out.write(clear(this.outputText, this.out.columns));
}
super.render();
this.outputError = "";
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(this.done),
!this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered
].join(` `);
if (this.error) {
this.outputError += this.errorMsg.split(`
`).reduce((a5, l6, i5) => a5 + `
${i5 ? ` ` : figures.pointerSmall} ${color.red().italic(l6)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
}
};
module3.exports = NumberPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/multiselect.js
var require_multiselect2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/multiselect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var { cursor } = require_src();
var Prompt = require_prompt2();
var { clear, figures, style, wrap: wrap4, entriesToDisplay } = require_util8();
var MultiselectPrompt = class extends Prompt {
static {
__name(this, "MultiselectPrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.cursor = opts.cursor || 0;
this.scrollIndex = opts.cursor || 0;
this.hint = opts.hint || "";
this.warn = opts.warn || "- This option is disabled -";
this.minSelected = opts.min;
this.showMinError = false;
this.maxChoices = opts.max;
this.instructions = opts.instructions;
this.optionsPerPage = opts.optionsPerPage || 10;
this.value = opts.choices.map((ch2, idx) => {
if (typeof ch2 === "string")
ch2 = { title: ch2, value: idx };
return {
title: ch2 && (ch2.title || ch2.value || ch2),
description: ch2 && ch2.description,
value: ch2 && (ch2.value === void 0 ? idx : ch2.value),
selected: ch2 && ch2.selected,
disabled: ch2 && ch2.disabled
};
});
this.clear = clear("", this.out.columns);
if (!opts.overrideRender) {
this.render();
}
}
reset() {
this.value.map((v7) => !v7.selected);
this.cursor = 0;
this.fire();
this.render();
}
selected() {
return this.value.filter((v7) => v7.selected);
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
const selected = this.value.filter((e7) => e7.selected);
if (this.minSelected && selected.length < this.minSelected) {
this.showMinError = true;
this.render();
} else {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
}
first() {
this.cursor = 0;
this.render();
}
last() {
this.cursor = this.value.length - 1;
this.render();
}
next() {
this.cursor = (this.cursor + 1) % this.value.length;
this.render();
}
up() {
if (this.cursor === 0) {
this.cursor = this.value.length - 1;
} else {
this.cursor--;
}
this.render();
}
down() {
if (this.cursor === this.value.length - 1) {
this.cursor = 0;
} else {
this.cursor++;
}
this.render();
}
left() {
this.value[this.cursor].selected = false;
this.render();
}
right() {
if (this.value.filter((e7) => e7.selected).length >= this.maxChoices) return this.bell();
this.value[this.cursor].selected = true;
this.render();
}
handleSpaceToggle() {
const v7 = this.value[this.cursor];
if (v7.selected) {
v7.selected = false;
this.render();
} else if (v7.disabled || this.value.filter((e7) => e7.selected).length >= this.maxChoices) {
return this.bell();
} else {
v7.selected = true;
this.render();
}
}
toggleAll() {
if (this.maxChoices !== void 0 || this.value[this.cursor].disabled) {
return this.bell();
}
const newSelected = !this.value[this.cursor].selected;
this.value.filter((v7) => !v7.disabled).forEach((v7) => v7.selected = newSelected);
this.render();
}
_(c6, key) {
if (c6 === " ") {
this.handleSpaceToggle();
} else if (c6 === "a") {
this.toggleAll();
} else {
return this.bell();
}
}
renderInstructions() {
if (this.instructions === void 0 || this.instructions) {
if (typeof this.instructions === "string") {
return this.instructions;
}
return `
Instructions:
${figures.arrowUp}/${figures.arrowDown}: Highlight option
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
` + (this.maxChoices === void 0 ? ` a: Toggle all
` : "") + ` enter/return: Complete answer`;
}
return "";
}
renderOption(cursor2, v7, i5, arrowIndicator) {
const prefix = (v7.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + arrowIndicator + " ";
let title, desc;
if (v7.disabled) {
title = cursor2 === i5 ? color.gray().underline(v7.title) : color.strikethrough().gray(v7.title);
} else {
title = cursor2 === i5 ? color.cyan().underline(v7.title) : v7.title;
if (cursor2 === i5 && v7.description) {
desc = ` - ${v7.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v7.description.split(/\r?\n/).length > 1) {
desc = "\n" + wrap4(v7.description, { margin: prefix.length, width: this.out.columns });
}
}
}
return prefix + title + color.gray(desc || "");
}
// shared with autocompleteMultiselect
paginateOptions(options) {
if (options.length === 0) {
return color.red("No matches for this query.");
}
let { startIndex, endIndex } = entriesToDisplay(this.cursor, options.length, this.optionsPerPage);
let prefix, styledOptions = [];
for (let i5 = startIndex; i5 < endIndex; i5++) {
if (i5 === startIndex && startIndex > 0) {
prefix = figures.arrowUp;
} else if (i5 === endIndex - 1 && endIndex < options.length) {
prefix = figures.arrowDown;
} else {
prefix = " ";
}
styledOptions.push(this.renderOption(this.cursor, options[i5], i5, prefix));
}
return "\n" + styledOptions.join("\n");
}
// shared with autocomleteMultiselect
renderOptions(options) {
if (!this.done) {
return this.paginateOptions(options);
}
return "";
}
renderDoneOrInstructions() {
if (this.done) {
return this.value.filter((e7) => e7.selected).map((v7) => v7.title).join(", ");
}
const output = [color.gray(this.hint), this.renderInstructions()];
if (this.value[this.cursor].disabled) {
output.push(color.yellow(this.warn));
}
return output.join(" ");
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
super.render();
let prompt2 = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(false),
this.renderDoneOrInstructions()
].join(" ");
if (this.showMinError) {
prompt2 += color.red(`You must select a minimum of ${this.minSelected} choices.`);
this.showMinError = false;
}
prompt2 += this.renderOptions(this.value);
this.out.write(this.clear + prompt2);
this.clear = clear(prompt2, this.out.columns);
}
};
module3.exports = MultiselectPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/autocomplete.js
var require_autocomplete2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/autocomplete.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { erase, cursor } = require_src();
var { style, clear, figures, wrap: wrap4, entriesToDisplay } = require_util8();
var getVal = /* @__PURE__ */ __name((arr, i5) => arr[i5] && (arr[i5].value || arr[i5].title || arr[i5]), "getVal");
var getTitle = /* @__PURE__ */ __name((arr, i5) => arr[i5] && (arr[i5].title || arr[i5].value || arr[i5]), "getTitle");
var getIndex2 = /* @__PURE__ */ __name((arr, valOrTitle) => {
const index = arr.findIndex((el) => el.value === valOrTitle || el.title === valOrTitle);
return index > -1 ? index : void 0;
}, "getIndex");
var AutocompletePrompt = class extends Prompt {
static {
__name(this, "AutocompletePrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.suggest = opts.suggest;
this.choices = opts.choices;
this.initial = typeof opts.initial === "number" ? opts.initial : getIndex2(opts.choices, opts.initial);
this.select = this.initial || opts.cursor || 0;
this.i18n = { noMatches: opts.noMatches || "no matches found" };
this.fallback = opts.fallback || this.initial;
this.clearFirst = opts.clearFirst || false;
this.suggestions = [];
this.input = "";
this.limit = opts.limit || 10;
this.cursor = 0;
this.transform = style.render(opts.style);
this.scale = this.transform.scale;
this.render = this.render.bind(this);
this.complete = this.complete.bind(this);
this.clear = clear("", this.out.columns);
this.complete(this.render);
this.render();
}
set fallback(fb) {
this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
}
get fallback() {
let choice;
if (typeof this._fb === "number")
choice = this.choices[this._fb];
else if (typeof this._fb === "string")
choice = { title: this._fb };
return choice || this._fb || { title: this.i18n.noMatches };
}
moveSelect(i5) {
this.select = i5;
if (this.suggestions.length > 0)
this.value = getVal(this.suggestions, i5);
else this.value = this.fallback.value;
this.fire();
}
async complete(cb2) {
const p6 = this.completing = this.suggest(this.input, this.choices);
const suggestions = await p6;
if (this.completing !== p6) return;
this.suggestions = suggestions.map((s5, i5, arr) => ({ title: getTitle(arr, i5), value: getVal(arr, i5), description: s5.description }));
this.completing = false;
const l6 = Math.max(suggestions.length - 1, 0);
this.moveSelect(Math.min(l6, this.select));
cb2 && cb2();
}
reset() {
this.input = "";
this.complete(() => {
this.moveSelect(this.initial !== void 0 ? this.initial : 0);
this.render();
});
this.render();
}
exit() {
if (this.clearFirst && this.input.length > 0) {
this.reset();
} else {
this.done = this.exited = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
}
abort() {
this.done = this.aborted = true;
this.exited = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
this.done = true;
this.aborted = this.exited = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
_(c6, key) {
let s1 = this.input.slice(0, this.cursor);
let s22 = this.input.slice(this.cursor);
this.input = `${s1}${c6}${s22}`;
this.cursor = s1.length + 1;
this.complete(this.render);
this.render();
}
delete() {
if (this.cursor === 0) return this.bell();
let s1 = this.input.slice(0, this.cursor - 1);
let s22 = this.input.slice(this.cursor);
this.input = `${s1}${s22}`;
this.complete(this.render);
this.cursor = this.cursor - 1;
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
let s1 = this.input.slice(0, this.cursor);
let s22 = this.input.slice(this.cursor + 1);
this.input = `${s1}${s22}`;
this.complete(this.render);
this.render();
}
first() {
this.moveSelect(0);
this.render();
}
last() {
this.moveSelect(this.suggestions.length - 1);
this.render();
}
up() {
if (this.select === 0) {
this.moveSelect(this.suggestions.length - 1);
} else {
this.moveSelect(this.select - 1);
}
this.render();
}
down() {
if (this.select === this.suggestions.length - 1) {
this.moveSelect(0);
} else {
this.moveSelect(this.select + 1);
}
this.render();
}
next() {
if (this.select === this.suggestions.length - 1) {
this.moveSelect(0);
} else this.moveSelect(this.select + 1);
this.render();
}
nextPage() {
this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
this.render();
}
prevPage() {
this.moveSelect(Math.max(this.select - this.limit, 0));
this.render();
}
left() {
if (this.cursor <= 0) return this.bell();
this.cursor = this.cursor - 1;
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
this.cursor = this.cursor + 1;
this.render();
}
renderOption(v7, hovered, isStart, isEnd) {
let desc;
let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : " ";
let title = hovered ? color.cyan().underline(v7.title) : v7.title;
prefix = (hovered ? color.cyan(figures.pointer) + " " : " ") + prefix;
if (v7.description) {
desc = ` - ${v7.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v7.description.split(/\r?\n/).length > 1) {
desc = "\n" + wrap4(v7.description, { margin: 3, width: this.out.columns });
}
}
return prefix + " " + title + color.gray(desc || "");
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit);
this.outputText = [
style.symbol(this.done, this.aborted, this.exited),
color.bold(this.msg),
style.delimiter(this.completing),
this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)
].join(" ");
if (!this.done) {
const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i5) => this.renderOption(
item,
this.select === i5 + startIndex,
i5 === 0 && startIndex > 0,
i5 + startIndex === endIndex - 1 && endIndex < this.choices.length
)).join("\n");
this.outputText += `
` + (suggestions || color.gray(this.fallback.title));
}
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = AutocompletePrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/autocompleteMultiselect.js
var require_autocompleteMultiselect2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/autocompleteMultiselect.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var color = require_kleur();
var { cursor } = require_src();
var MultiselectPrompt = require_multiselect2();
var { clear, style, figures } = require_util8();
var AutocompleteMultiselectPrompt = class extends MultiselectPrompt {
static {
__name(this, "AutocompleteMultiselectPrompt");
}
constructor(opts = {}) {
opts.overrideRender = true;
super(opts);
this.inputValue = "";
this.clear = clear("", this.out.columns);
this.filteredOptions = this.value;
this.render();
}
last() {
this.cursor = this.filteredOptions.length - 1;
this.render();
}
next() {
this.cursor = (this.cursor + 1) % this.filteredOptions.length;
this.render();
}
up() {
if (this.cursor === 0) {
this.cursor = this.filteredOptions.length - 1;
} else {
this.cursor--;
}
this.render();
}
down() {
if (this.cursor === this.filteredOptions.length - 1) {
this.cursor = 0;
} else {
this.cursor++;
}
this.render();
}
left() {
this.filteredOptions[this.cursor].selected = false;
this.render();
}
right() {
if (this.value.filter((e7) => e7.selected).length >= this.maxChoices) return this.bell();
this.filteredOptions[this.cursor].selected = true;
this.render();
}
delete() {
if (this.inputValue.length) {
this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1);
this.updateFilteredOptions();
}
}
updateFilteredOptions() {
const currentHighlight = this.filteredOptions[this.cursor];
this.filteredOptions = this.value.filter((v7) => {
if (this.inputValue) {
if (typeof v7.title === "string") {
if (v7.title.toLowerCase().includes(this.inputValue.toLowerCase())) {
return true;
}
}
if (typeof v7.value === "string") {
if (v7.value.toLowerCase().includes(this.inputValue.toLowerCase())) {
return true;
}
}
return false;
}
return true;
});
const newHighlightIndex = this.filteredOptions.findIndex((v7) => v7 === currentHighlight);
this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex;
this.render();
}
handleSpaceToggle() {
const v7 = this.filteredOptions[this.cursor];
if (v7.selected) {
v7.selected = false;
this.render();
} else if (v7.disabled || this.value.filter((e7) => e7.selected).length >= this.maxChoices) {
return this.bell();
} else {
v7.selected = true;
this.render();
}
}
handleInputChange(c6) {
this.inputValue = this.inputValue + c6;
this.updateFilteredOptions();
}
_(c6, key) {
if (c6 === " ") {
this.handleSpaceToggle();
} else {
this.handleInputChange(c6);
}
}
renderInstructions() {
if (this.instructions === void 0 || this.instructions) {
if (typeof this.instructions === "string") {
return this.instructions;
}
return `
Instructions:
${figures.arrowUp}/${figures.arrowDown}: Highlight option
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
[a,b,c]/delete: Filter choices
enter/return: Complete answer
`;
}
return "";
}
renderCurrentInput() {
return `
Filtered results for: ${this.inputValue ? this.inputValue : color.gray("Enter something to filter")}
`;
}
renderOption(cursor2, v7, i5) {
let title;
if (v7.disabled) title = cursor2 === i5 ? color.gray().underline(v7.title) : color.strikethrough().gray(v7.title);
else title = cursor2 === i5 ? color.cyan().underline(v7.title) : v7.title;
return (v7.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + title;
}
renderDoneOrInstructions() {
if (this.done) {
return this.value.filter((e7) => e7.selected).map((v7) => v7.title).join(", ");
}
const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()];
if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) {
output.push(color.yellow(this.warn));
}
return output.join(" ");
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
super.render();
let prompt2 = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(false),
this.renderDoneOrInstructions()
].join(" ");
if (this.showMinError) {
prompt2 += color.red(`You must select a minimum of ${this.minSelected} choices.`);
this.showMinError = false;
}
prompt2 += this.renderOptions(this.filteredOptions);
this.out.write(this.clear + prompt2);
this.clear = clear(prompt2, this.out.columns);
}
};
module3.exports = AutocompleteMultiselectPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/confirm.js
var require_confirm2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/confirm.js"(exports2, module3) {
init_import_meta_url();
var color = require_kleur();
var Prompt = require_prompt2();
var { style, clear } = require_util8();
var { erase, cursor } = require_src();
var ConfirmPrompt = class extends Prompt {
static {
__name(this, "ConfirmPrompt");
}
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.value = opts.initial;
this.initialValue = !!opts.initial;
this.yesMsg = opts.yes || "yes";
this.yesOption = opts.yesOption || "(Y/n)";
this.noMsg = opts.no || "no";
this.noOption = opts.noOption || "(y/N)";
this.render();
}
reset() {
this.value = this.initialValue;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
submit() {
this.value = this.value || false;
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write("\n");
this.close();
}
_(c6, key) {
if (c6.toLowerCase() === "y") {
this.value = true;
return this.submit();
}
if (c6.toLowerCase() === "n") {
this.value = false;
return this.submit();
}
return this.bell();
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(this.done),
this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)
].join(" ");
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
};
module3.exports = ConfirmPrompt;
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/index.js
var require_elements2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/elements/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = {
TextPrompt: require_text2(),
SelectPrompt: require_select2(),
TogglePrompt: require_toggle2(),
DatePrompt: require_date3(),
NumberPrompt: require_number2(),
MultiselectPrompt: require_multiselect2(),
AutocompletePrompt: require_autocomplete2(),
AutocompleteMultiselectPrompt: require_autocompleteMultiselect2(),
ConfirmPrompt: require_confirm2()
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/prompts.js
var require_prompts2 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/prompts.js"(exports2) {
"use strict";
init_import_meta_url();
var $2 = exports2;
var el = require_elements2();
var noop = /* @__PURE__ */ __name((v7) => v7, "noop");
function toPrompt(type, args, opts = {}) {
return new Promise((res, rej) => {
const p6 = new el[type](args);
const onAbort = opts.onAbort || noop;
const onSubmit = opts.onSubmit || noop;
const onExit6 = opts.onExit || noop;
p6.on("state", args.onState || noop);
p6.on("submit", (x6) => res(onSubmit(x6)));
p6.on("exit", (x6) => res(onExit6(x6)));
p6.on("abort", (x6) => rej(onAbort(x6)));
});
}
__name(toPrompt, "toPrompt");
$2.text = (args) => toPrompt("TextPrompt", args);
$2.password = (args) => {
args.style = "password";
return $2.text(args);
};
$2.invisible = (args) => {
args.style = "invisible";
return $2.text(args);
};
$2.number = (args) => toPrompt("NumberPrompt", args);
$2.date = (args) => toPrompt("DatePrompt", args);
$2.confirm = (args) => toPrompt("ConfirmPrompt", args);
$2.list = (args) => {
const sep5 = args.separator || ",";
return toPrompt("TextPrompt", args, {
onSubmit: /* @__PURE__ */ __name((str) => str.split(sep5).map((s5) => s5.trim()), "onSubmit")
});
};
$2.toggle = (args) => toPrompt("TogglePrompt", args);
$2.select = (args) => toPrompt("SelectPrompt", args);
$2.multiselect = (args) => {
args.choices = [].concat(args.choices || []);
const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
return toPrompt("MultiselectPrompt", args, {
onAbort: toSelected,
onSubmit: toSelected
});
};
$2.autocompleteMultiselect = (args) => {
args.choices = [].concat(args.choices || []);
const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
return toPrompt("AutocompleteMultiselectPrompt", args, {
onAbort: toSelected,
onSubmit: toSelected
});
};
var byTitle = /* @__PURE__ */ __name((input, choices) => Promise.resolve(
choices.filter((item) => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())
), "byTitle");
$2.autocomplete = (args) => {
args.suggest = args.suggest || byTitle;
args.choices = [].concat(args.choices || []);
return toPrompt("AutocompletePrompt", args);
};
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/index.js
var require_lib = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/lib/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var prompts2 = require_prompts2();
var passOn = ["suggest", "format", "onState", "validate", "onRender", "type"];
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
async function prompt2(questions = [], { onSubmit = noop, onCancel = noop } = {}) {
const answers = {};
const override2 = prompt2._override || {};
questions = [].concat(questions);
let answer, question, quit, name2, type, lastPrompt;
const getFormattedAnswer = /* @__PURE__ */ __name(async (question2, answer2, skipValidation = false) => {
if (!skipValidation && question2.validate && question2.validate(answer2) !== true) {
return;
}
return question2.format ? await question2.format(answer2, answers) : answer2;
}, "getFormattedAnswer");
for (question of questions) {
({ name: name2, type } = question);
if (typeof type === "function") {
type = await type(answer, { ...answers }, question);
question["type"] = type;
}
if (!type) continue;
for (let key in question) {
if (passOn.includes(key)) continue;
let value = question[key];
question[key] = typeof value === "function" ? await value(answer, { ...answers }, lastPrompt) : value;
}
lastPrompt = question;
if (typeof question.message !== "string") {
throw new Error("prompt message is required");
}
({ name: name2, type } = question);
if (prompts2[type] === void 0) {
throw new Error(`prompt type (${type}) is not defined`);
}
if (override2[question.name] !== void 0) {
answer = await getFormattedAnswer(question, override2[question.name]);
if (answer !== void 0) {
answers[name2] = answer;
continue;
}
}
try {
answer = prompt2._injected ? getInjectedAnswer(prompt2._injected, question.initial) : await prompts2[type](question);
answers[name2] = answer = await getFormattedAnswer(question, answer, true);
quit = await onSubmit(question, answer, answers);
} catch (err) {
quit = !await onCancel(question, answers);
}
if (quit) return answers;
}
return answers;
}
__name(prompt2, "prompt");
function getInjectedAnswer(injected, deafultValue) {
const answer = injected.shift();
if (answer instanceof Error) {
throw answer;
}
return answer === void 0 ? deafultValue : answer;
}
__name(getInjectedAnswer, "getInjectedAnswer");
function inject(answers) {
prompt2._injected = (prompt2._injected || []).concat(answers);
}
__name(inject, "inject");
function override(answers) {
prompt2._override = Object.assign({}, answers);
}
__name(override, "override");
module3.exports = Object.assign(prompt2, { prompt: prompt2, prompts: prompts2, inject, override });
}
});
// ../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/index.js
var require_prompts3 = __commonJS({
"../../node_modules/.pnpm/prompts@2.4.2/node_modules/prompts/index.js"(exports2, module3) {
init_import_meta_url();
function isNodeLT(tar) {
tar = (Array.isArray(tar) ? tar : tar.split(".")).map(Number);
let i5 = 0, src = process.versions.node.split(".").map(Number);
for (; i5 < tar.length; i5++) {
if (src[i5] > tar[i5]) return false;
if (tar[i5] > src[i5]) return true;
}
return false;
}
__name(isNodeLT, "isNodeLT");
module3.exports = isNodeLT("8.6.0") ? require_dist2() : require_lib();
}
});
// ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
var require_picocolors = __commonJS({
"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2, module3) {
init_import_meta_url();
var p6 = process || {};
var argv = p6.argv || [];
var env6 = p6.env || {};
var isColorSupported = !(!!env6.NO_COLOR || argv.includes("--no-color")) && (!!env6.FORCE_COLOR || argv.includes("--color") || p6.platform === "win32" || (p6.stdout || {}).isTTY && env6.TERM !== "dumb" || !!env6.CI);
var formatter = /* @__PURE__ */ __name((open4, close2, replace = open4) => (input) => {
let string = "" + input, index = string.indexOf(close2, open4.length);
return ~index ? open4 + replaceClose(string, close2, replace, index) + close2 : open4 + string + close2;
}, "formatter");
var replaceClose = /* @__PURE__ */ __name((string, close2, replace, index) => {
let result = "", cursor = 0;
do {
result += string.substring(cursor, index) + replace;
cursor = index + close2.length;
index = string.indexOf(close2, cursor);
} while (~index);
return result + string.substring(cursor);
}, "replaceClose");
var createColors = /* @__PURE__ */ __name((enabled = isColorSupported) => {
let f6 = enabled ? formatter : () => String;
return {
isColorSupported: enabled,
reset: f6("\x1B[0m", "\x1B[0m"),
bold: f6("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
dim: f6("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
italic: f6("\x1B[3m", "\x1B[23m"),
underline: f6("\x1B[4m", "\x1B[24m"),
inverse: f6("\x1B[7m", "\x1B[27m"),
hidden: f6("\x1B[8m", "\x1B[28m"),
strikethrough: f6("\x1B[9m", "\x1B[29m"),
black: f6("\x1B[30m", "\x1B[39m"),
red: f6("\x1B[31m", "\x1B[39m"),
green: f6("\x1B[32m", "\x1B[39m"),
yellow: f6("\x1B[33m", "\x1B[39m"),
blue: f6("\x1B[34m", "\x1B[39m"),
magenta: f6("\x1B[35m", "\x1B[39m"),
cyan: f6("\x1B[36m", "\x1B[39m"),
white: f6("\x1B[37m", "\x1B[39m"),
gray: f6("\x1B[90m", "\x1B[39m"),
bgBlack: f6("\x1B[40m", "\x1B[49m"),
bgRed: f6("\x1B[41m", "\x1B[49m"),
bgGreen: f6("\x1B[42m", "\x1B[49m"),
bgYellow: f6("\x1B[43m", "\x1B[49m"),
bgBlue: f6("\x1B[44m", "\x1B[49m"),
bgMagenta: f6("\x1B[45m", "\x1B[49m"),
bgCyan: f6("\x1B[46m", "\x1B[49m"),
bgWhite: f6("\x1B[47m", "\x1B[49m"),
blackBright: f6("\x1B[90m", "\x1B[39m"),
redBright: f6("\x1B[91m", "\x1B[39m"),
greenBright: f6("\x1B[92m", "\x1B[39m"),
yellowBright: f6("\x1B[93m", "\x1B[39m"),
blueBright: f6("\x1B[94m", "\x1B[39m"),
magentaBright: f6("\x1B[95m", "\x1B[39m"),
cyanBright: f6("\x1B[96m", "\x1B[39m"),
whiteBright: f6("\x1B[97m", "\x1B[39m"),
bgBlackBright: f6("\x1B[100m", "\x1B[49m"),
bgRedBright: f6("\x1B[101m", "\x1B[49m"),
bgGreenBright: f6("\x1B[102m", "\x1B[49m"),
bgYellowBright: f6("\x1B[103m", "\x1B[49m"),
bgBlueBright: f6("\x1B[104m", "\x1B[49m"),
bgMagentaBright: f6("\x1B[105m", "\x1B[49m"),
bgCyanBright: f6("\x1B[106m", "\x1B[49m"),
bgWhiteBright: f6("\x1B[107m", "\x1B[49m")
};
}, "createColors");
module3.exports = createColors();
module3.exports.createColors = createColors;
}
});
// ../../node_modules/.pnpm/@clack+core@0.3.2/node_modules/@clack/core/dist/index.mjs
function z({ onlyFirst: t7 = false } = {}) {
const u5 = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");
return new RegExp(u5, t7 ? void 0 : "g");
}
function $(t7) {
if (typeof t7 != "string") throw new TypeError(`Expected a \`string\`, got \`${typeof t7}\``);
return t7.replace(z(), "");
}
function c(t7, u5 = {}) {
if (typeof t7 != "string" || t7.length === 0 || (u5 = { ambiguousIsNarrow: true, ...u5 }, t7 = $(t7), t7.length === 0)) return 0;
t7 = t7.replace(Y(), " ");
const F3 = u5.ambiguousIsNarrow ? 1 : 2;
let e7 = 0;
for (const s5 of t7) {
const C3 = s5.codePointAt(0);
if (C3 <= 31 || C3 >= 127 && C3 <= 159 || C3 >= 768 && C3 <= 879) continue;
switch (K.eastAsianWidth(s5)) {
case "F":
case "W":
e7 += 2;
break;
case "A":
e7 += F3;
break;
default:
e7 += 1;
}
}
return e7;
}
function U() {
const t7 = /* @__PURE__ */ new Map();
for (const [u5, F3] of Object.entries(r)) {
for (const [e7, s5] of Object.entries(F3)) r[e7] = { open: `\x1B[${s5[0]}m`, close: `\x1B[${s5[1]}m` }, F3[e7] = r[e7], t7.set(s5[0], s5[1]);
Object.defineProperty(r, u5, { value: F3, enumerable: false });
}
return Object.defineProperty(r, "codes", { value: t7, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = L(), r.color.ansi256 = M(), r.color.ansi16m = T(), r.bgColor.ansi = L(v), r.bgColor.ansi256 = M(v), r.bgColor.ansi16m = T(v), Object.defineProperties(r, { rgbToAnsi256: { value: /* @__PURE__ */ __name((u5, F3, e7) => u5 === F3 && F3 === e7 ? u5 < 8 ? 16 : u5 > 248 ? 231 : Math.round((u5 - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u5 / 255 * 5) + 6 * Math.round(F3 / 255 * 5) + Math.round(e7 / 255 * 5), "value"), enumerable: false }, hexToRgb: { value: /* @__PURE__ */ __name((u5) => {
const F3 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u5.toString(16));
if (!F3) return [0, 0, 0];
let [e7] = F3;
e7.length === 3 && (e7 = [...e7].map((C3) => C3 + C3).join(""));
const s5 = Number.parseInt(e7, 16);
return [s5 >> 16 & 255, s5 >> 8 & 255, s5 & 255];
}, "value"), enumerable: false }, hexToAnsi256: { value: /* @__PURE__ */ __name((u5) => r.rgbToAnsi256(...r.hexToRgb(u5)), "value"), enumerable: false }, ansi256ToAnsi: { value: /* @__PURE__ */ __name((u5) => {
if (u5 < 8) return 30 + u5;
if (u5 < 16) return 90 + (u5 - 8);
let F3, e7, s5;
if (u5 >= 232) F3 = ((u5 - 232) * 10 + 8) / 255, e7 = F3, s5 = F3;
else {
u5 -= 16;
const i5 = u5 % 36;
F3 = Math.floor(u5 / 36) / 5, e7 = Math.floor(i5 / 6) / 5, s5 = i5 % 6 / 5;
}
const C3 = Math.max(F3, e7, s5) * 2;
if (C3 === 0) return 30;
let D3 = 30 + (Math.round(s5) << 2 | Math.round(e7) << 1 | Math.round(F3));
return C3 === 2 && (D3 += 60), D3;
}, "value"), enumerable: false }, rgbToAnsi: { value: /* @__PURE__ */ __name((u5, F3, e7) => r.ansi256ToAnsi(r.rgbToAnsi256(u5, F3, e7)), "value"), enumerable: false }, hexToAnsi: { value: /* @__PURE__ */ __name((u5) => r.ansi256ToAnsi(r.hexToAnsi256(u5)), "value"), enumerable: false } }), r;
}
function P(t7, u5, F3) {
return String(t7).normalize().replace(/\r\n/g, `
`).split(`
`).map((e7) => uD(e7, u5, F3)).join(`
`);
}
function FD(t7, u5) {
if (t7 === u5) return;
const F3 = t7.split(`
`), e7 = u5.split(`
`), s5 = [];
for (let C3 = 0; C3 < Math.max(F3.length, e7.length); C3++) F3[C3] !== e7[C3] && s5.push(C3);
return s5;
}
function eD(t7) {
return t7 === R;
}
function g(t7, u5) {
t7.isTTY && t7.setRawMode(u5);
}
var import_sisteransi, import_node_process2, f, import_node_readline, import_node_tty2, import_picocolors, m, G, K, Y, v, L, M, T, r, Z, H, q, p, J, b, W, Q, I, w, N, j, X, _2, DD, uD, R, V, tD, h, sD, iD, ED, oD;
var init_dist = __esm({
"../../node_modules/.pnpm/@clack+core@0.3.2/node_modules/@clack/core/dist/index.mjs"() {
init_import_meta_url();
import_sisteransi = __toESM(require_src(), 1);
import_node_process2 = require("process");
f = __toESM(require("readline"), 1);
import_node_readline = __toESM(require("readline"), 1);
import_node_tty2 = require("tty");
import_picocolors = __toESM(require_picocolors(), 1);
__name(z, "z");
__name($, "$");
m = {};
G = { get exports() {
return m;
}, set exports(t7) {
m = t7;
} };
(function(t7) {
var u5 = {};
t7.exports = u5, u5.eastAsianWidth = function(e7) {
var s5 = e7.charCodeAt(0), C3 = e7.length == 2 ? e7.charCodeAt(1) : 0, D3 = s5;
return 55296 <= s5 && s5 <= 56319 && 56320 <= C3 && C3 <= 57343 && (s5 &= 1023, C3 &= 1023, D3 = s5 << 10 | C3, D3 += 65536), D3 == 12288 || 65281 <= D3 && D3 <= 65376 || 65504 <= D3 && D3 <= 65510 ? "F" : D3 == 8361 || 65377 <= D3 && D3 <= 65470 || 65474 <= D3 && D3 <= 65479 || 65482 <= D3 && D3 <= 65487 || 65490 <= D3 && D3 <= 65495 || 65498 <= D3 && D3 <= 65500 || 65512 <= D3 && D3 <= 65518 ? "H" : 4352 <= D3 && D3 <= 4447 || 4515 <= D3 && D3 <= 4519 || 4602 <= D3 && D3 <= 4607 || 9001 <= D3 && D3 <= 9002 || 11904 <= D3 && D3 <= 11929 || 11931 <= D3 && D3 <= 12019 || 12032 <= D3 && D3 <= 12245 || 12272 <= D3 && D3 <= 12283 || 12289 <= D3 && D3 <= 12350 || 12353 <= D3 && D3 <= 12438 || 12441 <= D3 && D3 <= 12543 || 12549 <= D3 && D3 <= 12589 || 12593 <= D3 && D3 <= 12686 || 12688 <= D3 && D3 <= 12730 || 12736 <= D3 && D3 <= 12771 || 12784 <= D3 && D3 <= 12830 || 12832 <= D3 && D3 <= 12871 || 12880 <= D3 && D3 <= 13054 || 13056 <= D3 && D3 <= 19903 || 19968 <= D3 && D3 <= 42124 || 42128 <= D3 && D3 <= 42182 || 43360 <= D3 && D3 <= 43388 || 44032 <= D3 && D3 <= 55203 || 55216 <= D3 && D3 <= 55238 || 55243 <= D3 && D3 <= 55291 || 63744 <= D3 && D3 <= 64255 || 65040 <= D3 && D3 <= 65049 || 65072 <= D3 && D3 <= 65106 || 65108 <= D3 && D3 <= 65126 || 65128 <= D3 && D3 <= 65131 || 110592 <= D3 && D3 <= 110593 || 127488 <= D3 && D3 <= 127490 || 127504 <= D3 && D3 <= 127546 || 127552 <= D3 && D3 <= 127560 || 127568 <= D3 && D3 <= 127569 || 131072 <= D3 && D3 <= 194367 || 177984 <= D3 && D3 <= 196605 || 196608 <= D3 && D3 <= 262141 ? "W" : 32 <= D3 && D3 <= 126 || 162 <= D3 && D3 <= 163 || 165 <= D3 && D3 <= 166 || D3 == 172 || D3 == 175 || 10214 <= D3 && D3 <= 10221 || 10629 <= D3 && D3 <= 10630 ? "Na" : D3 == 161 || D3 == 164 || 167 <= D3 && D3 <= 168 || D3 == 170 || 173 <= D3 && D3 <= 174 || 176 <= D3 && D3 <= 180 || 182 <= D3 && D3 <= 186 || 188 <= D3 && D3 <= 191 || D3 == 198 || D3 == 208 || 215 <= D3 && D3 <= 216 || 222 <= D3 && D3 <= 225 || D3 == 230 || 232 <= D3 && D3 <= 234 || 236 <= D3 && D3 <= 237 || D3 == 240 || 242 <= D3 && D3 <= 243 || 247 <= D3 && D3 <= 250 || D3 == 252 || D3 == 254 || D3 == 257 || D3 == 273 || D3 == 275 || D3 == 283 || 294 <= D3 && D3 <= 295 || D3 == 299 || 305 <= D3 && D3 <= 307 || D3 == 312 || 319 <= D3 && D3 <= 322 || D3 == 324 || 328 <= D3 && D3 <= 331 || D3 == 333 || 338 <= D3 && D3 <= 339 || 358 <= D3 && D3 <= 359 || D3 == 363 || D3 == 462 || D3 == 464 || D3 == 466 || D3 == 468 || D3 == 470 || D3 == 472 || D3 == 474 || D3 == 476 || D3 == 593 || D3 == 609 || D3 == 708 || D3 == 711 || 713 <= D3 && D3 <= 715 || D3 == 717 || D3 == 720 || 728 <= D3 && D3 <= 731 || D3 == 733 || D3 == 735 || 768 <= D3 && D3 <= 879 || 913 <= D3 && D3 <= 929 || 931 <= D3 && D3 <= 937 || 945 <= D3 && D3 <= 961 || 963 <= D3 && D3 <= 969 || D3 == 1025 || 1040 <= D3 && D3 <= 1103 || D3 == 1105 || D3 == 8208 || 8211 <= D3 && D3 <= 8214 || 8216 <= D3 && D3 <= 8217 || 8220 <= D3 && D3 <= 8221 || 8224 <= D3 && D3 <= 8226 || 8228 <= D3 && D3 <= 8231 || D3 == 8240 || 8242 <= D3 && D3 <= 8243 || D3 == 8245 || D3 == 8251 || D3 == 8254 || D3 == 8308 || D3 == 8319 || 8321 <= D3 && D3 <= 8324 || D3 == 8364 || D3 == 8451 || D3 == 8453 || D3 == 8457 || D3 == 8467 || D3 == 8470 || 8481 <= D3 && D3 <= 8482 || D3 == 8486 || D3 == 8491 || 8531 <= D3 && D3 <= 8532 || 8539 <= D3 && D3 <= 8542 || 8544 <= D3 && D3 <= 8555 || 8560 <= D3 && D3 <= 8569 || D3 == 8585 || 8592 <= D3 && D3 <= 8601 || 8632 <= D3 && D3 <= 8633 || D3 == 8658 || D3 == 8660 || D3 == 8679 || D3 == 8704 || 8706 <= D3 && D3 <= 8707 || 8711 <= D3 && D3 <= 8712 || D3 == 8715 || D3 == 8719 || D3 == 8721 || D3 == 8725 || D3 == 8730 || 8733 <= D3 && D3 <= 8736 || D3 == 8739 || D3 == 8741 || 8743 <= D3 && D3 <= 8748 || D3 == 8750 || 8756 <= D3 && D3 <= 8759 || 8764 <= D3 && D3 <= 8765 || D3 == 8776 || D3 == 8780 || D3 == 8786 || 8800 <= D3 && D3 <= 8801 || 8804 <= D3 && D3 <= 8807 || 8810 <= D3 && D3 <= 8811 || 8814 <= D3 && D3 <= 8815 || 8834 <= D3 && D3 <= 8835 || 8838 <= D3 && D3 <= 8839 || D3 == 8853 || D3 == 8857 || D3 == 8869 || D3 == 8895 || D3 == 8978 || 9312 <= D3 && D3 <= 9449 || 9451 <= D3 && D3 <= 9547 || 9552 <= D3 && D3 <= 9587 || 9600 <= D3 && D3 <= 9615 || 9618 <= D3 && D3 <= 9621 || 9632 <= D3 && D3 <= 9633 || 9635 <= D3 && D3 <= 9641 || 9650 <= D3 && D3 <= 9651 || 9654 <= D3 && D3 <= 9655 || 9660 <= D3 && D3 <= 9661 || 9664 <= D3 && D3 <= 9665 || 9670 <= D3 && D3 <= 9672 || D3 == 9675 || 9678 <= D3 && D3 <= 9681 || 9698 <= D3 && D3 <= 9701 || D3 == 9711 || 9733 <= D3 && D3 <= 9734 || D3 == 9737 || 9742 <= D3 && D3 <= 9743 || 9748 <= D3 && D3 <= 9749 || D3 == 9756 || D3 == 9758 || D3 == 9792 || D3 == 9794 || 9824 <= D3 && D3 <= 9825 || 9827 <= D3 && D3 <= 9829 || 9831 <= D3 && D3 <= 9834 || 9836 <= D3 && D3 <= 9837 || D3 == 9839 || 9886 <= D3 && D3 <= 9887 || 9918 <= D3 && D3 <= 9919 || 9924 <= D3 && D3 <= 9933 || 9935 <= D3 && D3 <= 9953 || D3 == 9955 || 9960 <= D3 && D3 <= 9983 || D3 == 10045 || D3 == 10071 || 10102 <= D3 && D3 <= 10111 || 11093 <= D3 && D3 <= 11097 || 12872 <= D3 && D3 <= 12879 || 57344 <= D3 && D3 <= 63743 || 65024 <= D3 && D3 <= 65039 || D3 == 65533 || 127232 <= D3 && D3 <= 127242 || 127248 <= D3 && D3 <= 127277 || 127280 <= D3 && D3 <= 127337 || 127344 <= D3 && D3 <= 127386 || 917760 <= D3 && D3 <= 917999 || 983040 <= D3 && D3 <= 1048573 || 1048576 <= D3 && D3 <= 1114109 ? "A" : "N";
}, u5.characterLength = function(e7) {
var s5 = this.eastAsianWidth(e7);
return s5 == "F" || s5 == "W" || s5 == "A" ? 2 : 1;
};
function F3(e7) {
return e7.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
}
__name(F3, "F");
u5.length = function(e7) {
for (var s5 = F3(e7), C3 = 0, D3 = 0; D3 < s5.length; D3++) C3 = C3 + this.characterLength(s5[D3]);
return C3;
}, u5.slice = function(e7, s5, C3) {
textLen = u5.length(e7), s5 = s5 || 0, C3 = C3 || 1, s5 < 0 && (s5 = textLen + s5), C3 < 0 && (C3 = textLen + C3);
for (var D3 = "", i5 = 0, o5 = F3(e7), E3 = 0; E3 < o5.length; E3++) {
var a5 = o5[E3], n6 = u5.length(a5);
if (i5 >= s5 - (n6 == 2 ? 1 : 0)) if (i5 + n6 <= C3) D3 += a5;
else break;
i5 += n6;
}
return D3;
};
})(G);
K = m;
Y = /* @__PURE__ */ __name(function() {
return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
}, "Y");
__name(c, "c");
v = 10;
L = /* @__PURE__ */ __name((t7 = 0) => (u5) => `\x1B[${u5 + t7}m`, "L");
M = /* @__PURE__ */ __name((t7 = 0) => (u5) => `\x1B[${38 + t7};5;${u5}m`, "M");
T = /* @__PURE__ */ __name((t7 = 0) => (u5, F3, e7) => `\x1B[${38 + t7};2;${u5};${F3};${e7}m`, "T");
r = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
Object.keys(r.modifier);
Z = Object.keys(r.color);
H = Object.keys(r.bgColor);
[...Z, ...H];
__name(U, "U");
q = U();
p = /* @__PURE__ */ new Set(["\x1B", "\x9B"]);
J = 39;
b = "\x07";
W = "[";
Q = "]";
I = "m";
w = `${Q}8;;`;
N = /* @__PURE__ */ __name((t7) => `${p.values().next().value}${W}${t7}${I}`, "N");
j = /* @__PURE__ */ __name((t7) => `${p.values().next().value}${w}${t7}${b}`, "j");
X = /* @__PURE__ */ __name((t7) => t7.split(" ").map((u5) => c(u5)), "X");
_2 = /* @__PURE__ */ __name((t7, u5, F3) => {
const e7 = [...u5];
let s5 = false, C3 = false, D3 = c($(t7[t7.length - 1]));
for (const [i5, o5] of e7.entries()) {
const E3 = c(o5);
if (D3 + E3 <= F3 ? t7[t7.length - 1] += o5 : (t7.push(o5), D3 = 0), p.has(o5) && (s5 = true, C3 = e7.slice(i5 + 1).join("").startsWith(w)), s5) {
C3 ? o5 === b && (s5 = false, C3 = false) : o5 === I && (s5 = false);
continue;
}
D3 += E3, D3 === F3 && i5 < e7.length - 1 && (t7.push(""), D3 = 0);
}
!D3 && t7[t7.length - 1].length > 0 && t7.length > 1 && (t7[t7.length - 2] += t7.pop());
}, "_");
DD = /* @__PURE__ */ __name((t7) => {
const u5 = t7.split(" ");
let F3 = u5.length;
for (; F3 > 0 && !(c(u5[F3 - 1]) > 0); ) F3--;
return F3 === u5.length ? t7 : u5.slice(0, F3).join(" ") + u5.slice(F3).join("");
}, "DD");
uD = /* @__PURE__ */ __name((t7, u5, F3 = {}) => {
if (F3.trim !== false && t7.trim() === "") return "";
let e7 = "", s5, C3;
const D3 = X(t7);
let i5 = [""];
for (const [E3, a5] of t7.split(" ").entries()) {
F3.trim !== false && (i5[i5.length - 1] = i5[i5.length - 1].trimStart());
let n6 = c(i5[i5.length - 1]);
if (E3 !== 0 && (n6 >= u5 && (F3.wordWrap === false || F3.trim === false) && (i5.push(""), n6 = 0), (n6 > 0 || F3.trim === false) && (i5[i5.length - 1] += " ", n6++)), F3.hard && D3[E3] > u5) {
const B3 = u5 - n6, A3 = 1 + Math.floor((D3[E3] - B3 - 1) / u5);
Math.floor((D3[E3] - 1) / u5) < A3 && i5.push(""), _2(i5, a5, u5);
continue;
}
if (n6 + D3[E3] > u5 && n6 > 0 && D3[E3] > 0) {
if (F3.wordWrap === false && n6 < u5) {
_2(i5, a5, u5);
continue;
}
i5.push("");
}
if (n6 + D3[E3] > u5 && F3.wordWrap === false) {
_2(i5, a5, u5);
continue;
}
i5[i5.length - 1] += a5;
}
F3.trim !== false && (i5 = i5.map((E3) => DD(E3)));
const o5 = [...i5.join(`
`)];
for (const [E3, a5] of o5.entries()) {
if (e7 += a5, p.has(a5)) {
const { groups: B3 } = new RegExp(`(?:\\${W}(?<code>\\d+)m|\\${w}(?<uri>.*)${b})`).exec(o5.slice(E3).join("")) || { groups: {} };
if (B3.code !== void 0) {
const A3 = Number.parseFloat(B3.code);
s5 = A3 === J ? void 0 : A3;
} else B3.uri !== void 0 && (C3 = B3.uri.length === 0 ? void 0 : B3.uri);
}
const n6 = q.codes.get(Number(s5));
o5[E3 + 1] === `
` ? (C3 && (e7 += j("")), s5 && n6 && (e7 += N(n6))) : a5 === `
` && (s5 && n6 && (e7 += N(s5)), C3 && (e7 += j(C3)));
}
return e7;
}, "uD");
__name(P, "P");
__name(FD, "FD");
R = Symbol("clack:cancel");
__name(eD, "eD");
__name(g, "g");
V = /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"]]);
tD = /* @__PURE__ */ new Set(["up", "down", "left", "right", "space", "enter"]);
h = class {
static {
__name(this, "h");
}
constructor({ render: u5, input: F3 = import_node_process2.stdin, output: e7 = import_node_process2.stdout, ...s5 }, C3 = true) {
this._track = false, this._cursor = 0, this.state = "initial", this.error = "", this.subscribers = /* @__PURE__ */ new Map(), this._prevFrame = "", this.opts = s5, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = u5.bind(this), this._track = C3, this.input = F3, this.output = e7;
}
prompt() {
const u5 = new import_node_tty2.WriteStream(0);
return u5._write = (F3, e7, s5) => {
this._track && (this.value = this.rl.line.replace(/\t/g, ""), this._cursor = this.rl.cursor, this.emit("value", this.value)), s5();
}, this.input.pipe(u5), this.rl = import_node_readline.default.createInterface({ input: this.input, output: u5, tabSize: 2, prompt: "", escapeCodeTimeout: 50 }), import_node_readline.default.emitKeypressEvents(this.input, this.rl), this.rl.prompt(), this.opts.initialValue !== void 0 && this._track && this.rl.write(this.opts.initialValue), this.input.on("keypress", this.onKeypress), g(this.input, true), this.output.on("resize", this.render), this.render(), new Promise((F3, e7) => {
this.once("submit", () => {
this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), g(this.input, false), F3(this.value);
}), this.once("cancel", () => {
this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), g(this.input, false), F3(R);
});
});
}
on(u5, F3) {
const e7 = this.subscribers.get(u5) ?? [];
e7.push({ cb: F3 }), this.subscribers.set(u5, e7);
}
once(u5, F3) {
const e7 = this.subscribers.get(u5) ?? [];
e7.push({ cb: F3, once: true }), this.subscribers.set(u5, e7);
}
emit(u5, ...F3) {
const e7 = this.subscribers.get(u5) ?? [], s5 = [];
for (const C3 of e7) C3.cb(...F3), C3.once && s5.push(() => e7.splice(e7.indexOf(C3), 1));
for (const C3 of s5) C3();
}
unsubscribe() {
this.subscribers.clear();
}
onKeypress(u5, F3) {
if (this.state === "error" && (this.state = "active"), F3?.name && !this._track && V.has(F3.name) && this.emit("cursor", V.get(F3.name)), F3?.name && tD.has(F3.name) && this.emit("cursor", F3.name), u5 && (u5.toLowerCase() === "y" || u5.toLowerCase() === "n") && this.emit("confirm", u5.toLowerCase() === "y"), u5 && this.emit("key", u5.toLowerCase()), F3?.name === "return") {
if (this.opts.validate) {
const e7 = this.opts.validate(this.value);
e7 && (this.error = e7, this.state = "error", this.rl.write(this.value));
}
this.state !== "error" && (this.state = "submit");
}
u5 === "" && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
}
close() {
this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
`), g(this.input, false), this.rl.close(), this.emit(`${this.state}`, this.value), this.unsubscribe();
}
restoreCursor() {
const u5 = P(this._prevFrame, process.stdout.columns, { hard: true }).split(`
`).length - 1;
this.output.write(import_sisteransi.cursor.move(-999, u5 * -1));
}
render() {
const u5 = P(this._render(this) ?? "", process.stdout.columns, { hard: true });
if (u5 !== this._prevFrame) {
if (this.state === "initial") this.output.write(import_sisteransi.cursor.hide);
else {
const F3 = FD(this._prevFrame, u5);
if (this.restoreCursor(), F3 && F3?.length === 1) {
const e7 = F3[0];
this.output.write(import_sisteransi.cursor.move(0, e7)), this.output.write(import_sisteransi.erase.lines(1));
const s5 = u5.split(`
`);
this.output.write(s5[e7]), this._prevFrame = u5, this.output.write(import_sisteransi.cursor.move(0, s5.length - e7 - 1));
return;
} else if (F3 && F3?.length > 1) {
const e7 = F3[0];
this.output.write(import_sisteransi.cursor.move(0, e7)), this.output.write(import_sisteransi.erase.down());
const C3 = u5.split(`
`).slice(e7);
this.output.write(C3.join(`
`)), this._prevFrame = u5;
return;
}
this.output.write(import_sisteransi.erase.down());
}
this.output.write(u5), this.state === "initial" && (this.state = "active"), this._prevFrame = u5;
}
}
};
sD = class extends h {
static {
__name(this, "sD");
}
get cursor() {
return this.value ? 0 : 1;
}
get _value() {
return this.cursor === 0;
}
constructor(u5) {
super(u5, false), this.value = !!u5.initialValue, this.on("value", () => {
this.value = this._value;
}), this.on("confirm", (F3) => {
this.output.write(import_sisteransi.cursor.move(0, -1)), this.value = F3, this.state = "submit", this.close();
}), this.on("cursor", () => {
this.value = !this.value;
});
}
};
iD = class extends h {
static {
__name(this, "iD");
}
constructor(u5) {
super(u5, false), this.cursor = 0, this.options = u5.options, this.value = [...u5.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: F3 }) => F3 === u5.cursorAt), 0), this.on("key", (F3) => {
F3 === "a" && this.toggleAll();
}), this.on("cursor", (F3) => {
switch (F3) {
case "left":
case "up":
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
break;
case "down":
case "right":
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
break;
case "space":
this.toggleValue();
break;
}
});
}
get _value() {
return this.options[this.cursor].value;
}
toggleAll() {
const u5 = this.value.length === this.options.length;
this.value = u5 ? [] : this.options.map((F3) => F3.value);
}
toggleValue() {
const u5 = this.value.includes(this._value);
this.value = u5 ? this.value.filter((F3) => F3 !== this._value) : [...this.value, this._value];
}
};
ED = class extends h {
static {
__name(this, "ED");
}
constructor(u5) {
super(u5, false), this.cursor = 0, this.options = u5.options, this.cursor = this.options.findIndex(({ value: F3 }) => F3 === u5.initialValue), this.cursor === -1 && (this.cursor = 0), this.changeValue(), this.on("cursor", (F3) => {
switch (F3) {
case "left":
case "up":
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
break;
case "down":
case "right":
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
break;
}
this.changeValue();
});
}
get _value() {
return this.options[this.cursor];
}
changeValue() {
this.value = this._value.value;
}
};
oD = class extends h {
static {
__name(this, "oD");
}
constructor(u5) {
super(u5), this.valueWithCursor = "", this.on("finalize", () => {
this.value || (this.value = u5.defaultValue), this.valueWithCursor = this.value;
}), this.on("value", () => {
if (this.cursor >= this.value.length) this.valueWithCursor = `${this.value}${import_picocolors.default.inverse(import_picocolors.default.hidden("_"))}`;
else {
const F3 = this.value.slice(0, this.cursor), e7 = this.value.slice(this.cursor);
this.valueWithCursor = `${F3}${import_picocolors.default.inverse(e7[0])}${e7.slice(1)}`;
}
});
}
get cursor() {
return this._cursor;
}
};
}
});
// ../../node_modules/.pnpm/ansi-escapes@5.0.0/node_modules/ansi-escapes/index.js
var ESC, OSC, BEL, SEP, isTerminalApp, ansiEscapes, ansi_escapes_default;
var init_ansi_escapes = __esm({
"../../node_modules/.pnpm/ansi-escapes@5.0.0/node_modules/ansi-escapes/index.js"() {
init_import_meta_url();
ESC = "\x1B[";
OSC = "\x1B]";
BEL = "\x07";
SEP = ";";
isTerminalApp = process.env.TERM_PROGRAM === "Apple_Terminal";
ansiEscapes = {};
ansiEscapes.cursorTo = (x6, y4) => {
if (typeof x6 !== "number") {
throw new TypeError("The `x` argument is required");
}
if (typeof y4 !== "number") {
return ESC + (x6 + 1) + "G";
}
return ESC + (y4 + 1) + ";" + (x6 + 1) + "H";
};
ansiEscapes.cursorMove = (x6, y4) => {
if (typeof x6 !== "number") {
throw new TypeError("The `x` argument is required");
}
let returnValue = "";
if (x6 < 0) {
returnValue += ESC + -x6 + "D";
} else if (x6 > 0) {
returnValue += ESC + x6 + "C";
}
if (y4 < 0) {
returnValue += ESC + -y4 + "A";
} else if (y4 > 0) {
returnValue += ESC + y4 + "B";
}
return returnValue;
};
ansiEscapes.cursorUp = (count = 1) => ESC + count + "A";
ansiEscapes.cursorDown = (count = 1) => ESC + count + "B";
ansiEscapes.cursorForward = (count = 1) => ESC + count + "C";
ansiEscapes.cursorBackward = (count = 1) => ESC + count + "D";
ansiEscapes.cursorLeft = ESC + "G";
ansiEscapes.cursorSavePosition = isTerminalApp ? "\x1B7" : ESC + "s";
ansiEscapes.cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC + "u";
ansiEscapes.cursorGetPosition = ESC + "6n";
ansiEscapes.cursorNextLine = ESC + "E";
ansiEscapes.cursorPrevLine = ESC + "F";
ansiEscapes.cursorHide = ESC + "?25l";
ansiEscapes.cursorShow = ESC + "?25h";
ansiEscapes.eraseLines = (count) => {
let clear = "";
for (let i5 = 0; i5 < count; i5++) {
clear += ansiEscapes.eraseLine + (i5 < count - 1 ? ansiEscapes.cursorUp() : "");
}
if (count) {
clear += ansiEscapes.cursorLeft;
}
return clear;
};
ansiEscapes.eraseEndLine = ESC + "K";
ansiEscapes.eraseStartLine = ESC + "1K";
ansiEscapes.eraseLine = ESC + "2K";
ansiEscapes.eraseDown = ESC + "J";
ansiEscapes.eraseUp = ESC + "1J";
ansiEscapes.eraseScreen = ESC + "2J";
ansiEscapes.scrollUp = ESC + "S";
ansiEscapes.scrollDown = ESC + "T";
ansiEscapes.clearScreen = "\x1Bc";
ansiEscapes.clearTerminal = process.platform === "win32" ? `${ansiEscapes.eraseScreen}${ESC}0f` : (
// 1. Erases the screen (Only done in case `2` is not supported)
// 2. Erases the whole screen including scrollback buffer
// 3. Moves cursor to the top-left position
// More info: https://www.real-world-systems.com/docs/ANSIcode.html
`${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`
);
ansiEscapes.beep = BEL;
ansiEscapes.link = (text, url4) => {
return [
OSC,
"8",
SEP,
SEP,
url4,
BEL,
text,
OSC,
"8",
SEP,
SEP,
BEL
].join("");
};
ansiEscapes.image = (buffer, options = {}) => {
let returnValue = `${OSC}1337;File=inline=1`;
if (options.width) {
returnValue += `;width=${options.width}`;
}
if (options.height) {
returnValue += `;height=${options.height}`;
}
if (options.preserveAspectRatio === false) {
returnValue += ";preserveAspectRatio=0";
}
return returnValue + ":" + buffer.toString("base64") + BEL;
};
ansiEscapes.iTerm = {
setCwd: /* @__PURE__ */ __name((cwd2 = process.cwd()) => `${OSC}50;CurrentDir=${cwd2}${BEL}`, "setCwd"),
annotation: /* @__PURE__ */ __name((message, options = {}) => {
let returnValue = `${OSC}1337;`;
const hasX = typeof options.x !== "undefined";
const hasY = typeof options.y !== "undefined";
if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== "undefined")) {
throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
}
message = message.replace(/\|/g, "");
returnValue += options.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
if (options.length > 0) {
returnValue += (hasX ? [message, options.length, options.x, options.y] : [options.length, message]).join("|");
} else {
returnValue += message;
}
return returnValue + BEL;
}, "annotation")
};
ansi_escapes_default = ansiEscapes;
}
});
// ../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js
var require_mimic_fn = __commonJS({
"../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var mimicFn = /* @__PURE__ */ __name((to, from) => {
for (const prop of Reflect.ownKeys(from)) {
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
}
return to;
}, "mimicFn");
module3.exports = mimicFn;
module3.exports.default = mimicFn;
}
});
// ../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js
var require_onetime = __commonJS({
"../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var mimicFn = require_mimic_fn();
var calledFunctions2 = /* @__PURE__ */ new WeakMap();
var onetime3 = /* @__PURE__ */ __name((function_, options = {}) => {
if (typeof function_ !== "function") {
throw new TypeError("Expected a function");
}
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || "<anonymous>";
const onetime4 = /* @__PURE__ */ __name(function(...arguments_) {
calledFunctions2.set(onetime4, ++callCount);
if (callCount === 1) {
returnValue = function_.apply(this, arguments_);
function_ = null;
} else if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
}
return returnValue;
}, "onetime");
mimicFn(onetime4, function_);
calledFunctions2.set(onetime4, callCount);
return onetime4;
}, "onetime");
module3.exports = onetime3;
module3.exports.default = onetime3;
module3.exports.callCount = (function_) => {
if (!calledFunctions2.has(function_)) {
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions2.get(function_);
};
}
});
// ../../node_modules/.pnpm/restore-cursor@4.0.0/node_modules/restore-cursor/index.js
var import_node_process3, import_onetime, import_signal_exit2, restoreCursor, restore_cursor_default;
var init_restore_cursor = __esm({
"../../node_modules/.pnpm/restore-cursor@4.0.0/node_modules/restore-cursor/index.js"() {
init_import_meta_url();
import_node_process3 = __toESM(require("process"), 1);
import_onetime = __toESM(require_onetime(), 1);
import_signal_exit2 = __toESM(require_signal_exit(), 1);
restoreCursor = (0, import_onetime.default)(() => {
(0, import_signal_exit2.default)(() => {
import_node_process3.default.stderr.write("\x1B[?25h");
}, { alwaysLast: true });
});
restore_cursor_default = restoreCursor;
}
});
// ../../node_modules/.pnpm/cli-cursor@4.0.0/node_modules/cli-cursor/index.js
var import_node_process4, isHidden, cliCursor, cli_cursor_default;
var init_cli_cursor = __esm({
"../../node_modules/.pnpm/cli-cursor@4.0.0/node_modules/cli-cursor/index.js"() {
init_import_meta_url();
import_node_process4 = __toESM(require("process"), 1);
init_restore_cursor();
isHidden = false;
cliCursor = {};
cliCursor.show = (writableStream = import_node_process4.default.stderr) => {
if (!writableStream.isTTY) {
return;
}
isHidden = false;
writableStream.write("\x1B[?25h");
};
cliCursor.hide = (writableStream = import_node_process4.default.stderr) => {
if (!writableStream.isTTY) {
return;
}
restore_cursor_default();
isHidden = true;
writableStream.write("\x1B[?25l");
};
cliCursor.toggle = (force, writableStream) => {
if (force !== void 0) {
isHidden = force;
}
if (isHidden) {
cliCursor.show(writableStream);
} else {
cliCursor.hide(writableStream);
}
};
cli_cursor_default = cliCursor;
}
});
// ../../node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js
var require_eastasianwidth = __commonJS({
"../../node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js"(exports2, module3) {
init_import_meta_url();
var eaw = {};
if ("undefined" == typeof module3) {
window.eastasianwidth = eaw;
} else {
module3.exports = eaw;
}
eaw.eastAsianWidth = function(character) {
var x6 = character.charCodeAt(0);
var y4 = character.length == 2 ? character.charCodeAt(1) : 0;
var codePoint = x6;
if (55296 <= x6 && x6 <= 56319 && (56320 <= y4 && y4 <= 57343)) {
x6 &= 1023;
y4 &= 1023;
codePoint = x6 << 10 | y4;
codePoint += 65536;
}
if (12288 == codePoint || 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510) {
return "F";
}
if (8361 == codePoint || 65377 <= codePoint && codePoint <= 65470 || 65474 <= codePoint && codePoint <= 65479 || 65482 <= codePoint && codePoint <= 65487 || 65490 <= codePoint && codePoint <= 65495 || 65498 <= codePoint && codePoint <= 65500 || 65512 <= codePoint && codePoint <= 65518) {
return "H";
}
if (4352 <= codePoint && codePoint <= 4447 || 4515 <= codePoint && codePoint <= 4519 || 4602 <= codePoint && codePoint <= 4607 || 9001 <= codePoint && codePoint <= 9002 || 11904 <= codePoint && codePoint <= 11929 || 11931 <= codePoint && codePoint <= 12019 || 12032 <= codePoint && codePoint <= 12245 || 12272 <= codePoint && codePoint <= 12283 || 12289 <= codePoint && codePoint <= 12350 || 12353 <= codePoint && codePoint <= 12438 || 12441 <= codePoint && codePoint <= 12543 || 12549 <= codePoint && codePoint <= 12589 || 12593 <= codePoint && codePoint <= 12686 || 12688 <= codePoint && codePoint <= 12730 || 12736 <= codePoint && codePoint <= 12771 || 12784 <= codePoint && codePoint <= 12830 || 12832 <= codePoint && codePoint <= 12871 || 12880 <= codePoint && codePoint <= 13054 || 13056 <= codePoint && codePoint <= 19903 || 19968 <= codePoint && codePoint <= 42124 || 42128 <= codePoint && codePoint <= 42182 || 43360 <= codePoint && codePoint <= 43388 || 44032 <= codePoint && codePoint <= 55203 || 55216 <= codePoint && codePoint <= 55238 || 55243 <= codePoint && codePoint <= 55291 || 63744 <= codePoint && codePoint <= 64255 || 65040 <= codePoint && codePoint <= 65049 || 65072 <= codePoint && codePoint <= 65106 || 65108 <= codePoint && codePoint <= 65126 || 65128 <= codePoint && codePoint <= 65131 || 110592 <= codePoint && codePoint <= 110593 || 127488 <= codePoint && codePoint <= 127490 || 127504 <= codePoint && codePoint <= 127546 || 127552 <= codePoint && codePoint <= 127560 || 127568 <= codePoint && codePoint <= 127569 || 131072 <= codePoint && codePoint <= 194367 || 177984 <= codePoint && codePoint <= 196605 || 196608 <= codePoint && codePoint <= 262141) {
return "W";
}
if (32 <= codePoint && codePoint <= 126 || 162 <= codePoint && codePoint <= 163 || 165 <= codePoint && codePoint <= 166 || 172 == codePoint || 175 == codePoint || 10214 <= codePoint && codePoint <= 10221 || 10629 <= codePoint && codePoint <= 10630) {
return "Na";
}
if (161 == codePoint || 164 == codePoint || 167 <= codePoint && codePoint <= 168 || 170 == codePoint || 173 <= codePoint && codePoint <= 174 || 176 <= codePoint && codePoint <= 180 || 182 <= codePoint && codePoint <= 186 || 188 <= codePoint && codePoint <= 191 || 198 == codePoint || 208 == codePoint || 215 <= codePoint && codePoint <= 216 || 222 <= codePoint && codePoint <= 225 || 230 == codePoint || 232 <= codePoint && codePoint <= 234 || 236 <= codePoint && codePoint <= 237 || 240 == codePoint || 242 <= codePoint && codePoint <= 243 || 247 <= codePoint && codePoint <= 250 || 252 == codePoint || 254 == codePoint || 257 == codePoint || 273 == codePoint || 275 == codePoint || 283 == codePoint || 294 <= codePoint && codePoint <= 295 || 299 == codePoint || 305 <= codePoint && codePoint <= 307 || 312 == codePoint || 319 <= codePoint && codePoint <= 322 || 324 == codePoint || 328 <= codePoint && codePoint <= 331 || 333 == codePoint || 338 <= codePoint && codePoint <= 339 || 358 <= codePoint && codePoint <= 359 || 363 == codePoint || 462 == codePoint || 464 == codePoint || 466 == codePoint || 468 == codePoint || 470 == codePoint || 472 == codePoint || 474 == codePoint || 476 == codePoint || 593 == codePoint || 609 == codePoint || 708 == codePoint || 711 == codePoint || 713 <= codePoint && codePoint <= 715 || 717 == codePoint || 720 == codePoint || 728 <= codePoint && codePoint <= 731 || 733 == codePoint || 735 == codePoint || 768 <= codePoint && codePoint <= 879 || 913 <= codePoint && codePoint <= 929 || 931 <= codePoint && codePoint <= 937 || 945 <= codePoint && codePoint <= 961 || 963 <= codePoint && codePoint <= 969 || 1025 == codePoint || 1040 <= codePoint && codePoint <= 1103 || 1105 == codePoint || 8208 == codePoint || 8211 <= codePoint && codePoint <= 8214 || 8216 <= codePoint && codePoint <= 8217 || 8220 <= codePoint && codePoint <= 8221 || 8224 <= codePoint && codePoint <= 8226 || 8228 <= codePoint && codePoint <= 8231 || 8240 == codePoint || 8242 <= codePoint && codePoint <= 8243 || 8245 == codePoint || 8251 == codePoint || 8254 == codePoint || 8308 == codePoint || 8319 == codePoint || 8321 <= codePoint && codePoint <= 8324 || 8364 == codePoint || 8451 == codePoint || 8453 == codePoint || 8457 == codePoint || 8467 == codePoint || 8470 == codePoint || 8481 <= codePoint && codePoint <= 8482 || 8486 == codePoint || 8491 == codePoint || 8531 <= codePoint && codePoint <= 8532 || 8539 <= codePoint && codePoint <= 8542 || 8544 <= codePoint && codePoint <= 8555 || 8560 <= codePoint && codePoint <= 8569 || 8585 == codePoint || 8592 <= codePoint && codePoint <= 8601 || 8632 <= codePoint && codePoint <= 8633 || 8658 == codePoint || 8660 == codePoint || 8679 == codePoint || 8704 == codePoint || 8706 <= codePoint && codePoint <= 8707 || 8711 <= codePoint && codePoint <= 8712 || 8715 == codePoint || 8719 == codePoint || 8721 == codePoint || 8725 == codePoint || 8730 == codePoint || 8733 <= codePoint && codePoint <= 8736 || 8739 == codePoint || 8741 == codePoint || 8743 <= codePoint && codePoint <= 8748 || 8750 == codePoint || 8756 <= codePoint && codePoint <= 8759 || 8764 <= codePoint && codePoint <= 8765 || 8776 == codePoint || 8780 == codePoint || 8786 == codePoint || 8800 <= codePoint && codePoint <= 8801 || 8804 <= codePoint && codePoint <= 8807 || 8810 <= codePoint && codePoint <= 8811 || 8814 <= codePoint && codePoint <= 8815 || 8834 <= codePoint && codePoint <= 8835 || 8838 <= codePoint && codePoint <= 8839 || 8853 == codePoint || 8857 == codePoint || 8869 == codePoint || 8895 == codePoint || 8978 == codePoint || 9312 <= codePoint && codePoint <= 9449 || 9451 <= codePoint && codePoint <= 9547 || 9552 <= codePoint && codePoint <= 9587 || 9600 <= codePoint && codePoint <= 9615 || 9618 <= codePoint && codePoint <= 9621 || 9632 <= codePoint && codePoint <= 9633 || 9635 <= codePoint && codePoint <= 9641 || 9650 <= codePoint && codePoint <= 9651 || 9654 <= codePoint && codePoint <= 9655 || 9660 <= codePoint && codePoint <= 9661 || 9664 <= codePoint && codePoint <= 9665 || 9670 <= codePoint && codePoint <= 9672 || 9675 == codePoint || 9678 <= codePoint && codePoint <= 9681 || 9698 <= codePoint && codePoint <= 9701 || 9711 == codePoint || 9733 <= codePoint && codePoint <= 9734 || 9737 == codePoint || 9742 <= codePoint && codePoint <= 9743 || 9748 <= codePoint && codePoint <= 9749 || 9756 == codePoint || 9758 == codePoint || 9792 == codePoint || 9794 == codePoint || 9824 <= codePoint && codePoint <= 9825 || 9827 <= codePoint && codePoint <= 9829 || 9831 <= codePoint && codePoint <= 9834 || 9836 <= codePoint && codePoint <= 9837 || 9839 == codePoint || 9886 <= codePoint && codePoint <= 9887 || 9918 <= codePoint && codePoint <= 9919 || 9924 <= codePoint && codePoint <= 9933 || 9935 <= codePoint && codePoint <= 9953 || 9955 == codePoint || 9960 <= codePoint && codePoint <= 9983 || 10045 == codePoint || 10071 == codePoint || 10102 <= codePoint && codePoint <= 10111 || 11093 <= codePoint && codePoint <= 11097 || 12872 <= codePoint && codePoint <= 12879 || 57344 <= codePoint && codePoint <= 63743 || 65024 <= codePoint && codePoint <= 65039 || 65533 == codePoint || 127232 <= codePoint && codePoint <= 127242 || 127248 <= codePoint && codePoint <= 127277 || 127280 <= codePoint && codePoint <= 127337 || 127344 <= codePoint && codePoint <= 127386 || 917760 <= codePoint && codePoint <= 917999 || 983040 <= codePoint && codePoint <= 1048573 || 1048576 <= codePoint && codePoint <= 1114109) {
return "A";
}
return "N";
};
eaw.characterLength = function(character) {
var code = this.eastAsianWidth(character);
if (code == "F" || code == "W" || code == "A") {
return 2;
} else {
return 1;
}
};
function stringToArray(string) {
return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
}
__name(stringToArray, "stringToArray");
eaw.length = function(string) {
var characters = stringToArray(string);
var len = 0;
for (var i5 = 0; i5 < characters.length; i5++) {
len = len + this.characterLength(characters[i5]);
}
return len;
};
eaw.slice = function(text, start, end) {
textLen = eaw.length(text);
start = start ? start : 0;
end = end ? end : 1;
if (start < 0) {
start = textLen + start;
}
if (end < 0) {
end = textLen + end;
}
var result = "";
var eawLen = 0;
var chars = stringToArray(text);
for (var i5 = 0; i5 < chars.length; i5++) {
var char = chars[i5];
var charLen = eaw.length(char);
if (eawLen >= start - (charLen == 2 ? 1 : 0)) {
if (eawLen + charLen <= end) {
result += char;
} else {
break;
}
}
eawLen += charLen;
}
return result;
};
}
});
// ../../node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js
var require_emoji_regex2 = __commonJS({
"../../node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = function() {
return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
};
}
});
// ../../node_modules/.pnpm/string-width@5.1.2/node_modules/string-width/index.js
function stringWidth(string, options = {}) {
if (typeof string !== "string" || string.length === 0) {
return 0;
}
options = {
ambiguousIsNarrow: true,
...options
};
string = stripAnsi2(string);
if (string.length === 0) {
return 0;
}
string = string.replace((0, import_emoji_regex.default)(), " ");
const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;
let width = 0;
for (const character of string) {
const codePoint = character.codePointAt(0);
if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
continue;
}
if (codePoint >= 768 && codePoint <= 879) {
continue;
}
const code = import_eastasianwidth.default.eastAsianWidth(character);
switch (code) {
case "F":
case "W":
width += 2;
break;
case "A":
width += ambiguousCharacterWidth;
break;
default:
width += 1;
}
}
return width;
}
var import_eastasianwidth, import_emoji_regex;
var init_string_width = __esm({
"../../node_modules/.pnpm/string-width@5.1.2/node_modules/string-width/index.js"() {
init_import_meta_url();
init_strip_ansi();
import_eastasianwidth = __toESM(require_eastasianwidth(), 1);
import_emoji_regex = __toESM(require_emoji_regex2(), 1);
__name(stringWidth, "stringWidth");
}
});
// ../../node_modules/.pnpm/ansi-styles@6.2.1/node_modules/ansi-styles/index.js
function assembleStyles2() {
const codes = /* @__PURE__ */ new Map();
for (const [groupName, group] of Object.entries(styles3)) {
for (const [styleName, style] of Object.entries(group)) {
styles3[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles3[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles3, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles3, "codes", {
value: codes,
enumerable: false
});
styles3.color.close = "\x1B[39m";
styles3.bgColor.close = "\x1B[49m";
styles3.color.ansi = wrapAnsi162();
styles3.color.ansi256 = wrapAnsi2562();
styles3.color.ansi16m = wrapAnsi16m2();
styles3.bgColor.ansi = wrapAnsi162(ANSI_BACKGROUND_OFFSET2);
styles3.bgColor.ansi256 = wrapAnsi2562(ANSI_BACKGROUND_OFFSET2);
styles3.bgColor.ansi16m = wrapAnsi16m2(ANSI_BACKGROUND_OFFSET2);
Object.defineProperties(styles3, {
rgbToAnsi256: {
value: /* @__PURE__ */ __name((red2, green2, blue2) => {
if (red2 === green2 && green2 === blue2) {
if (red2 < 8) {
return 16;
}
if (red2 > 248) {
return 231;
}
return Math.round((red2 - 8) / 247 * 24) + 232;
}
return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue2 / 255 * 5);
}, "value"),
enumerable: false
},
hexToRgb: {
value: /* @__PURE__ */ __name((hex) => {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map((character) => character + character).join("");
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
integer >> 16 & 255,
integer >> 8 & 255,
integer & 255
/* eslint-enable no-bitwise */
];
}, "value"),
enumerable: false
},
hexToAnsi256: {
value: /* @__PURE__ */ __name((hex) => styles3.rgbToAnsi256(...styles3.hexToRgb(hex)), "value"),
enumerable: false
},
ansi256ToAnsi: {
value: /* @__PURE__ */ __name((code) => {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red2;
let green2;
let blue2;
if (code >= 232) {
red2 = ((code - 232) * 10 + 8) / 255;
green2 = red2;
blue2 = red2;
} else {
code -= 16;
const remainder = code % 36;
red2 = Math.floor(code / 36) / 5;
green2 = Math.floor(remainder / 6) / 5;
blue2 = remainder % 6 / 5;
}
const value = Math.max(red2, green2, blue2) * 2;
if (value === 0) {
return 30;
}
let result = 30 + (Math.round(blue2) << 2 | Math.round(green2) << 1 | Math.round(red2));
if (value === 2) {
result += 60;
}
return result;
}, "value"),
enumerable: false
},
rgbToAnsi: {
value: /* @__PURE__ */ __name((red2, green2, blue2) => styles3.ansi256ToAnsi(styles3.rgbToAnsi256(red2, green2, blue2)), "value"),
enumerable: false
},
hexToAnsi: {
value: /* @__PURE__ */ __name((hex) => styles3.ansi256ToAnsi(styles3.hexToAnsi256(hex)), "value"),
enumerable: false
}
});
return styles3;
}
var ANSI_BACKGROUND_OFFSET2, wrapAnsi162, wrapAnsi2562, wrapAnsi16m2, styles3, modifierNames2, foregroundColorNames2, backgroundColorNames2, colorNames2, ansiStyles2, ansi_styles_default2;
var init_ansi_styles2 = __esm({
"../../node_modules/.pnpm/ansi-styles@6.2.1/node_modules/ansi-styles/index.js"() {
init_import_meta_url();
ANSI_BACKGROUND_OFFSET2 = 10;
wrapAnsi162 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
wrapAnsi2562 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
wrapAnsi16m2 = /* @__PURE__ */ __name((offset = 0) => (red2, green2, blue2) => `\x1B[${38 + offset};2;${red2};${green2};${blue2}m`, "wrapAnsi16m");
styles3 = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39],
// Alias of `blackBright`
grey: [90, 39],
// Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49],
// Alias of `bgBlackBright`
bgGrey: [100, 49],
// Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
modifierNames2 = Object.keys(styles3.modifier);
foregroundColorNames2 = Object.keys(styles3.color);
backgroundColorNames2 = Object.keys(styles3.bgColor);
colorNames2 = [...foregroundColorNames2, ...backgroundColorNames2];
__name(assembleStyles2, "assembleStyles");
ansiStyles2 = assembleStyles2();
ansi_styles_default2 = ansiStyles2;
}
});
// ../../node_modules/.pnpm/wrap-ansi@8.1.0/node_modules/wrap-ansi/index.js
function wrapAnsi(string, columns, options) {
return String(string).normalize().replace(/\r\n/g, "\n").split("\n").map((line) => exec(line, columns, options)).join("\n");
}
var ESCAPES, END_CODE, ANSI_ESCAPE_BELL, ANSI_CSI, ANSI_OSC, ANSI_SGR_TERMINATOR, ANSI_ESCAPE_LINK, wrapAnsiCode, wrapAnsiHyperlink, wordLengths, wrapWord, stringVisibleTrimSpacesRight, exec;
var init_wrap_ansi = __esm({
"../../node_modules/.pnpm/wrap-ansi@8.1.0/node_modules/wrap-ansi/index.js"() {
init_import_meta_url();
init_string_width();
init_strip_ansi();
init_ansi_styles2();
ESCAPES = /* @__PURE__ */ new Set([
"\x1B",
"\x9B"
]);
END_CODE = 39;
ANSI_ESCAPE_BELL = "\x07";
ANSI_CSI = "[";
ANSI_OSC = "]";
ANSI_SGR_TERMINATOR = "m";
ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
wrapAnsiCode = /* @__PURE__ */ __name((code) => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`, "wrapAnsiCode");
wrapAnsiHyperlink = /* @__PURE__ */ __name((uri) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`, "wrapAnsiHyperlink");
wordLengths = /* @__PURE__ */ __name((string) => string.split(" ").map((character) => stringWidth(character)), "wordLengths");
wrapWord = /* @__PURE__ */ __name((rows, word, columns) => {
const characters = [...word];
let isInsideEscape = false;
let isInsideLinkEscape = false;
let visible = stringWidth(stripAnsi2(rows[rows.length - 1]));
for (const [index, character] of characters.entries()) {
const characterLength = stringWidth(character);
if (visible + characterLength <= columns) {
rows[rows.length - 1] += character;
} else {
rows.push(character);
visible = 0;
}
if (ESCAPES.has(character)) {
isInsideEscape = true;
isInsideLinkEscape = characters.slice(index + 1).join("").startsWith(ANSI_ESCAPE_LINK);
}
if (isInsideEscape) {
if (isInsideLinkEscape) {
if (character === ANSI_ESCAPE_BELL) {
isInsideEscape = false;
isInsideLinkEscape = false;
}
} else if (character === ANSI_SGR_TERMINATOR) {
isInsideEscape = false;
}
continue;
}
visible += characterLength;
if (visible === columns && index < characters.length - 1) {
rows.push("");
visible = 0;
}
}
if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
rows[rows.length - 2] += rows.pop();
}
}, "wrapWord");
stringVisibleTrimSpacesRight = /* @__PURE__ */ __name((string) => {
const words = string.split(" ");
let last = words.length;
while (last > 0) {
if (stringWidth(words[last - 1]) > 0) {
break;
}
last--;
}
if (last === words.length) {
return string;
}
return words.slice(0, last).join(" ") + words.slice(last).join("");
}, "stringVisibleTrimSpacesRight");
exec = /* @__PURE__ */ __name((string, columns, options = {}) => {
if (options.trim !== false && string.trim() === "") {
return "";
}
let returnValue = "";
let escapeCode;
let escapeUrl;
const lengths = wordLengths(string);
let rows = [""];
for (const [index, word] of string.split(" ").entries()) {
if (options.trim !== false) {
rows[rows.length - 1] = rows[rows.length - 1].trimStart();
}
let rowLength = stringWidth(rows[rows.length - 1]);
if (index !== 0) {
if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
rows.push("");
rowLength = 0;
}
if (rowLength > 0 || options.trim === false) {
rows[rows.length - 1] += " ";
rowLength++;
}
}
if (options.hard && lengths[index] > columns) {
const remainingColumns = columns - rowLength;
const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
if (breaksStartingNextLine < breaksStartingThisLine) {
rows.push("");
}
wrapWord(rows, word, columns);
continue;
}
if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
if (options.wordWrap === false && rowLength < columns) {
wrapWord(rows, word, columns);
continue;
}
rows.push("");
}
if (rowLength + lengths[index] > columns && options.wordWrap === false) {
wrapWord(rows, word, columns);
continue;
}
rows[rows.length - 1] += word;
}
if (options.trim !== false) {
rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
}
const pre = [...rows.join("\n")];
for (const [index, character] of pre.entries()) {
returnValue += character;
if (ESCAPES.has(character)) {
const { groups } = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join("")) || { groups: {} };
if (groups.code !== void 0) {
const code2 = Number.parseFloat(groups.code);
escapeCode = code2 === END_CODE ? void 0 : code2;
} else if (groups.uri !== void 0) {
escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
}
}
const code = ansi_styles_default2.codes.get(Number(escapeCode));
if (pre[index + 1] === "\n") {
if (escapeUrl) {
returnValue += wrapAnsiHyperlink("");
}
if (escapeCode && code) {
returnValue += wrapAnsiCode(code);
}
} else if (character === "\n") {
if (escapeCode && code) {
returnValue += wrapAnsiCode(escapeCode);
}
if (escapeUrl) {
returnValue += wrapAnsiHyperlink(escapeUrl);
}
}
}
return returnValue;
}, "exec");
__name(wrapAnsi, "wrapAnsi");
}
});
// ../../node_modules/.pnpm/is-fullwidth-code-point@4.0.0/node_modules/is-fullwidth-code-point/index.js
function isFullwidthCodePoint(codePoint) {
if (!Number.isInteger(codePoint)) {
return false;
}
return codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
// CJK Radicals Supplement .. Enclosed CJK Letters and Months
11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
131072 <= codePoint && codePoint <= 262141);
}
var init_is_fullwidth_code_point = __esm({
"../../node_modules/.pnpm/is-fullwidth-code-point@4.0.0/node_modules/is-fullwidth-code-point/index.js"() {
init_import_meta_url();
__name(isFullwidthCodePoint, "isFullwidthCodePoint");
}
});
// ../../node_modules/.pnpm/slice-ansi@5.0.0/node_modules/slice-ansi/index.js
function sliceAnsi(string, begin, end) {
const characters = [...string];
const ansiCodes = [];
let stringEnd = typeof end === "number" ? end : characters.length;
let isInsideEscape = false;
let ansiCode;
let visible = 0;
let output = "";
for (const [index, character] of characters.entries()) {
let leftEscape = false;
if (ESCAPES2.includes(character)) {
const code = /\d[^m]*/.exec(string.slice(index, index + 18));
ansiCode = code && code.length > 0 ? code[0] : void 0;
if (visible < stringEnd) {
isInsideEscape = true;
if (ansiCode !== void 0) {
ansiCodes.push(ansiCode);
}
}
} else if (isInsideEscape && character === "m") {
isInsideEscape = false;
leftEscape = true;
}
if (!isInsideEscape && !leftEscape) {
visible++;
}
if (!astralRegex.test(character) && isFullwidthCodePoint(character.codePointAt())) {
visible++;
if (typeof end !== "number") {
stringEnd++;
}
}
if (visible > begin && visible <= stringEnd) {
output += character;
} else if (visible === begin && !isInsideEscape && ansiCode !== void 0) {
output = checkAnsi(ansiCodes);
} else if (visible >= stringEnd) {
output += checkAnsi(ansiCodes, true, ansiCode);
break;
}
}
return output;
}
var astralRegex, ESCAPES2, wrapAnsi2, checkAnsi;
var init_slice_ansi = __esm({
"../../node_modules/.pnpm/slice-ansi@5.0.0/node_modules/slice-ansi/index.js"() {
init_import_meta_url();
init_is_fullwidth_code_point();
init_ansi_styles2();
astralRegex = /^[\uD800-\uDBFF][\uDC00-\uDFFF]$/;
ESCAPES2 = [
"\x1B",
"\x9B"
];
wrapAnsi2 = /* @__PURE__ */ __name((code) => `${ESCAPES2[0]}[${code}m`, "wrapAnsi");
checkAnsi = /* @__PURE__ */ __name((ansiCodes, isEscapes, endAnsiCode) => {
let output = [];
ansiCodes = [...ansiCodes];
for (let ansiCode of ansiCodes) {
const ansiCodeOrigin = ansiCode;
if (ansiCode.includes(";")) {
ansiCode = ansiCode.split(";")[0][0] + "0";
}
const item = ansi_styles_default2.codes.get(Number.parseInt(ansiCode, 10));
if (item) {
const indexEscape = ansiCodes.indexOf(item.toString());
if (indexEscape === -1) {
output.push(wrapAnsi2(isEscapes ? item : ansiCodeOrigin));
} else {
ansiCodes.splice(indexEscape, 1);
}
} else if (isEscapes) {
output.push(wrapAnsi2(0));
break;
} else {
output.push(wrapAnsi2(ansiCodeOrigin));
}
}
if (isEscapes) {
output = output.filter((element, index) => output.indexOf(element) === index);
if (endAnsiCode !== void 0) {
const fistEscapeCode = wrapAnsi2(ansi_styles_default2.codes.get(Number.parseInt(endAnsiCode, 10)));
output = output.reduce((current, next) => next === fistEscapeCode ? [next, ...current] : [...current, next], []);
}
}
return output.join("");
}, "checkAnsi");
__name(sliceAnsi, "sliceAnsi");
}
});
// ../../node_modules/.pnpm/log-update@5.0.1/node_modules/log-update/index.js
function createLogUpdate(stream2, { showCursor = false } = {}) {
let previousLineCount = 0;
let previousWidth = getWidth(stream2);
let previousOutput = "";
const render2 = /* @__PURE__ */ __name((...arguments_) => {
if (!showCursor) {
cli_cursor_default.hide();
}
let output = arguments_.join(" ") + "\n";
output = fitToTerminalHeight(stream2, output);
const width = getWidth(stream2);
if (output === previousOutput && previousWidth === width) {
return;
}
previousOutput = output;
previousWidth = width;
output = wrapAnsi(output, width, {
trim: false,
hard: true,
wordWrap: false
});
stream2.write(ansi_escapes_default.eraseLines(previousLineCount) + output);
previousLineCount = output.split("\n").length;
}, "render");
render2.clear = () => {
stream2.write(ansi_escapes_default.eraseLines(previousLineCount));
previousOutput = "";
previousWidth = getWidth(stream2);
previousLineCount = 0;
};
render2.done = () => {
previousOutput = "";
previousWidth = getWidth(stream2);
previousLineCount = 0;
if (!showCursor) {
cli_cursor_default.show();
}
};
return render2;
}
var import_node_process5, defaultTerminalHeight, getWidth, fitToTerminalHeight, logUpdate, logUpdateStderr;
var init_log_update = __esm({
"../../node_modules/.pnpm/log-update@5.0.1/node_modules/log-update/index.js"() {
init_import_meta_url();
import_node_process5 = __toESM(require("process"), 1);
init_ansi_escapes();
init_cli_cursor();
init_wrap_ansi();
init_slice_ansi();
init_strip_ansi();
defaultTerminalHeight = 24;
getWidth = /* @__PURE__ */ __name((stream2) => {
const { columns } = stream2;
if (!columns) {
return 80;
}
return columns;
}, "getWidth");
fitToTerminalHeight = /* @__PURE__ */ __name((stream2, text) => {
const terminalHeight = stream2.rows || defaultTerminalHeight;
const lines = text.split("\n");
const toRemove = lines.length - terminalHeight;
if (toRemove <= 0) {
return text;
}
return sliceAnsi(
text,
stripAnsi2(lines.slice(0, toRemove).join("\n")).length + 1
);
}, "fitToTerminalHeight");
__name(createLogUpdate, "createLogUpdate");
logUpdate = createLogUpdate(import_node_process5.default.stdout);
logUpdateStderr = createLogUpdate(import_node_process5.default.stderr);
}
});
// ../cli/error.ts
var CancelError2;
var init_error = __esm({
"../cli/error.ts"() {
init_import_meta_url();
CancelError2 = class extends Error {
constructor(message, signal) {
super(message);
this.signal = signal;
}
static {
__name(this, "CancelError");
}
};
}
});
// ../cli/select-list.ts
var SelectRefreshablePrompt;
var init_select_list = __esm({
"../cli/select-list.ts"() {
init_import_meta_url();
init_dist();
SelectRefreshablePrompt = class extends h {
static {
__name(this, "SelectRefreshablePrompt");
}
options;
cursor = 0;
get _value() {
return this.options[this.cursor];
}
changeValue() {
this.value = this._value.value;
}
constructor(opts) {
super(opts, false);
this.options = opts.options;
this.cursor = this.options.findIndex(
({ value }) => value === opts.initialValue
);
if (this.cursor === -1) {
this.cursor = 0;
}
this.changeValue();
this.on("key", (c6) => {
if (c6 !== "r") {
return;
}
void opts.onRefresh().then((newOptions) => {
this.options = [...newOptions];
this.cursor = 0;
this.changeValue();
const that = this;
if ("render" in that && typeof that.render === "function") {
that.render();
}
}).catch(() => {
});
});
this.on("cursor", (key) => {
switch (key) {
case "left":
case "up":
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
break;
case "down":
case "right":
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
break;
}
this.changeValue();
});
}
};
}
});
// ../cli/streams.ts
var stdout, stderr;
var init_streams = __esm({
"../cli/streams.ts"() {
init_import_meta_url();
stdout = process.stdout;
stderr = process.stderr;
}
});
// ../cli/check-macos-version.ts
function checkMacOSVersion(options) {
if (process.platform !== "darwin") {
return;
}
if (process.env.CI) {
return;
}
const release3 = import_node_os3.default.release();
const macOSVersion = darwinVersionToMacOSVersion(release3);
if (macOSVersion && isVersionLessThan(macOSVersion, MINIMUM_MACOS_VERSION)) {
if (options.shouldThrow) {
throw new Error(
`Unsupported macOS version: The Cloudflare Workers runtime cannot run on the current version of macOS (${macOSVersion}). The minimum requirement is macOS ${MINIMUM_MACOS_VERSION}+. See https://github.com/cloudflare/workerd?tab=readme-ov-file#running-workerd If you cannot upgrade your version of macOS, you could try running in a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`
);
} else {
console.warn(
`\u26A0\uFE0F Warning: Unsupported macOS version detected (${macOSVersion}). The Cloudflare Workers runtime may not work correctly on macOS versions below ${MINIMUM_MACOS_VERSION}. Consider upgrading to macOS ${MINIMUM_MACOS_VERSION}+ or using a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`
);
}
}
}
function darwinVersionToMacOSVersion(darwinVersion) {
const match2 = darwinVersion.match(/^(\d+)\.(\d+)\.(\d+)/);
if (!match2) {
return null;
}
const major = parseInt(match2[1], 10);
if (major >= 20) {
const macOSMajor = major - 9;
const minor = parseInt(match2[2], 10);
const patch = parseInt(match2[3], 10);
return `${macOSMajor}.${minor}.${patch}`;
}
return null;
}
function isVersionLessThan(version1, version22) {
const versionRegex = /^(\d+)\.(\d+)\.(\d+)$/;
const match1 = version1.match(versionRegex);
const match2 = version22.match(versionRegex);
if (!match1 || !match2) {
throw new Error(
`Invalid version format. Expected M.m.p format, got: ${version1}, ${version22}`
);
}
const [major1, minor1, patch1] = [
parseInt(match1[1], 10),
parseInt(match1[2], 10),
parseInt(match1[3], 10)
];
const [major2, minor2, patch2] = [
parseInt(match2[1], 10),
parseInt(match2[2], 10),
parseInt(match2[3], 10)
];
if (major1 !== major2) {
return major1 < major2;
}
if (minor1 !== minor2) {
return minor1 < minor2;
}
return patch1 < patch2;
}
var import_node_os3, MINIMUM_MACOS_VERSION;
var init_check_macos_version = __esm({
"../cli/check-macos-version.ts"() {
init_import_meta_url();
import_node_os3 = __toESM(require("os"));
MINIMUM_MACOS_VERSION = "13.5.0";
__name(checkMacOSVersion, "checkMacOSVersion");
__name(darwinVersionToMacOSVersion, "darwinVersionToMacOSVersion");
__name(isVersionLessThan, "isVersionLessThan");
}
});
// ../cli/index.ts
var import_process, shapes, status, space, logRaw, log, newline, format6, updateStatus, startSection, endSection, cancel, warn, success, stripAnsi3, linkRegex, crash, error;
var init_cli = __esm({
"../cli/index.ts"() {
init_import_meta_url();
import_process = require("process");
init_colors();
init_streams();
init_check_macos_version();
shapes = {
diamond: "\u25C7",
dash: "\u2500",
radioInactive: "\u25CB",
radioActive: "\u25CF",
backActive: "\u25C0",
backInactive: "\u25C1",
bar: "\u2502",
leftT: "\u251C",
rigthT: "\u2524",
arrows: {
left: "\u2039",
right: "\u203A"
},
corners: {
tl: "\u256D",
bl: "\u2570",
tr: "\u256E",
br: "\u256F"
}
};
status = {
error: bgRed(` ERROR `),
warning: bgYellow(` WARNING `),
info: bgBlue(` INFO `),
success: bgGreen(` SUCCESS `),
cancel: white.bgRed(` X `)
};
space = /* @__PURE__ */ __name((n6 = 1) => {
return hidden("\u200A".repeat(n6));
}, "space");
logRaw = /* @__PURE__ */ __name((msg) => {
stdout.write(`${msg}
`);
}, "logRaw");
log = /* @__PURE__ */ __name((msg) => {
const lines = msg.split("\n").map((ln) => `${gray(shapes.bar)}${ln.length > 0 ? " " + white(ln) : ""}`);
logRaw(lines.join("\n"));
}, "log");
newline = /* @__PURE__ */ __name(() => {
log("");
}, "newline");
format6 = /* @__PURE__ */ __name((msg, {
linePrefix = gray(shapes.bar),
firstLinePrefix = linePrefix,
newlineBefore = false,
newlineAfter = false,
formatLine = /* @__PURE__ */ __name((line) => white(line), "formatLine"),
multiline = true
} = {}) => {
const lines = multiline ? msg.split("\n") : [msg];
const formattedLines = lines.map(
(line, i5) => (i5 === 0 ? firstLinePrefix : linePrefix) + space() + formatLine(line)
);
if (newlineBefore) {
formattedLines.unshift(linePrefix);
}
if (newlineAfter) {
formattedLines.push(linePrefix);
}
return formattedLines.join("\n");
}, "format");
updateStatus = /* @__PURE__ */ __name((msg, printNewLine = true) => {
logRaw(
format6(msg, {
firstLinePrefix: gray(shapes.leftT),
linePrefix: gray(shapes.bar),
newlineAfter: printNewLine
})
);
}, "updateStatus");
startSection = /* @__PURE__ */ __name((heading, subheading, printNewLine = true) => {
logRaw(
`${gray(shapes.corners.tl)} ${brandColor(heading)} ${subheading ? dim(subheading) : ""}`
);
if (printNewLine) {
newline();
}
}, "startSection");
endSection = /* @__PURE__ */ __name((heading, subheading) => {
logRaw(
`${gray(shapes.corners.bl)} ${brandColor(heading)} ${subheading ? dim(subheading) : ""}
`
);
}, "endSection");
cancel = /* @__PURE__ */ __name((msg, {
// current default is backcompat and makes sense going forward too
shape = shapes.corners.bl,
// current default for backcompat -- TODO: change default to true once all callees have been updated
multiline = false
} = {}) => {
logRaw(
format6(msg, {
firstLinePrefix: `${gray(shape)} ${status.cancel}`,
linePrefix: gray(shapes.bar),
newlineBefore: true,
formatLine: /* @__PURE__ */ __name((line) => dim(line), "formatLine"),
// for backcompat but it's not ideal for this to be "dim"
multiline
})
);
}, "cancel");
warn = /* @__PURE__ */ __name((msg, {
// current default for backcompat -- TODO: change default to shapes.bar once all callees have been updated
shape = shapes.corners.bl,
// current default for backcompat -- TODO: change default to true once all callees have been updated
multiline = false,
newlineBefore = true
} = {}) => {
logRaw(
format6(msg, {
firstLinePrefix: gray(shape) + space() + status.warning,
linePrefix: gray(shapes.bar),
formatLine: /* @__PURE__ */ __name((line) => dim(line), "formatLine"),
// for backcompat but it's not ideal for this to be "dim"
multiline,
newlineBefore
})
);
}, "warn");
success = /* @__PURE__ */ __name((msg, {
// current default for backcompat -- TODO: change default to shapes.bar once all callees have been updated
shape = shapes.corners.bl,
// current default for backcompat -- TODO: change default to true once all callees have been updated
multiline = false
} = {}) => {
logRaw(
format6(msg, {
firstLinePrefix: gray(shape) + space() + status.success,
linePrefix: gray(shapes.bar),
newlineBefore: true,
formatLine: /* @__PURE__ */ __name((line) => dim(line), "formatLine"),
// for backcompat but it's not ideal for this to be "dim"
multiline
})
);
}, "success");
stripAnsi3 = /* @__PURE__ */ __name((str) => {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
].join("|");
const regex2 = RegExp(pattern, "g");
return str.replace(linkRegex, "$2").replace(regex2, "");
}, "stripAnsi");
linkRegex = // eslint-disable-next-line no-control-regex
/\u001B\]8;;(?<url>.+)\u001B\\(?<label>.+)\u001B\]8;;\u001B\\/g;
crash = /* @__PURE__ */ __name((msg, extra) => {
error(msg, extra);
(0, import_process.exit)(1);
}, "crash");
error = /* @__PURE__ */ __name((msg, extra, corner = shapes.corners.bl) => {
if (msg) {
stderr.write(
`${gray(corner)} ${status.error} ${dim(msg)}
${extra ? space() + extra + "\n" : ""}`
);
}
}, "error");
}
});
// ../cli/interactive.ts
function acceptDefault(promptConfig, renderers, initialValue) {
const error2 = promptConfig.validate?.(initialValue);
if (error2) {
if (promptConfig.throwOnError) {
throw new Error(error2);
} else {
crash(error2);
}
}
const lines = renderers.submit({ value: initialValue });
logRaw(lines.join("\n"));
return initialValue;
}
function isInteractive() {
try {
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
} catch {
return false;
}
}
var logUpdate2, grayBar, blCorner, leftT, inputPrompt, renderSubmit, getRenderers, getTextRenderers, getSelectRenderers, getSelectListRenderers, getConfirmRenderers, spinnerFrames, ellipsisFrames, spinner, unwrapFactory, spinnerWhile;
var init_interactive = __esm({
"../cli/interactive.ts"() {
init_import_meta_url();
init_dist();
init_log_update();
init_colors();
init_error();
init_select_list();
init_streams();
init_cli();
logUpdate2 = createLogUpdate(stdout);
grayBar = gray(shapes.bar);
blCorner = gray(shapes.corners.bl);
leftT = gray(shapes.leftT);
__name(acceptDefault, "acceptDefault");
inputPrompt = /* @__PURE__ */ __name(async (promptConfig) => {
const renderers = {
...getRenderers(promptConfig),
...promptConfig.renderers
};
let prompt2;
const dispatchRender = /* @__PURE__ */ __name((props, p6) => {
let state2 = props.state;
if (state2 === "initial" && promptConfig.initialErrorMessage) {
state2 = "error";
props.error = promptConfig.initialErrorMessage;
}
const renderedLines = renderers[state2](props, p6);
return renderedLines.join("\n");
}, "dispatchRender");
if (promptConfig.type === "select") {
const initialValue = String(promptConfig.defaultValue);
if (promptConfig.acceptDefault) {
return acceptDefault(promptConfig, renderers, initialValue);
}
prompt2 = new ED({
...promptConfig,
options: promptConfig.options.filter((o5) => !o5.hidden),
initialValue,
render() {
return dispatchRender(this, prompt2);
}
});
} else if (promptConfig.type === "confirm") {
const initialValue = Boolean(promptConfig.defaultValue);
if (promptConfig.acceptDefault) {
return acceptDefault(promptConfig, renderers, initialValue);
}
prompt2 = new sD({
...promptConfig,
initialValue,
active: promptConfig.activeText || "",
inactive: promptConfig.inactiveText || "",
render() {
return dispatchRender(this, prompt2);
}
});
} else if (promptConfig.type == "multiselect") {
let initialValues;
if (Array.isArray(promptConfig.defaultValue)) {
initialValues = promptConfig.defaultValue;
} else if (promptConfig.defaultValue !== void 0) {
initialValues = [String(promptConfig.defaultValue)];
}
if (promptConfig.acceptDefault) {
return acceptDefault(promptConfig, renderers, initialValues);
}
prompt2 = new iD({
...promptConfig,
options: promptConfig.options,
initialValues,
render() {
return dispatchRender(this, prompt2);
}
});
} else if (promptConfig.type === "list") {
const initialValue = String(promptConfig.defaultValue);
if (promptConfig.acceptDefault) {
return acceptDefault(promptConfig, renderers, initialValue);
}
prompt2 = new SelectRefreshablePrompt({
...promptConfig,
onRefresh: promptConfig.onRefresh ?? (() => Promise.resolve(promptConfig.options)),
initialValue,
render() {
return dispatchRender(this, prompt2);
}
});
} else {
const initialValue = promptConfig.initialValue ?? String(promptConfig.defaultValue ?? "");
if (promptConfig.acceptDefault) {
return acceptDefault(promptConfig, renderers, initialValue);
}
prompt2 = new oD({
...promptConfig,
initialValue: promptConfig.initialValue,
defaultValue: String(promptConfig.defaultValue ?? ""),
render() {
return dispatchRender(this, prompt2);
}
});
}
const input = await prompt2.prompt();
if (eD(input)) {
if (promptConfig.throwOnError) {
throw new CancelError2("Operation cancelled");
} else {
cancel("Operation cancelled");
process.exit(0);
}
}
return input;
}, "inputPrompt");
renderSubmit = /* @__PURE__ */ __name((config, value) => {
const { question, label } = config;
if (config.type !== "confirm" && !value) {
return [`${leftT} ${question} ${dim("(skipped)")}`, `${grayBar}`];
}
const content = config.type === "confirm" ? `${grayBar} ${brandColor(value)} ${dim(label)}` : `${grayBar} ${brandColor(label)} ${dim(value)}`;
return [`${leftT} ${question}`, content, `${grayBar}`];
}, "renderSubmit");
getRenderers = /* @__PURE__ */ __name((config) => {
switch (config.type) {
case "select":
return getSelectRenderers(config);
case "confirm":
return getConfirmRenderers(config);
case "text":
return getTextRenderers(config);
case "multiselect":
return getSelectRenderers(config);
case "list":
return getSelectListRenderers(config);
}
}, "getRenderers");
getTextRenderers = /* @__PURE__ */ __name((config) => {
const { question } = config;
const helpText = config.helpText ?? "";
const format9 = config.format ?? ((val2) => String(val2));
const defaultValue = config.defaultValue?.toString() ?? "";
const activeRenderer = /* @__PURE__ */ __name(({ value }) => [
`${blCorner} ${bold(question)} ${dim(helpText)}`,
`${space(2)}${format9(value || dim(defaultValue))}`,
``
// extra line for readability
], "activeRenderer");
return {
initial: /* @__PURE__ */ __name(() => [
`${blCorner} ${bold(question)} ${dim(helpText)}`,
`${space(2)}${gray(format9(defaultValue))}`,
``
// extra line for readability
], "initial"),
active: activeRenderer,
error: /* @__PURE__ */ __name(({ value, error: error2 }) => [
`${leftT} ${status.error} ${dim(error2)}`,
`${grayBar}`,
`${blCorner} ${question} ${dim(helpText)}`,
`${space(2)}${format9(value)}`,
``
// extra line for readability
], "error"),
submit: /* @__PURE__ */ __name(({ value }) => renderSubmit(config, format9(value ?? "")), "submit"),
cancel: activeRenderer
};
}, "getTextRenderers");
getSelectRenderers = /* @__PURE__ */ __name((config) => {
const { options, question, helpText: _helpText } = config;
const helpText = _helpText ?? "";
const maxItemsPerPage = config.maxItemsPerPage ?? 32;
const defaultRenderer = /* @__PURE__ */ __name(({ cursor = 0, value }) => {
const renderOption = /* @__PURE__ */ __name((opt, i5) => {
const { label: optionLabel, value: optionValue } = opt;
const active2 = i5 === cursor;
const isInListOfValues = Array.isArray(value) && value.includes(optionValue);
const color = isInListOfValues || active2 ? blue : white;
const text = active2 ? color.underline(optionLabel) : color(optionLabel);
const sublabel = opt.sublabel ? color.grey(opt.sublabel) : "";
const indicator = isInListOfValues || active2 && !Array.isArray(value) ? color(opt.activeIcon ?? shapes.radioActive) : color(opt.inactiveIcon ?? shapes.radioInactive);
return `${space(2)}${indicator} ${text} ${sublabel}`;
}, "renderOption");
const renderOptionCondition = /* @__PURE__ */ __name((_4, i5) => {
if (options.length <= maxItemsPerPage) {
return true;
}
if (i5 < cursor) {
return options.length - i5 <= maxItemsPerPage;
}
return cursor + maxItemsPerPage > i5;
}, "renderOptionCondition");
const visibleOptions = options.filter((o5) => !o5.hidden);
const activeOption = visibleOptions.at(cursor);
const lines = [
`${blCorner} ${bold(question)} ${dim(helpText)}`,
`${cursor > 0 && options.length > maxItemsPerPage ? `${space(2)}${dim("...")}
` : ""}${visibleOptions.map(renderOption).filter(renderOptionCondition).join(`
`)}${cursor + maxItemsPerPage < options.length && options.length > maxItemsPerPage ? `
${space(2)}${dim("...")}` : ""}`,
``
// extra line for readability
];
if (activeOption?.description) {
const wordSegmenter = new Intl.Segmenter("en", { granularity: "word" });
const padding = space(2);
const availableWidth = process.stdout.columns - stripAnsi3(padding).length * 2;
const description = stripAnsi3(activeOption.description);
const descriptionLines = [];
let descriptionLineNumber = 0;
for (const data of wordSegmenter.segment(description)) {
let line = descriptionLines[descriptionLineNumber] ?? "";
const currentLineWidth = line.length;
const segmentSize = data.segment.length;
if (currentLineWidth + segmentSize > availableWidth) {
descriptionLineNumber++;
line = "";
if (data.segment.match(/^\s+$/)) {
continue;
}
}
descriptionLines[descriptionLineNumber] = line + data.segment;
}
lines.push(
dim(
descriptionLines.map((line) => padding + line + padding).join("\n")
),
``
);
}
return lines;
}, "defaultRenderer");
return {
initial: defaultRenderer,
active: defaultRenderer,
confirm: defaultRenderer,
error: /* @__PURE__ */ __name((opts, prompt2) => {
return [
`${leftT} ${status.error} ${dim(opts.error)}`,
`${grayBar}`,
...defaultRenderer(opts, prompt2)
];
}, "error"),
submit: /* @__PURE__ */ __name(({ value }) => {
if (Array.isArray(value)) {
return renderSubmit(
config,
options.filter((o5) => value.includes(o5.value)).map((o5) => o5.label).join(", ")
);
}
return renderSubmit(
config,
options.find((o5) => o5.value === value)?.label
);
}, "submit"),
cancel: defaultRenderer
};
}, "getSelectRenderers");
getSelectListRenderers = /* @__PURE__ */ __name((config) => {
const { question, helpText: _helpText } = config;
let options = config.options;
const helpText = _helpText ?? "";
const { rows } = stdout;
const defaultRenderer = /* @__PURE__ */ __name(({ cursor, value }, prompt2) => {
if (prompt2 instanceof SelectRefreshablePrompt) {
options = prompt2.options;
}
cursor = cursor ?? 0;
let smallCursor = 0;
const renderOption = /* @__PURE__ */ __name((opt, i5) => {
const { label: optionLabel, value: optionValueAny } = opt;
const optionValue = optionValueAny.toString();
const active2 = i5 === smallCursor;
const isInListOfValues = Array.isArray(value) && value.includes(optionValue);
const color = isInListOfValues || active2 ? blue : white;
const text = active2 ? color.underline(optionLabel) : color(optionLabel);
const indicator = isInListOfValues || active2 && !Array.isArray(value) ? color(shapes.radioActive) : color(shapes.radioInactive);
const indicatorMargin = 2;
const detailBulletpointMargin = indicatorMargin + 4;
return [
`${space(indicatorMargin)}${indicator} ${text}`,
...opt.details.map(
(detail, j6) => `${space(detailBulletpointMargin)}${j6 === opt.details.length - 1 ? gray(shapes.corners.bl) : grayBar} ${detail}`
)
];
}, "renderOption");
const pages = [];
let current = {
size: 0,
options: []
};
const VERTICAL_MARGIN = 6;
for (const option of options) {
const optionHeight = option.details.length + 1;
if (current.size + optionHeight > rows - VERTICAL_MARGIN) {
pages.push(current.options);
current = { size: optionHeight, options: [option] };
continue;
}
current.size += optionHeight;
current.options.push(option);
}
if (current.size !== 0) {
pages.push(current.options);
}
let isFirstPage = true;
let isLastPage = false;
let page = [];
let len = 0;
for (let i5 = 0; i5 < pages.length; i5++) {
const pageIter = pages[i5];
if (cursor >= len && pageIter.length + len > cursor) {
isFirstPage = i5 === 0;
isLastPage = i5 === pages.length - 1;
page = pageIter;
smallCursor = cursor - len;
break;
}
len += pageIter.length;
}
return [
`${blCorner} ${bold(question)} ${dim(helpText)}`,
...!isFirstPage ? [`${space(2)}${dim("...")}`] : [],
...page.map(renderOption).reduce((prev, now) => [...prev, ...now], []),
...!isLastPage ? [`${space(2)}${dim("...")}`] : []
];
}, "defaultRenderer");
return {
initial: defaultRenderer,
active: defaultRenderer,
confirm: defaultRenderer,
error: /* @__PURE__ */ __name((opts, prompt2) => {
return [
`${leftT} ${status.error} ${dim(opts.error)}`,
`${grayBar}`,
...defaultRenderer(opts, prompt2)
];
}, "error"),
submit: /* @__PURE__ */ __name(({ value }) => {
if (Array.isArray(value)) {
return renderSubmit(
config,
options.filter((o5) => value.includes(o5.value)).map((o5) => o5.value).join(", ")
);
}
return renderSubmit(
config,
options.find((o5) => o5.value === value)?.value
);
}, "submit"),
cancel: defaultRenderer
};
}, "getSelectListRenderers");
getConfirmRenderers = /* @__PURE__ */ __name((config) => {
const { activeText, inactiveText, question, helpText: _helpText } = config;
const helpText = _helpText ?? "";
const active2 = activeText || "Yes";
const inactive = inactiveText || "No";
const defaultRenderer = /* @__PURE__ */ __name(({ value }) => {
const yesColor = value ? blue.underline : dim;
const noColor = value ? dim : blue.underline;
return [
`${blCorner} ${bold(question)} ${dim(helpText)}`,
`${space(2)}${yesColor(active2)} / ${noColor(inactive)}`
];
}, "defaultRenderer");
return {
initial: defaultRenderer,
active: defaultRenderer,
confirm: defaultRenderer,
error: defaultRenderer,
submit: /* @__PURE__ */ __name(({ value }) => renderSubmit(config, value ? "yes" : "no"), "submit"),
cancel: defaultRenderer
};
}, "getConfirmRenderers");
spinnerFrames = {
clockwise: ["\u2524", "\u2518", "\u2534", "\u2514", "\u251C", "\u250C", "\u252C", "\u2510"],
vertical: ["\u2581", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2586", "\u2585", "\u2584", "\u2583"]
};
ellipsisFrames = ["", ".", "..", "...", " ..", " .", ""];
spinner = /* @__PURE__ */ __name((frames = spinnerFrames.clockwise, color = brandColor) => {
const frameRate = 120;
let loop = null;
let startMsg;
let currentMsg;
function clearLoop() {
if (loop) {
clearTimeout(loop);
}
loop = null;
}
__name(clearLoop, "clearLoop");
return {
start(msg, helpText) {
helpText ||= ``;
currentMsg = msg;
startMsg = currentMsg;
if (helpText !== void 0 && helpText.length > 0) {
startMsg += ` ${dim(helpText)}`;
}
if (isInteractive()) {
let index = 0;
clearLoop();
loop = setInterval(() => {
index++;
const spinnerFrame = frames[index % frames.length];
const ellipsisFrame = ellipsisFrames[index % ellipsisFrames.length];
if (msg) {
logUpdate2(`${color(spinnerFrame)} ${currentMsg} ${ellipsisFrame}`);
}
}, frameRate);
} else {
logRaw(`${leftT} ${startMsg}`);
}
},
update(msg) {
currentMsg = msg;
},
stop(msg) {
if (isInteractive()) {
logUpdate2.clear();
if (msg) {
logUpdate2(`${leftT} ${startMsg}
${grayBar} ${msg}`);
logUpdate2.done();
newline();
}
clearLoop();
} else {
if (msg !== void 0) {
logRaw(`${grayBar} ${msg}`);
}
newline();
}
}
};
}, "spinner");
unwrapFactory = /* @__PURE__ */ __name((input) => {
const output = typeof input === "function" ? input() : input;
return output;
}, "unwrapFactory");
spinnerWhile = /* @__PURE__ */ __name(async (opts) => {
const s5 = opts.spinner ?? spinner();
s5.start(unwrapFactory(opts.startMessage));
try {
const result = await unwrapFactory(opts.promise);
return result;
} finally {
s5.stop(unwrapFactory(opts.endMessage));
}
}, "spinnerWhile");
__name(isInteractive, "isInteractive");
}
});
// ../../node_modules/.pnpm/ci-info@3.9.0/node_modules/ci-info/vendors.json
var require_vendors = __commonJS({
"../../node_modules/.pnpm/ci-info@3.9.0/node_modules/ci-info/vendors.json"(exports2, module3) {
module3.exports = [
{
name: "Appcircle",
constant: "APPCIRCLE",
env: "AC_APPCIRCLE"
},
{
name: "AppVeyor",
constant: "APPVEYOR",
env: "APPVEYOR",
pr: "APPVEYOR_PULL_REQUEST_NUMBER"
},
{
name: "AWS CodeBuild",
constant: "CODEBUILD",
env: "CODEBUILD_BUILD_ARN"
},
{
name: "Azure Pipelines",
constant: "AZURE_PIPELINES",
env: "TF_BUILD",
pr: {
BUILD_REASON: "PullRequest"
}
},
{
name: "Bamboo",
constant: "BAMBOO",
env: "bamboo_planKey"
},
{
name: "Bitbucket Pipelines",
constant: "BITBUCKET",
env: "BITBUCKET_COMMIT",
pr: "BITBUCKET_PR_ID"
},
{
name: "Bitrise",
constant: "BITRISE",
env: "BITRISE_IO",
pr: "BITRISE_PULL_REQUEST"
},
{
name: "Buddy",
constant: "BUDDY",
env: "BUDDY_WORKSPACE_ID",
pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
},
{
name: "Buildkite",
constant: "BUILDKITE",
env: "BUILDKITE",
pr: {
env: "BUILDKITE_PULL_REQUEST",
ne: "false"
}
},
{
name: "CircleCI",
constant: "CIRCLE",
env: "CIRCLECI",
pr: "CIRCLE_PULL_REQUEST"
},
{
name: "Cirrus CI",
constant: "CIRRUS",
env: "CIRRUS_CI",
pr: "CIRRUS_PR"
},
{
name: "Codefresh",
constant: "CODEFRESH",
env: "CF_BUILD_ID",
pr: {
any: [
"CF_PULL_REQUEST_NUMBER",
"CF_PULL_REQUEST_ID"
]
}
},
{
name: "Codemagic",
constant: "CODEMAGIC",
env: "CM_BUILD_ID",
pr: "CM_PULL_REQUEST"
},
{
name: "Codeship",
constant: "CODESHIP",
env: {
CI_NAME: "codeship"
}
},
{
name: "Drone",
constant: "DRONE",
env: "DRONE",
pr: {
DRONE_BUILD_EVENT: "pull_request"
}
},
{
name: "dsari",
constant: "DSARI",
env: "DSARI"
},
{
name: "Expo Application Services",
constant: "EAS",
env: "EAS_BUILD"
},
{
name: "Gerrit",
constant: "GERRIT",
env: "GERRIT_PROJECT"
},
{
name: "GitHub Actions",
constant: "GITHUB_ACTIONS",
env: "GITHUB_ACTIONS",
pr: {
GITHUB_EVENT_NAME: "pull_request"
}
},
{
name: "GitLab CI",
constant: "GITLAB",
env: "GITLAB_CI",
pr: "CI_MERGE_REQUEST_ID"
},
{
name: "GoCD",
constant: "GOCD",
env: "GO_PIPELINE_LABEL"
},
{
name: "Google Cloud Build",
constant: "GOOGLE_CLOUD_BUILD",
env: "BUILDER_OUTPUT"
},
{
name: "Harness CI",
constant: "HARNESS",
env: "HARNESS_BUILD_ID"
},
{
name: "Heroku",
constant: "HEROKU",
env: {
env: "NODE",
includes: "/app/.heroku/node/bin/node"
}
},
{
name: "Hudson",
constant: "HUDSON",
env: "HUDSON_URL"
},
{
name: "Jenkins",
constant: "JENKINS",
env: [
"JENKINS_URL",
"BUILD_ID"
],
pr: {
any: [
"ghprbPullId",
"CHANGE_ID"
]
}
},
{
name: "LayerCI",
constant: "LAYERCI",
env: "LAYERCI",
pr: "LAYERCI_PULL_REQUEST"
},
{
name: "Magnum CI",
constant: "MAGNUM",
env: "MAGNUM"
},
{
name: "Netlify CI",
constant: "NETLIFY",
env: "NETLIFY",
pr: {
env: "PULL_REQUEST",
ne: "false"
}
},
{
name: "Nevercode",
constant: "NEVERCODE",
env: "NEVERCODE",
pr: {
env: "NEVERCODE_PULL_REQUEST",
ne: "false"
}
},
{
name: "ReleaseHub",
constant: "RELEASEHUB",
env: "RELEASE_BUILD_ID"
},
{
name: "Render",
constant: "RENDER",
env: "RENDER",
pr: {
IS_PULL_REQUEST: "true"
}
},
{
name: "Sail CI",
constant: "SAIL",
env: "SAILCI",
pr: "SAIL_PULL_REQUEST_NUMBER"
},
{
name: "Screwdriver",
constant: "SCREWDRIVER",
env: "SCREWDRIVER",
pr: {
env: "SD_PULL_REQUEST",
ne: "false"
}
},
{
name: "Semaphore",
constant: "SEMAPHORE",
env: "SEMAPHORE",
pr: "PULL_REQUEST_NUMBER"
},
{
name: "Shippable",
constant: "SHIPPABLE",
env: "SHIPPABLE",
pr: {
IS_PULL_REQUEST: "true"
}
},
{
name: "Solano CI",
constant: "SOLANO",
env: "TDDIUM",
pr: "TDDIUM_PR_ID"
},
{
name: "Sourcehut",
constant: "SOURCEHUT",
env: {
CI_NAME: "sourcehut"
}
},
{
name: "Strider CD",
constant: "STRIDER",
env: "STRIDER"
},
{
name: "TaskCluster",
constant: "TASKCLUSTER",
env: [
"TASK_ID",
"RUN_ID"
]
},
{
name: "TeamCity",
constant: "TEAMCITY",
env: "TEAMCITY_VERSION"
},
{
name: "Travis CI",
constant: "TRAVIS",
env: "TRAVIS",
pr: {
env: "TRAVIS_PULL_REQUEST",
ne: "false"
}
},
{
name: "Vercel",
constant: "VERCEL",
env: {
any: [
"NOW_BUILDER",
"VERCEL"
]
},
pr: "VERCEL_GIT_PULL_REQUEST_ID"
},
{
name: "Visual Studio App Center",
constant: "APPCENTER",
env: "APPCENTER_BUILD_ID"
},
{
name: "Woodpecker",
constant: "WOODPECKER",
env: {
CI: "woodpecker"
},
pr: {
CI_BUILD_EVENT: "pull_request"
}
},
{
name: "Xcode Cloud",
constant: "XCODE_CLOUD",
env: "CI_XCODE_PROJECT",
pr: "CI_PULL_REQUEST_NUMBER"
},
{
name: "Xcode Server",
constant: "XCODE_SERVER",
env: "XCS"
}
];
}
});
// ../../node_modules/.pnpm/ci-info@3.9.0/node_modules/ci-info/index.js
var require_ci_info = __commonJS({
"../../node_modules/.pnpm/ci-info@3.9.0/node_modules/ci-info/index.js"(exports2) {
"use strict";
init_import_meta_url();
var vendors = require_vendors();
var env6 = process.env;
Object.defineProperty(exports2, "_vendors", {
value: vendors.map(function(v7) {
return v7.constant;
})
});
exports2.name = null;
exports2.isPR = null;
vendors.forEach(function(vendor) {
const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
const isCI2 = envs.every(function(obj) {
return checkEnv(obj);
});
exports2[vendor.constant] = isCI2;
if (!isCI2) {
return;
}
exports2.name = vendor.name;
switch (typeof vendor.pr) {
case "string":
exports2.isPR = !!env6[vendor.pr];
break;
case "object":
if ("env" in vendor.pr) {
exports2.isPR = vendor.pr.env in env6 && env6[vendor.pr.env] !== vendor.pr.ne;
} else if ("any" in vendor.pr) {
exports2.isPR = vendor.pr.any.some(function(key) {
return !!env6[key];
});
} else {
exports2.isPR = checkEnv(vendor.pr);
}
break;
default:
exports2.isPR = null;
}
});
exports2.isCI = !!(env6.CI !== "false" && // Bypass all checks if CI env is explicitly set to 'false'
(env6.BUILD_ID || // Jenkins, Cloudbees
env6.BUILD_NUMBER || // Jenkins, TeamCity
env6.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
env6.CI_APP_ID || // Appflow
env6.CI_BUILD_ID || // Appflow
env6.CI_BUILD_NUMBER || // Appflow
env6.CI_NAME || // Codeship and others
env6.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
env6.RUN_ID || // TaskCluster, dsari
exports2.name || false));
function checkEnv(obj) {
if (typeof obj === "string") return !!env6[obj];
if ("env" in obj) {
return env6[obj.env] && env6[obj.env].includes(obj.includes);
}
if ("any" in obj) {
return obj.any.some(function(k6) {
return !!env6[k6];
});
}
return Object.keys(obj).every(function(k6) {
return env6[k6] === obj[k6];
});
}
__name(checkEnv, "checkEnv");
}
});
// ../../node_modules/.pnpm/is-ci@3.0.1/node_modules/is-ci/index.js
var require_is_ci = __commonJS({
"../../node_modules/.pnpm/is-ci@3.0.1/node_modules/is-ci/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = require_ci_info().isCI;
}
});
// src/is-ci.ts
function isPagesCI() {
return process.env.CF_PAGES === "1";
}
function isWorkersCI() {
return process.env.WORKERS_CI === "1";
}
var import_is_ci, CI;
var init_is_ci = __esm({
"src/is-ci.ts"() {
init_import_meta_url();
import_is_ci = __toESM(require_is_ci());
__name(isPagesCI, "isPagesCI");
__name(isWorkersCI, "isWorkersCI");
CI = {
/** Is Wrangler currently running in a CI? */
isCI() {
return import_is_ci.default || isPagesCI() || isWorkersCI();
}
};
}
});
// src/is-interactive.ts
function isInteractive2() {
if (isPagesCI() || isWorkersCI()) {
return false;
}
return isInteractive();
}
function isNonInteractiveOrCI() {
return !isInteractive2() || CI.isCI();
}
var init_is_interactive = __esm({
"src/is-interactive.ts"() {
init_import_meta_url();
init_interactive();
init_is_ci();
__name(isInteractive2, "isInteractive");
__name(isNonInteractiveOrCI, "isNonInteractiveOrCI");
}
});
// src/dialogs.ts
async function confirm(text, { defaultValue = true, fallbackValue = true } = {}) {
if (isNonInteractiveOrCI()) {
logger.log(`? ${text}`);
logger.log(
`\u{1F916} ${source_default.dim(
"Using fallback value in non-interactive context:"
)} ${source_default.white.bold(fallbackValue ? "yes" : "no")}`
);
return fallbackValue;
}
const { value } = await (0, import_prompts.default)({
type: "confirm",
name: "value",
message: text,
initial: defaultValue,
onState: /* @__PURE__ */ __name((state2) => {
if (state2.aborted) {
process.nextTick(() => {
process.exit(1);
});
}
}, "onState")
});
return value;
}
async function prompt(text, options = {}) {
if (isNonInteractiveOrCI()) {
if (options?.defaultValue === void 0) {
throw new NoDefaultValueProvided();
}
logger.log(`? ${text}`);
logger.log(
`\u{1F916} ${source_default.dim(
"Using default value in non-interactive context:"
)} ${source_default.white.bold(options.defaultValue)}`
);
return options.defaultValue;
}
const { value } = await (0, import_prompts.default)({
type: "text",
name: "value",
message: text,
initial: options?.defaultValue,
style: options?.isSecret ? "password" : "default",
onState: /* @__PURE__ */ __name((state2) => {
if (state2.aborted) {
process.nextTick(() => {
process.exit(1);
});
}
}, "onState")
});
return value;
}
async function select(text, options) {
if (isNonInteractiveOrCI()) {
if (options.fallbackOption === void 0) {
throw new NoDefaultValueProvided();
}
logger.log(`? ${text}`);
logger.log(
`\u{1F916} ${source_default.dim(
"Using fallback value in non-interactive context:"
)} ${source_default.white.bold(options.choices[options.fallbackOption].title)}`
);
return options.choices[options.fallbackOption].value;
}
const { value } = await (0, import_prompts.default)({
type: "select",
name: "value",
message: text,
choices: options.choices,
initial: options.defaultOption,
onState: /* @__PURE__ */ __name((state2) => {
if (state2.aborted) {
process.nextTick(() => {
process.exit(1);
});
}
}, "onState")
});
return value;
}
async function multiselect(text, options) {
if (isNonInteractiveOrCI()) {
if (options?.defaultOptions === void 0) {
throw new NoDefaultValueProvided();
}
const defaultTitles = options.defaultOptions.map(
(index) => options.choices[index].title
);
logger.log(`? ${text}`);
logger.log(
`\u{1F916} ${source_default.dim(
"Using default value(s) in non-interactive context:"
)} ${source_default.white.bold(defaultTitles.join(", "))}`
);
return options.defaultOptions.map((index) => options.choices[index].value);
}
const { value } = await (0, import_prompts.default)({
type: "multiselect",
name: "value",
message: text,
choices: options.choices,
instructions: false,
hint: "- Space to select. Return to submit",
onState: /* @__PURE__ */ __name((state2) => {
if (state2.aborted) {
process.nextTick(() => {
process.exit(1);
});
}
}, "onState")
});
return value;
}
var import_prompts, NoDefaultValueProvided;
var init_dialogs = __esm({
"src/dialogs.ts"() {
init_import_meta_url();
init_source();
import_prompts = __toESM(require_prompts3());
init_errors();
init_is_interactive();
init_logger();
NoDefaultValueProvided = class extends UserError {
static {
__name(this, "NoDefaultValueProvided");
}
constructor() {
super("This command cannot be run in a non-interactive context", {
telemetryMessage: true
});
Object.setPrototypeOf(this, new.target.prototype);
}
};
__name(confirm, "confirm");
__name(prompt, "prompt");
__name(select, "select");
__name(multiselect, "multiselect");
}
});
// src/pages/constants.ts
var isWindows, MAX_ASSET_COUNT, MAX_ASSET_SIZE, PAGES_CONFIG_CACHE_FILENAME, MAX_BUCKET_SIZE, MAX_BUCKET_FILE_COUNT, BULK_UPLOAD_CONCURRENCY, MAX_UPLOAD_ATTEMPTS, MAX_UPLOAD_GATEWAY_ERRORS, MAX_DEPLOYMENT_ATTEMPTS, MAX_DEPLOYMENT_STATUS_ATTEMPTS, MAX_CHECK_MISSING_ATTEMPTS, SECONDS_TO_WAIT_FOR_PROXY, MAX_FUNCTIONS_ROUTES_RULES, MAX_FUNCTIONS_ROUTES_RULE_LENGTH, ROUTES_SPEC_VERSION, ROUTES_SPEC_DESCRIPTION;
var init_constants = __esm({
"src/pages/constants.ts"() {
init_import_meta_url();
init_package();
isWindows = process.platform === "win32";
MAX_ASSET_COUNT = 2e4;
MAX_ASSET_SIZE = 25 * 1024 * 1024;
PAGES_CONFIG_CACHE_FILENAME = "pages.json";
MAX_BUCKET_SIZE = 40 * 1024 * 1024;
MAX_BUCKET_FILE_COUNT = isWindows ? 1e3 : 2e3;
BULK_UPLOAD_CONCURRENCY = 3;
MAX_UPLOAD_ATTEMPTS = 5;
MAX_UPLOAD_GATEWAY_ERRORS = 5;
MAX_DEPLOYMENT_ATTEMPTS = 3;
MAX_DEPLOYMENT_STATUS_ATTEMPTS = 5;
MAX_CHECK_MISSING_ATTEMPTS = 5;
SECONDS_TO_WAIT_FOR_PROXY = 5;
MAX_FUNCTIONS_ROUTES_RULES = 100;
MAX_FUNCTIONS_ROUTES_RULE_LENGTH = 100;
ROUTES_SPEC_VERSION = 1;
ROUTES_SPEC_DESCRIPTION = `Generated by wrangler@${version}`;
}
});
// src/pages/functions/routes-validation.ts
function isRoutesJSONSpec(data) {
return typeof data === "object" && data && "version" in data && typeof data.version === "number" && data.version === ROUTES_SPEC_VERSION && Array.isArray(data.include) && Array.isArray(data.exclude) || false;
}
function validateRoutes(routesJSON, routesPath) {
if (!isRoutesJSONSpec(routesJSON)) {
throw new FatalError(
getRoutesValidationErrorMessage(
0 /* INVALID_JSON_SPEC */,
routesPath
),
1
);
}
if (!hasIncludeRules(routesJSON)) {
throw new FatalError(
getRoutesValidationErrorMessage(
1 /* NO_INCLUDE_RULES */,
routesPath
),
1
);
}
if (!hasValidRulesCount(routesJSON)) {
throw new FatalError(
getRoutesValidationErrorMessage(
3 /* TOO_MANY_RULES */,
routesPath
),
1
);
}
if (!hasValidRuleCharCount(routesJSON)) {
throw new FatalError(
getRoutesValidationErrorMessage(
4 /* RULE_TOO_LONG */,
routesPath
),
1
);
}
if (!hasValidRules(routesJSON)) {
throw new FatalError(
getRoutesValidationErrorMessage(
2 /* INVALID_RULES */,
routesPath
),
1
);
}
if (hasOverlappingRules(routesJSON.include) || hasOverlappingRules(routesJSON.exclude)) {
throw new FatalError(
getRoutesValidationErrorMessage(
5 /* OVERLAPPING_RULES */,
routesPath
),
1
);
}
}
function hasIncludeRules(routesJSON) {
if (!routesJSON || !routesJSON.include) {
throw new Error(
"Function `hasIncludeRules` was called out of context. Attempting to validate include rules for routes that are undefined or an invalid RoutesJSONSpec"
);
}
return routesJSON?.include?.length > 0;
}
function hasValidRulesCount(routesJSON) {
if (!routesJSON || !routesJSON.include || !routesJSON.exclude) {
throw new Error(
"Function `hasValidRulesCount` was called out of context. Attempting to validate maximum rules count for routes that are undefined or an invalid RoutesJSONSpec"
);
}
return routesJSON.include.length + routesJSON.exclude.length <= MAX_FUNCTIONS_ROUTES_RULES;
}
function hasValidRuleCharCount(routesJSON) {
if (!routesJSON || !routesJSON.include || !routesJSON.exclude) {
throw new Error(
"Function `hasValidRuleCharCount` was called out of context. Attempting to validate rules maximum character count for routes that are undefined or an invalid RoutesJSONSpec"
);
}
const rules = [...routesJSON.include, ...routesJSON.exclude];
return rules.filter((rule) => rule.length > MAX_FUNCTIONS_ROUTES_RULE_LENGTH).length === 0;
}
function hasValidRules(routesJSON) {
if (!routesJSON || !routesJSON.include || !routesJSON.exclude) {
throw new Error(
"Function `hasValidRules` was called out of context. Attempting to validate rules for routes that are undefined or an invalid RoutesJSONSpec"
);
}
const rules = [...routesJSON.include, ...routesJSON.exclude];
return rules.filter((rule) => !rule.match(/^\//)).length === 0;
}
function hasOverlappingRules(routes) {
if (!routes) {
throw new Error(
"Function `hasverlappingRules` was called out of context. Attempting to validate rules for routes that are undefined"
);
}
const endingSplatRoutes = routes.filter((route) => route.endsWith("/*"));
for (let i5 = 0; i5 < endingSplatRoutes.length; i5++) {
const crrRoute = endingSplatRoutes[i5];
const crrRouteTrimmed = crrRoute.substring(0, crrRoute.length - 1);
for (let j6 = 0; j6 < routes.length; j6++) {
const nextRoute = routes[j6];
if (nextRoute !== crrRoute && nextRoute.startsWith(crrRouteTrimmed)) {
return true;
}
}
}
return false;
}
var init_routes_validation = __esm({
"src/pages/functions/routes-validation.ts"() {
init_import_meta_url();
init_errors();
init_constants();
init_errors3();
__name(isRoutesJSONSpec, "isRoutesJSONSpec");
__name(validateRoutes, "validateRoutes");
__name(hasIncludeRules, "hasIncludeRules");
__name(hasValidRulesCount, "hasValidRulesCount");
__name(hasValidRuleCharCount, "hasValidRuleCharCount");
__name(hasValidRules, "hasValidRules");
__name(hasOverlappingRules, "hasOverlappingRules");
}
});
// src/pages/errors.ts
function getFunctionsNoRoutesWarning(functionsDirectory, suffix) {
return `No routes found when building Functions directory: ${functionsDirectory}${suffix ? " - " + suffix : ""}`;
}
function getRoutesValidationErrorMessage(errorCode, routesPath) {
switch (errorCode) {
case 1 /* NO_INCLUDE_RULES */:
return `Invalid _routes.json file found at: ${routesPath}
Routes must have at least 1 include rule, but no include rules were detected.`;
case 3 /* TOO_MANY_RULES */:
return `Invalid _routes.json file found at: ${routesPath}
Detected rules that are over the ${MAX_FUNCTIONS_ROUTES_RULES} rule limit. Please make sure you have a total of ${MAX_FUNCTIONS_ROUTES_RULES} include and exclude rules combined.`;
case 4 /* RULE_TOO_LONG */:
return `Invalid _routes.json file found at: ${routesPath}
Detected rules the are over the ${MAX_FUNCTIONS_ROUTES_RULE_LENGTH} character limit. Please make sure that each include and exclude routing rule is at most ${MAX_FUNCTIONS_ROUTES_RULE_LENGTH} characters long.`;
case 2 /* INVALID_RULES */:
return `Invalid _routes.json file found at: ${routesPath}
All rules must start with '/'.`;
case 5 /* OVERLAPPING_RULES */:
return `Invalid _routes.json file found at: ${routesPath}
Overlapping rules found. Please make sure that rules ending with a splat (eg. "/api/*") don't overlap any other rules (eg. "/api/foo"). This applies to both include and exclude rules individually.`;
case 0 /* INVALID_JSON_SPEC */:
default:
return `Invalid _routes.json file found at: ${routesPath}
Please make sure the JSON object has the following format:
{
version: ${ROUTES_SPEC_VERSION};
include: string[];
exclude: string[];
}
and that at least one include rule is provided.
`;
}
}
var EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR, EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR, EXIT_CODE_NO_CONFIG_FOUND, EXIT_CODE_INVALID_PAGES_CONFIG, FunctionsBuildError, FunctionsNoRoutesError;
var init_errors3 = __esm({
"src/pages/errors.ts"() {
init_import_meta_url();
init_errors();
init_constants();
init_routes_validation();
EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR = 156;
EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR = 157;
EXIT_CODE_NO_CONFIG_FOUND = 158;
EXIT_CODE_INVALID_PAGES_CONFIG = 159;
FunctionsBuildError = class extends UserError {
static {
__name(this, "FunctionsBuildError");
}
constructor(message) {
super(message);
}
};
FunctionsNoRoutesError = class extends UserError {
static {
__name(this, "FunctionsNoRoutesError");
}
constructor(message) {
super(message);
}
};
__name(getFunctionsNoRoutesWarning, "getFunctionsNoRoutesWarning");
__name(getRoutesValidationErrorMessage, "getRoutesValidationErrorMessage");
}
});
// src/experimental-flags.ts
var import_async_hooks, flags, run, getFlag;
var init_experimental_flags = __esm({
"src/experimental-flags.ts"() {
init_import_meta_url();
import_async_hooks = require("async_hooks");
init_logger();
flags = new import_async_hooks.AsyncLocalStorage();
run = /* @__PURE__ */ __name((flagValues, cb2) => flags.run(flagValues, cb2), "run");
getFlag = /* @__PURE__ */ __name((flag) => {
const store = flags.getStore();
if (store === void 0) {
logger.debug("No experimental flag store instantiated");
}
const value = flags.getStore()?.[flag];
if (value === void 0) {
logger.debug(
`Attempted to use flag "${flag}" which has not been instantiated`
);
}
return value;
}, "getFlag");
}
});
// src/utils/print-bindings.ts
function printBindings(bindings, tailConsumers = [], context2 = {}) {
let hasConnectionStatus = false;
const getMode = createGetMode({
isProvisioning: context2.provisioning,
isLocalDev: context2.local
});
const truncate4 = /* @__PURE__ */ __name((item, maxLength = 40) => {
const s5 = typeof item === "string" ? item : JSON.stringify(item);
if (s5.length < maxLength) {
return s5;
}
return `${s5.substring(0, maxLength - 3)}...`;
}, "truncate");
const output = [];
const {
data_blobs,
durable_objects,
workflows,
kv_namespaces,
send_email,
queues,
d1_databases,
vectorize,
hyperdrive,
r2_buckets,
logfwdr,
secrets_store_secrets,
services,
analytics_engine_datasets,
text_blobs,
browser,
images,
ai: ai2,
version_metadata,
unsafe,
vars,
wasm_modules,
dispatch_namespaces,
mtls_certificates,
pipelines,
assets,
unsafe_hello_world
} = bindings;
if (data_blobs !== void 0 && Object.keys(data_blobs).length > 0) {
output.push(
...Object.entries(data_blobs).map(([key, value]) => ({
name: key,
type: friendlyBindingNames.data_blobs,
value: typeof value === "string" ? truncate4(value) : "<Buffer>",
mode: getMode({ isSimulatedLocally: true })
}))
);
}
if (durable_objects !== void 0 && durable_objects.bindings.length > 0) {
output.push(
...durable_objects.bindings.map(({ name: name2, class_name, script_name }) => {
let value = class_name;
let mode = void 0;
if (script_name) {
if (context2.local && context2.registry !== null) {
const registryDefinition = context2.registry?.[script_name];
hasConnectionStatus = true;
if (registryDefinition && registryDefinition.durableObjects.some(
(d6) => d6.className === class_name
)) {
value += `, defined in ${script_name}`;
mode = getMode({ isSimulatedLocally: true, connected: true });
} else {
value += `, defined in ${script_name}`;
mode = getMode({ isSimulatedLocally: true, connected: false });
}
} else {
value += `, defined in ${script_name}`;
mode = getMode({ isSimulatedLocally: true });
}
} else {
mode = getMode({ isSimulatedLocally: true });
}
return {
name: name2,
type: friendlyBindingNames.durable_objects,
value,
mode
};
})
);
}
if (workflows !== void 0 && workflows.length > 0) {
output.push(
...workflows.map(
({ class_name, script_name, binding, experimental_remote }) => {
let value = class_name;
if (script_name) {
value += ` (defined in ${script_name})`;
}
return {
name: binding,
type: friendlyBindingNames.workflows,
value,
mode: getMode({
isSimulatedLocally: script_name ? !experimental_remote : true
})
};
}
)
);
}
if (kv_namespaces !== void 0 && kv_namespaces.length > 0) {
output.push(
...kv_namespaces.map(({ binding, id, experimental_remote }) => {
return {
name: binding,
type: friendlyBindingNames.kv_namespaces,
value: id,
mode: getMode({
isSimulatedLocally: !experimental_remote
})
};
})
);
}
if (send_email !== void 0 && send_email.length > 0) {
output.push(
...send_email.map((emailBinding) => {
const destination_address = "destination_address" in emailBinding ? emailBinding.destination_address : void 0;
const allowed_destination_addresses = "allowed_destination_addresses" in emailBinding ? emailBinding.allowed_destination_addresses : void 0;
return {
name: emailBinding.name,
type: friendlyBindingNames.send_email,
value: destination_address || allowed_destination_addresses?.join(", ") || "unrestricted",
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? !emailBinding.experimental_remote : true
})
};
})
);
}
if (queues !== void 0 && queues.length > 0) {
output.push(
...queues.map(({ binding, queue_name, experimental_remote }) => {
return {
name: binding,
type: friendlyBindingNames.queues,
value: queue_name,
mode: getMode({
isSimulatedLocally: !experimental_remote
})
};
})
);
}
if (d1_databases !== void 0 && d1_databases.length > 0) {
output.push(
...d1_databases.map(
({
binding,
database_name,
database_id,
preview_database_id,
experimental_remote
}) => {
const value = typeof database_id == "symbol" ? database_id : preview_database_id ?? database_name ?? database_id;
return {
name: binding,
type: friendlyBindingNames.d1_databases,
mode: getMode({
isSimulatedLocally: !experimental_remote
}),
value
};
}
)
);
}
if (vectorize !== void 0 && vectorize.length > 0) {
output.push(
...vectorize.map(({ binding, index_name, experimental_remote }) => {
return {
name: binding,
type: friendlyBindingNames.vectorize,
value: index_name,
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? experimental_remote ? false : void 0 : context2.vectorizeBindToProd ? false : (
/* Vectorize doesn't support local mode */
void 0
)
})
};
})
);
}
if (hyperdrive !== void 0 && hyperdrive.length > 0) {
output.push(
...hyperdrive.map(({ binding, id }) => {
return {
name: binding,
type: friendlyBindingNames.hyperdrive,
value: id,
mode: getMode({ isSimulatedLocally: true })
};
})
);
}
if (r2_buckets !== void 0 && r2_buckets.length > 0) {
output.push(
...r2_buckets.map(
({ binding, bucket_name, jurisdiction, experimental_remote }) => {
const value = typeof bucket_name === "symbol" ? bucket_name : bucket_name ? `${bucket_name}${jurisdiction ? ` (${jurisdiction})` : ""}` : void 0;
return {
name: binding,
type: friendlyBindingNames.r2_buckets,
value,
mode: getMode({
isSimulatedLocally: !experimental_remote
})
};
}
)
);
}
if (logfwdr !== void 0 && logfwdr.bindings.length > 0) {
output.push(
...logfwdr.bindings.map(({ name: name2, destination }) => {
return {
name: name2,
type: friendlyBindingNames.logfwdr,
value: destination,
mode: getMode()
};
})
);
}
if (secrets_store_secrets !== void 0 && secrets_store_secrets.length > 0) {
output.push(
...secrets_store_secrets.map(({ binding, store_id, secret_name }) => {
return {
name: binding,
type: friendlyBindingNames.secrets_store_secrets,
value: `${store_id}/${secret_name}`,
mode: getMode({ isSimulatedLocally: true })
};
})
);
}
if (unsafe_hello_world !== void 0 && unsafe_hello_world.length > 0) {
output.push(
...unsafe_hello_world.map(({ binding, enable_timer }) => {
return {
name: binding,
type: friendlyBindingNames.unsafe_hello_world,
value: enable_timer ? `Timer enabled` : `Timer disabled`,
mode: getMode({ isSimulatedLocally: true })
};
})
);
}
if (services !== void 0 && services.length > 0) {
output.push(
...services.map(
({ binding, service, entrypoint, experimental_remote }) => {
let value = service;
let mode = void 0;
if (entrypoint) {
value += `#${entrypoint}`;
}
if (experimental_remote) {
mode = getMode({ isSimulatedLocally: false });
} else if (context2.local && context2.registry !== null) {
const registryDefinition = context2.registry?.[service];
hasConnectionStatus = true;
if (registryDefinition && (!entrypoint || registryDefinition.entrypointAddresses?.[entrypoint])) {
mode = getMode({ isSimulatedLocally: true, connected: true });
} else {
mode = getMode({ isSimulatedLocally: true, connected: false });
}
}
return {
name: binding,
type: friendlyBindingNames.services,
value,
mode
};
}
)
);
}
if (analytics_engine_datasets !== void 0 && analytics_engine_datasets.length > 0) {
output.push(
...analytics_engine_datasets.map(({ binding, dataset }) => {
return {
name: binding,
type: friendlyBindingNames.analytics_engine_datasets,
value: dataset ?? binding,
mode: getMode({ isSimulatedLocally: true })
};
})
);
}
if (text_blobs !== void 0 && Object.keys(text_blobs).length > 0) {
output.push(
...Object.entries(text_blobs).map(([key, value]) => ({
name: key,
type: friendlyBindingNames.text_blobs,
value: truncate4(value),
mode: getMode({ isSimulatedLocally: true })
}))
);
}
if (browser !== void 0) {
output.push({
name: browser.binding,
type: friendlyBindingNames.browser,
value: void 0,
mode: getMode({
isSimulatedLocally: !(getFlag("REMOTE_BINDINGS") && browser.experimental_remote)
})
});
}
if (images !== void 0) {
output.push({
name: images.binding,
type: friendlyBindingNames.images,
value: void 0,
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? images.experimental_remote === true || images.experimental_remote === void 0 ? false : void 0 : !!context2.imagesLocalMode
})
});
}
if (ai2 !== void 0) {
output.push({
name: ai2.binding,
type: friendlyBindingNames.ai,
value: ai2.staging ? `staging` : void 0,
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? ai2.experimental_remote === true || ai2.experimental_remote === void 0 ? false : void 0 : false
})
});
}
if (pipelines?.length) {
output.push(
...pipelines.map(({ binding, pipeline, experimental_remote }) => ({
name: binding,
type: friendlyBindingNames.pipelines,
value: pipeline,
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? !experimental_remote : true
})
}))
);
}
if (assets !== void 0) {
output.push({
name: assets.binding,
type: friendlyBindingNames.assets,
value: void 0,
mode: getMode({ isSimulatedLocally: true })
});
}
if (version_metadata !== void 0) {
output.push({
name: version_metadata.binding,
type: friendlyBindingNames.version_metadata,
value: void 0,
mode: getMode({ isSimulatedLocally: true })
});
}
if (unsafe?.bindings !== void 0 && unsafe.bindings.length > 0) {
output.push(
...unsafe.bindings.map(({ name: name2, type }) => ({
name: name2,
type: friendlyBindingNames.unsafe,
value: type,
mode: getMode({ isSimulatedLocally: void 0 })
}))
);
}
if (vars !== void 0 && Object.keys(vars).length > 0) {
output.push(
...Object.entries(vars).map(([key, value]) => {
let parsedValue;
if (typeof value === "string") {
parsedValue = `"${truncate4(value)}"`;
} else if (typeof value === "object") {
parsedValue = truncate4(JSON.stringify(value));
} else {
parsedValue = `${truncate4(`${value}`)}`;
}
return {
name: key,
type: friendlyBindingNames.vars,
value: parsedValue,
mode: getMode({ isSimulatedLocally: true })
};
})
);
}
if (wasm_modules !== void 0 && Object.keys(wasm_modules).length > 0) {
output.push(
...Object.entries(wasm_modules).map(([key, value]) => ({
name: key,
type: friendlyBindingNames.wasm_modules,
value: typeof value === "string" ? truncate4(value) : "<Wasm>",
mode: getMode({ isSimulatedLocally: true })
}))
);
}
if (dispatch_namespaces !== void 0 && dispatch_namespaces.length > 0) {
output.push(
...dispatch_namespaces.map(
({ binding, namespace, outbound, experimental_remote }) => {
return {
name: binding,
type: friendlyBindingNames.dispatch_namespaces,
value: outbound ? `${namespace} (outbound -> ${outbound.service})` : namespace,
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? experimental_remote ? false : void 0 : void 0
})
};
}
)
);
}
if (mtls_certificates !== void 0 && mtls_certificates.length > 0) {
output.push(
...mtls_certificates.map(
({ binding, certificate_id, experimental_remote }) => {
return {
name: binding,
type: friendlyBindingNames.mtls_certificates,
value: certificate_id,
mode: getMode({
isSimulatedLocally: getFlag("REMOTE_BINDINGS") ? experimental_remote === true || experimental_remote === void 0 ? false : void 0 : false
})
};
}
)
);
}
if (unsafe?.metadata !== void 0) {
output.push(
...Object.entries(unsafe.metadata).map(([key, value]) => ({
name: key,
type: friendlyBindingNames.unsafe,
value: JSON.stringify(value),
mode: getMode({ isSimulatedLocally: false })
}))
);
}
if (output.length === 0) {
if (context2.warnIfNoBindings) {
if (context2.name && getFlag("MULTIWORKER")) {
logger.log(`No bindings found for ${source_default.blue(context2.name)}`);
} else {
logger.log("No bindings found.");
}
}
} else {
let title2;
if (context2.provisioning) {
title2 = "The following bindings need to be provisioned:";
} else if (context2.name && getFlag("MULTIWORKER")) {
title2 = `${source_default.blue(context2.name)} has access to the following bindings:`;
} else {
title2 = "Your Worker has access to the following bindings:";
}
const headings = {
binding: "Binding",
resource: "Resource",
mode: "Mode"
};
const maxValueLength = Math.max(
...output.map(
(b6) => typeof b6.value === "symbol" ? "inherited".length : b6.value?.length ?? 0
)
);
const maxNameLength = Math.max(...output.map((b6) => b6.name.length));
const maxTypeLength = Math.max(
...output.map((b6) => b6.type.length),
headings.resource.length
);
const maxModeLength = Math.max(
...output.map(
(b6) => b6.mode ? stripAnsi2(b6.mode).length : headings.mode.length
)
);
const hasMode = output.some((b6) => b6.mode);
const bindingPrefix = `env.`;
const bindingLength = bindingPrefix.length + maxNameLength + " (".length + maxValueLength + ")".length;
const columnGapSpaces = 6;
const columnGapSpacesWrapped = 4;
const shouldWrap = bindingLength + columnGapSpaces + maxTypeLength + columnGapSpaces + maxModeLength >= process.stdout.columns;
logger.log(title2);
const columnGap = shouldWrap ? " ".repeat(columnGapSpacesWrapped) : " ".repeat(columnGapSpaces);
logger.log(
`${padEndAnsi(dim(headings.binding), shouldWrap ? bindingPrefix.length + maxNameLength : bindingLength)}${columnGap}${padEndAnsi(dim(headings.resource), maxTypeLength)}${columnGap}${hasMode ? dim(headings.mode) : ""}`
);
for (const binding of output) {
const bindingValue = dim(
typeof binding.value === "symbol" ? source_default.italic("inherited") : binding.value ?? ""
);
const bindingString = padEndAnsi(
`${white(`env.${binding.name}`)}${binding.value && !shouldWrap ? ` (${bindingValue})` : ""}`,
shouldWrap ? bindingPrefix.length + maxNameLength : bindingLength
);
const suffix = shouldWrap ? binding.value ? `
${bindingValue}` : "" : "";
logger.log(
`${bindingString}${columnGap}${brandColor(binding.type.padEnd(maxTypeLength))}${columnGap}${hasMode ? binding.mode : ""}${suffix}`
);
}
logger.log();
}
let title;
if (context2.name && getFlag("MULTIWORKER")) {
title = `${source_default.blue(context2.name)} is sending Tail events to the following Workers:`;
} else {
title = "Your Worker is sending Tail events to the following Workers:";
}
if (tailConsumers !== void 0 && tailConsumers.length > 0) {
logger.log(
`${title}
${tailConsumers.map(({ service }) => {
if (context2.local && context2.registry !== null) {
const registryDefinition = context2.registry?.[service];
hasConnectionStatus = true;
if (registryDefinition) {
return `- ${service} ${source_default.green("[connected]")}`;
} else {
return `- ${service} ${source_default.red("[not connected]")}`;
}
} else {
return `- ${service}`;
}
}).join("\n")}`
);
}
if (hasConnectionStatus) {
logger.once.info(
dim(
`
Service bindings, Durable Object bindings, and Tail consumers connect to other wrangler or vite dev processes running locally, with their connection status indicated by ${source_default.green("[connected]")} or ${source_default.red("[not connected]")}. For more details, refer to https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/#local-development
`
)
);
}
}
function padEndAnsi(str, length) {
return str + " ".repeat(Math.max(0, length - stripAnsi2(str).length));
}
function createGetMode({
isProvisioning = false,
isLocalDev = false
}) {
return /* @__PURE__ */ __name(function bindingMode({
isSimulatedLocally,
connected
} = {}) {
if (isProvisioning || !isLocalDev) {
return void 0;
}
if (isSimulatedLocally === void 0) {
return dim("not supported");
}
return `${isSimulatedLocally ? source_default.blue("local") : source_default.yellow("remote")}${connected === void 0 ? "" : connected ? source_default.green(" [connected]") : source_default.red(" [not connected]")}`;
}, "bindingMode");
}
function warnOrError(type, remote, supports2) {
if (remote === true && supports2 === "local") {
throw new UserError(
`${friendlyBindingNames[type]} bindings do not support accessing remote resources.`,
{
telemetryMessage: true
}
);
}
if (remote === false && supports2 === "remote") {
throw new UserError(
`${friendlyBindingNames[type]} bindings do not support local development. You may be able to set \`experimental_remote: true\` for the binding definition in your configuration file to access a remote version of the resource.`,
{
telemetryMessage: true
}
);
}
if (remote === void 0 && supports2 === "remote") {
logger.warn(
`${friendlyBindingNames[type]} bindings do not support local development, and so parts of your Worker may not work correctly. You may be able to set \`experimental_remote: true\` for the binding definition in your configuration file to access a remote version of the resource.`
);
}
if (remote === void 0 && supports2 === "always-remote") {
logger.warn(
`${friendlyBindingNames[type]} bindings always access remote resources, and so may incur usage charges even in local dev. To suppress this warning, set \`experimental_remote: true\` for the binding definition in your configuration file.`
);
}
}
var friendlyBindingNames;
var init_print_bindings = __esm({
"src/utils/print-bindings.ts"() {
init_import_meta_url();
init_colors();
init_source();
init_strip_ansi();
init_errors();
init_experimental_flags();
init_logger();
friendlyBindingNames = {
data_blobs: "Data Blob",
durable_objects: "Durable Object",
kv_namespaces: "KV Namespace",
send_email: "Send Email",
queues: "Queue",
d1_databases: "D1 Database",
vectorize: "Vectorize Index",
hyperdrive: "Hyperdrive Config",
r2_buckets: "R2 Bucket",
logfwdr: "logfwdr",
services: "Worker",
analytics_engine_datasets: "Analytics Engine Dataset",
text_blobs: "Text Blob",
browser: "Browser",
ai: "AI",
images: "Images",
version_metadata: "Worker Version Metadata",
unsafe: "Unsafe Metadata",
vars: "Environment Variable",
wasm_modules: "Wasm Module",
dispatch_namespaces: "Dispatch Namespace",
mtls_certificates: "mTLS Certificate",
workflows: "Workflow",
pipelines: "Pipeline",
secrets_store_secrets: "Secrets Store Secret",
assets: "Assets",
unsafe_hello_world: "Hello World"
};
__name(printBindings, "printBindings");
__name(padEndAnsi, "padEndAnsi");
__name(createGetMode, "createGetMode");
__name(warnOrError, "warnOrError");
}
});
// ../../node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js
var init_yocto_queue = __esm({
"../../node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js
var init_p_limit = __esm({
"../../node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js"() {
init_import_meta_url();
init_yocto_queue();
}
});
// ../../node_modules/.pnpm/p-locate@6.0.0/node_modules/p-locate/index.js
var init_p_locate = __esm({
"../../node_modules/.pnpm/p-locate@6.0.0/node_modules/p-locate/index.js"() {
init_import_meta_url();
init_p_limit();
}
});
// ../../node_modules/.pnpm/locate-path@7.1.0/node_modules/locate-path/index.js
function checkType(type) {
if (type in typeMappings) {
return;
}
throw new Error(`Invalid type specified: ${type}`);
}
function locatePathSync(paths, {
cwd: cwd2 = import_node_process6.default.cwd(),
type = "file",
allowSymlinks = true
} = {}) {
checkType(type);
cwd2 = toPath(cwd2);
const statFunction = allowSymlinks ? import_node_fs2.default.statSync : import_node_fs2.default.lstatSync;
for (const path_ of paths) {
try {
const stat8 = statFunction(import_node_path5.default.resolve(cwd2, path_));
if (matchType(type, stat8)) {
return path_;
}
} catch {
}
}
}
var import_node_process6, import_node_path5, import_node_fs2, import_node_url, typeMappings, matchType, toPath;
var init_locate_path = __esm({
"../../node_modules/.pnpm/locate-path@7.1.0/node_modules/locate-path/index.js"() {
init_import_meta_url();
import_node_process6 = __toESM(require("process"), 1);
import_node_path5 = __toESM(require("path"), 1);
import_node_fs2 = __toESM(require("fs"), 1);
import_node_url = require("url");
init_p_locate();
typeMappings = {
directory: "isDirectory",
file: "isFile"
};
__name(checkType, "checkType");
matchType = /* @__PURE__ */ __name((type, stat8) => type === void 0 || stat8[typeMappings[type]](), "matchType");
toPath = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? (0, import_node_url.fileURLToPath)(urlOrPath) : urlOrPath, "toPath");
__name(locatePathSync, "locatePathSync");
}
});
// ../../node_modules/.pnpm/path-exists@5.0.0/node_modules/path-exists/index.js
var import_node_fs3;
var init_path_exists = __esm({
"../../node_modules/.pnpm/path-exists@5.0.0/node_modules/path-exists/index.js"() {
init_import_meta_url();
import_node_fs3 = __toESM(require("fs"), 1);
}
});
// ../../node_modules/.pnpm/find-up@6.3.0/node_modules/find-up/index.js
function findUpMultipleSync(name2, options = {}) {
let directory = import_node_path6.default.resolve(toPath2(options.cwd) || "");
const { root } = import_node_path6.default.parse(directory);
const stopAt = options.stopAt || root;
const limit = options.limit || Number.POSITIVE_INFINITY;
const paths = [name2].flat();
const runMatcher = /* @__PURE__ */ __name((locateOptions) => {
if (typeof name2 !== "function") {
return locatePathSync(paths, locateOptions);
}
const foundPath = name2(locateOptions.cwd);
if (typeof foundPath === "string") {
return locatePathSync([foundPath], locateOptions);
}
return foundPath;
}, "runMatcher");
const matches = [];
while (true) {
const foundPath = runMatcher({ ...options, cwd: directory });
if (foundPath === findUpStop) {
break;
}
if (foundPath) {
matches.push(import_node_path6.default.resolve(directory, foundPath));
}
if (directory === stopAt || matches.length >= limit) {
break;
}
directory = import_node_path6.default.dirname(directory);
}
return matches;
}
function findUpSync(name2, options = {}) {
const matches = findUpMultipleSync(name2, { ...options, limit: 1 });
return matches[0];
}
var import_node_path6, import_node_url2, toPath2, findUpStop;
var init_find_up = __esm({
"../../node_modules/.pnpm/find-up@6.3.0/node_modules/find-up/index.js"() {
init_import_meta_url();
import_node_path6 = __toESM(require("path"), 1);
import_node_url2 = require("url");
init_locate_path();
init_path_exists();
toPath2 = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? (0, import_node_url2.fileURLToPath)(urlOrPath) : urlOrPath, "toPath");
findUpStop = Symbol("findUpStop");
__name(findUpMultipleSync, "findUpMultipleSync");
__name(findUpSync, "findUpSync");
}
});
// src/config/config-helpers.ts
function resolveWranglerConfigPath({
config,
script
}, options) {
if (config !== void 0) {
return { userConfigPath: config, configPath: config };
}
const leafPath = script !== void 0 ? import_node_path7.default.dirname(script) : process.cwd();
return findWranglerConfig(leafPath, options);
}
function findWranglerConfig(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
const userConfigPath = findUpSync(`wrangler.json`, { cwd: referencePath }) ?? findUpSync(`wrangler.jsonc`, { cwd: referencePath }) ?? findUpSync(`wrangler.toml`, { cwd: referencePath });
return {
userConfigPath,
configPath: useRedirectIfAvailable ? findRedirectedWranglerConfig(referencePath, userConfigPath) : userConfigPath
};
}
function findRedirectedWranglerConfig(cwd2, userConfigPath) {
const PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";
const deployConfigPath = findUpSync(PATH_TO_DEPLOY_CONFIG, { cwd: cwd2 });
if (deployConfigPath === void 0) {
return userConfigPath;
}
let redirectedConfigPath;
const deployConfigFile = readFileSync6(deployConfigPath);
try {
const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
redirectedConfigPath = deployConfig.configPath && import_node_path7.default.resolve(import_node_path7.default.dirname(deployConfigPath), deployConfig.configPath);
} catch (e7) {
throw new UserError(
esm_default2`
Failed to parse the deploy configuration file at ${import_node_path7.default.relative(".", deployConfigPath)}
${e7 instanceof ParseError ? formatMessage(e7) : e7}
`
);
}
if (!redirectedConfigPath) {
throw new UserError(esm_default2`
A deploy configuration file was found at "${import_node_path7.default.relative(".", deployConfigPath)}".
But this is not valid - the required "configPath" property was not found.
Instead this file contains:
\`\`\`
${deployConfigFile}
\`\`\`
`);
}
if (redirectedConfigPath) {
if (!import_node_fs4.default.existsSync(redirectedConfigPath)) {
throw new UserError(esm_default2`
There is a deploy configuration at "${import_node_path7.default.relative(".", deployConfigPath)}".
But the redirected configuration path it points to, "${import_node_path7.default.relative(".", redirectedConfigPath)}", does not exist.
`);
}
if (userConfigPath) {
if (import_node_path7.default.join(import_node_path7.default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) {
throw new UserError(esm_default2`
Found both a user configuration file at "${import_node_path7.default.relative(".", userConfigPath)}"
and a deploy configuration file at "${import_node_path7.default.relative(".", deployConfigPath)}".
But these do not share the same base path so it is not clear which should be used.
`);
}
}
logger.info(esm_default2`
Using redirected Wrangler configuration.
- Configuration being used: "${import_node_path7.default.relative(".", redirectedConfigPath)}"
- Original user's configuration: "${userConfigPath ? import_node_path7.default.relative(".", userConfigPath) : "<no user config found>"}"
- Deploy configuration file: "${import_node_path7.default.relative(".", deployConfigPath)}"
`);
return redirectedConfigPath;
}
}
var import_node_fs4, import_node_path7;
var init_config_helpers = __esm({
"src/config/config-helpers.ts"() {
init_import_meta_url();
import_node_fs4 = __toESM(require("fs"));
import_node_path7 = __toESM(require("path"));
init_find_up();
init_esm2();
init_errors();
init_logger();
init_parse();
__name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
__name(findWranglerConfig, "findWranglerConfig");
__name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
}
});
// src/config/patch-config.ts
var import_fs8, import_toml2, experimental_patchConfig, getJSONPath, PatchConfigError;
var init_patch_config = __esm({
"src/config/patch-config.ts"() {
init_import_meta_url();
import_fs8 = require("fs");
import_toml2 = __toESM(require_toml());
init_main();
init_parse();
experimental_patchConfig = /* @__PURE__ */ __name((configPath, patch, isArrayInsertion = true) => {
let configString = readFileSync6(configPath);
if (configPath.endsWith("toml")) {
if (configString.includes("#")) {
throw new PatchConfigError(
"cannot patch .toml config if comments are present"
);
} else {
configString = JSON.stringify(parseTOML(configString));
}
}
const patchPaths = [];
getJSONPath(patch, patchPaths, isArrayInsertion);
for (const patchPath of patchPaths) {
const value = patchPath.pop();
const edit = modify(configString, patchPath, value, {
isArrayInsertion
});
configString = applyEdits(configString, edit);
}
const formatEdit = format4(configString, void 0, {});
configString = applyEdits(configString, formatEdit);
if (configPath.endsWith(".toml")) {
configString = import_toml2.default.stringify(parseJSONC(configString));
}
(0, import_fs8.writeFileSync)(configPath, configString);
return configString;
}, "experimental_patchConfig");
getJSONPath = /* @__PURE__ */ __name((obj, allPaths, isArrayInsertion, prevPath = []) => {
for (const [k6, v7] of Object.entries(obj)) {
const currentPath = [...prevPath, k6];
if (Array.isArray(v7)) {
v7.forEach((x6, i5) => {
if (isArrayInsertion) {
allPaths.push([...currentPath, -1, x6]);
} else if (typeof x6 === "object") {
getJSONPath(x6, allPaths, isArrayInsertion, [...currentPath, i5]);
} else {
allPaths.push([...currentPath, i5, x6]);
}
});
} else if (typeof v7 === "object") {
getJSONPath(v7, allPaths, isArrayInsertion, currentPath);
} else {
allPaths.push([...currentPath, v7]);
}
}
}, "getJSONPath");
PatchConfigError = class extends Error {
static {
__name(this, "PatchConfigError");
}
};
}
});
// ../../node_modules/.pnpm/pretty-bytes@6.1.1/node_modules/pretty-bytes/index.js
function prettyBytes(number, options) {
if (!Number.isFinite(number)) {
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
}
options = {
bits: false,
binary: false,
space: true,
...options
};
const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS;
const separator = options.space ? " " : "";
if (options.signed && number === 0) {
return ` 0${separator}${UNITS[0]}`;
}
const isNegative = number < 0;
const prefix = isNegative ? "-" : options.signed ? "+" : "";
if (isNegative) {
number = -number;
}
let localeOptions;
if (options.minimumFractionDigits !== void 0) {
localeOptions = { minimumFractionDigits: options.minimumFractionDigits };
}
if (options.maximumFractionDigits !== void 0) {
localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions };
}
if (number < 1) {
const numberString2 = toLocaleString(number, options.locale, localeOptions);
return prefix + numberString2 + separator + UNITS[0];
}
const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1);
number /= (options.binary ? 1024 : 1e3) ** exponent;
if (!localeOptions) {
number = number.toPrecision(3);
}
const numberString = toLocaleString(Number(number), options.locale, localeOptions);
const unit = UNITS[exponent];
return prefix + numberString + separator + unit;
}
var BYTE_UNITS, BIBYTE_UNITS, BIT_UNITS, BIBIT_UNITS, toLocaleString;
var init_pretty_bytes = __esm({
"../../node_modules/.pnpm/pretty-bytes@6.1.1/node_modules/pretty-bytes/index.js"() {
init_import_meta_url();
BYTE_UNITS = [
"B",
"kB",
"MB",
"GB",
"TB",
"PB",
"EB",
"ZB",
"YB"
];
BIBYTE_UNITS = [
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB"
];
BIT_UNITS = [
"b",
"kbit",
"Mbit",
"Gbit",
"Tbit",
"Pbit",
"Ebit",
"Zbit",
"Ybit"
];
BIBIT_UNITS = [
"b",
"kibit",
"Mibit",
"Gibit",
"Tibit",
"Pibit",
"Eibit",
"Zibit",
"Yibit"
];
toLocaleString = /* @__PURE__ */ __name((number, locale, options) => {
let result = number;
if (typeof locale === "string" || Array.isArray(locale)) {
result = number.toLocaleString(locale, options);
} else if (locale === true || options !== void 0) {
result = number.toLocaleString(void 0, options);
}
return result;
}, "toLocaleString");
__name(prettyBytes, "prettyBytes");
}
});
// src/dev/get-local-persistence-path.ts
function getLocalPersistencePath(persistTo, { userConfigPath }) {
return persistTo ? (
// If path specified, always treat it as relative to cwd()
import_node_path8.default.resolve(process.cwd(), persistTo)
) : (
// Otherwise, treat it as relative to the Wrangler configuration file,
// if one can be found, otherwise cwd()
import_node_path8.default.resolve(
userConfigPath ? import_node_path8.default.dirname(userConfigPath) : process.cwd(),
".wrangler/state"
)
);
}
var import_node_path8;
var init_get_local_persistence_path = __esm({
"src/dev/get-local-persistence-path.ts"() {
init_import_meta_url();
import_node_path8 = __toESM(require("path"));
__name(getLocalPersistencePath, "getLocalPersistencePath");
}
});
// src/queues/client.ts
async function createQueue(config, body) {
const accountId = await requireAuth(config);
return fetchResult(config, queuesUrl(accountId), {
method: "POST",
body: JSON.stringify(body)
});
}
async function updateQueue(config, body, queue_id) {
const accountId = await requireAuth(config);
return fetchResult(config, queuesUrl(accountId, queue_id), {
method: "PATCH",
body: JSON.stringify(body)
});
}
async function deleteQueue(config, queueName) {
const queue = await getQueue(config, queueName);
return deleteQueueById(config, queue.queue_id);
}
async function deleteQueueById(config, queueId) {
const accountId = await requireAuth(config);
return fetchResult(config, queuesUrl(accountId, queueId), {
method: "DELETE"
});
}
async function listQueues(config, page, name2) {
page = page ?? 1;
const accountId = await requireAuth(config);
const params = new import_node_url3.URLSearchParams({ page: page.toString() });
if (name2) {
params.append("name", name2);
}
return fetchResult(config, queuesUrl(accountId), {}, params);
}
async function listAllQueues(config, queueNames) {
const accountId = await requireAuth(config);
const params = new import_node_url3.URLSearchParams();
queueNames.forEach((e7) => {
params.append("name", e7);
});
return fetchPagedListResult(config, queuesUrl(accountId), {}, params);
}
async function getQueue(config, queueName) {
const queues = await listQueues(config, 1, queueName);
if (queues.length === 0) {
throw new UserError(
`Queue "${queueName}" does not exist. To create it, run: wrangler queues create ${queueName}`
);
}
return queues[0];
}
async function ensureQueuesExistByConfig(config) {
const producers = (config.queues.producers || []).map(
(producer) => producer.queue
);
const consumers = (config.queues.consumers || []).map(
(consumer) => consumer.queue
);
const queueNames = producers.concat(consumers);
await ensureQueuesExist(config, queueNames);
}
async function ensureQueuesExist(config, queueNames) {
if (queueNames.length > 0) {
const existingQueues = (await listAllQueues(config, queueNames)).map(
(q6) => q6.queue_name
);
if (queueNames.length !== existingQueues.length) {
const queueSet = new Set(existingQueues);
for (const queue of queueNames) {
if (!queueSet.has(queue)) {
throw new UserError(
`Queue "${queue}" does not exist. To create it, run: wrangler queues create ${queue}`
);
}
}
}
}
}
async function getQueueById(config, accountId, queueId) {
return fetchResult(config, queuesUrl(accountId, queueId), {});
}
async function postConsumer(config, queueName, body) {
const queue = await getQueue(config, queueName);
return postConsumerById(config, queue.queue_id, body);
}
async function postConsumerById(config, queueId, body) {
const accountId = await requireAuth(config);
return fetchResult(config, queueConsumersUrl(accountId, queueId), {
method: "POST",
body: JSON.stringify(body)
});
}
async function putConsumerById(config, queueId, consumerId, body) {
const accountId = await requireAuth(config);
return fetchResult(
config,
queueConsumersUrl(accountId, queueId, consumerId),
{
method: "PUT",
body: JSON.stringify(body)
}
);
}
async function putConsumer(config, queueName, scriptName, envName, body) {
const queue = await getQueue(config, queueName);
const targetConsumer = await resolveWorkerConsumerByName(
config,
scriptName,
envName,
queue
);
return putConsumerById(
config,
queue.queue_id,
targetConsumer.consumer_id,
body
);
}
async function resolveWorkerConsumerByName(config, consumerName, envName, queue) {
const queueName = queue.queue_name;
const consumers = queue.consumers.filter(
(c6) => c6.type === "worker" && (c6.script === consumerName || c6.service === consumerName)
);
if (consumers.length === 0) {
throw new UserError(
`No worker consumer '${consumerName}' exists for queue ${queue.queue_name}`
);
}
if (consumers.length > 1) {
const targetEnv = envName ?? await getDefaultService(config, consumerName);
const targetConsumers = consumers.filter(
(c6) => c6.environment === targetEnv
);
if (targetConsumers.length === 0) {
throw new UserError(
`No worker consumer '${consumerName}' exists for queue ${queueName}`
);
}
return consumers[0];
}
if (consumers[0].service) {
const targetEnv = envName ?? await getDefaultService(config, consumerName);
if (targetEnv != consumers[0].environment) {
throw new UserError(
`No worker consumer '${consumerName}' exists for queue ${queueName}`
);
}
}
return consumers[0];
}
async function deleteConsumerById(config, queueId, consumerId) {
const accountId = await requireAuth(config);
return fetchResult(
config,
queueConsumersUrl(accountId, queueId, consumerId),
{
method: "DELETE"
}
);
}
async function deletePullConsumer(config, queueName) {
const queue = await getQueue(config, queueName);
const consumer = queue.consumers[0];
if (consumer?.type !== "http_pull") {
throw new UserError(`No http_pull consumer exists for queue ${queueName}`);
}
return deleteConsumerById(config, queue.queue_id, consumer.consumer_id);
}
async function getDefaultService(config, serviceName) {
const accountId = await requireAuth(config);
const service = await fetchResult(
config,
`/accounts/${accountId}/workers/services/${serviceName}`,
{
method: "GET"
}
);
logger.info(service);
return service.default_environment.environment;
}
async function deleteWorkerConsumer(config, queueName, scriptName, envName) {
const queue = await getQueue(config, queueName);
const targetConsumer = await resolveWorkerConsumerByName(
config,
scriptName,
envName,
queue
);
return deleteConsumerById(config, queue.queue_id, targetConsumer.consumer_id);
}
async function purgeQueue(config, queueName) {
const accountId = await requireAuth(config);
const queue = await getQueue(config, queueName);
const purgeURL = `${queuesUrl(accountId, queue.queue_id)}/purge`;
const body = { delete_messages_permanently: true };
return fetchResult(config, purgeURL, {
method: "POST",
body: JSON.stringify(body)
});
}
async function createEventSubscription(config, queueName, request4) {
const accountId = await requireAuth(config);
const queue = await getQueue(config, queueName);
const body = {
...request4,
destination: {
type: "queues.queue",
queue_id: queue.queue_id
}
};
return fetchResult(
config,
`/accounts/${accountId}/event_subscriptions/subscriptions`,
{
method: "POST",
body: JSON.stringify(body)
}
);
}
async function listEventSubscriptions(config, queueName, options) {
const accountId = await requireAuth(config);
const queue = await getQueue(config, queueName);
const params = new import_node_url3.URLSearchParams({
queue_id: queue.queue_id,
page: (options?.page || 1).toString(),
per_page: (options?.per_page || 20).toString()
});
return fetchResult(
config,
`/accounts/${accountId}/event_subscriptions/subscriptions`,
{},
params
);
}
async function getEventSubscription(config, subscriptionId) {
const accountId = await requireAuth(config);
return fetchResult(
config,
`/accounts/${accountId}/event_subscriptions/subscriptions/${subscriptionId}`
);
}
async function updateEventSubscription(config, subscriptionId, request4) {
const accountId = await requireAuth(config);
return fetchResult(
config,
`/accounts/${accountId}/event_subscriptions/subscriptions/${subscriptionId}`,
{
method: "PATCH",
body: JSON.stringify(request4)
}
);
}
async function deleteEventSubscription(config, subscriptionId) {
const accountId = await requireAuth(config);
return fetchResult(
config,
`/accounts/${accountId}/event_subscriptions/subscriptions/${subscriptionId}`,
{
method: "DELETE"
}
);
}
async function getEventSubscriptionForQueue(config, queueName, subscriptionId) {
const subscription = await getEventSubscription(config, subscriptionId);
const queue = await getQueue(config, queueName);
if (subscription.destination.queue_id !== queue.queue_id) {
throw new UserError(
`Subscription '${subscriptionId}' does not belong to queue '${queueName}'. This subscription is configured for a different queue.`
);
}
return subscription;
}
var import_node_url3, queuesUrl, queueConsumersUrl;
var init_client2 = __esm({
"src/queues/client.ts"() {
init_import_meta_url();
import_node_url3 = require("url");
init_cfetch();
init_errors();
init_logger();
init_user2();
queuesUrl = /* @__PURE__ */ __name((accountId, queueId) => {
let url4 = `/accounts/${accountId}/queues`;
if (queueId) {
url4 += `/${queueId}`;
}
return url4;
}, "queuesUrl");
queueConsumersUrl = /* @__PURE__ */ __name((accountId, queueId, consumerId) => {
let url4 = `${queuesUrl(accountId, queueId)}/consumers`;
if (consumerId) {
url4 += `/${consumerId}`;
}
return url4;
}, "queueConsumersUrl");
__name(createQueue, "createQueue");
__name(updateQueue, "updateQueue");
__name(deleteQueue, "deleteQueue");
__name(deleteQueueById, "deleteQueueById");
__name(listQueues, "listQueues");
__name(listAllQueues, "listAllQueues");
__name(getQueue, "getQueue");
__name(ensureQueuesExistByConfig, "ensureQueuesExistByConfig");
__name(ensureQueuesExist, "ensureQueuesExist");
__name(getQueueById, "getQueueById");
__name(postConsumer, "postConsumer");
__name(postConsumerById, "postConsumerById");
__name(putConsumerById, "putConsumerById");
__name(putConsumer, "putConsumer");
__name(resolveWorkerConsumerByName, "resolveWorkerConsumerByName");
__name(deleteConsumerById, "deleteConsumerById");
__name(deletePullConsumer, "deletePullConsumer");
__name(getDefaultService, "getDefaultService");
__name(deleteWorkerConsumer, "deleteWorkerConsumer");
__name(purgeQueue, "purgeQueue");
__name(createEventSubscription, "createEventSubscription");
__name(listEventSubscriptions, "listEventSubscriptions");
__name(getEventSubscription, "getEventSubscription");
__name(updateEventSubscription, "updateEventSubscription");
__name(deleteEventSubscription, "deleteEventSubscription");
__name(getEventSubscriptionForQueue, "getEventSubscriptionForQueue");
}
});
// src/r2/helpers.ts
async function listR2Buckets(complianceConfig, accountId, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const results = await fetchResult(complianceConfig, `/accounts/${accountId}/r2/buckets`, { headers });
return results.buckets;
}
function tablefromR2BucketsListResponse(buckets) {
const rows = [];
for (const bucket of buckets) {
rows.push({
name: bucket.name,
creation_date: bucket.creation_date
});
}
return rows;
}
async function getR2Bucket(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}`,
{
method: "GET",
headers
}
);
return result;
}
async function getR2BucketMetrics(complianceConfig, accountId, bucketName, jurisdiction) {
const today = /* @__PURE__ */ new Date();
const yesterday = new Date(new Date(today).setDate(today.getDate() - 1));
let fullBucketName = bucketName;
if (jurisdiction) {
fullBucketName = `${jurisdiction}_${bucketName}`;
}
const storageMetricsQuery = `
query getR2StorageMetrics($accountTag: String, $filter: R2StorageAdaptiveGroupsFilter_InputObject) {
viewer {
accounts(filter: { accountTag: $accountTag }) {
r2StorageAdaptiveGroups(
limit: 1
filter: $filter
orderBy: [datetime_DESC]
) {
max {
objectCount
payloadSize
metadataSize
}
dimensions {
datetime
}
}
}
}
}
`;
const variables = {
accountTag: accountId,
filter: {
datetime_geq: yesterday.toISOString(),
datetime_leq: today.toISOString(),
bucketName: fullBucketName
}
};
const storageMetricsResult = await fetchGraphqlResult(complianceConfig, {
method: "POST",
body: JSON.stringify({
query: storageMetricsQuery,
operationName: "getR2StorageMetrics",
variables
}),
headers: {
"Content-Type": "application/json"
}
});
if (storageMetricsResult) {
const metricsData = storageMetricsResult.data?.viewer?.accounts[0]?.r2StorageAdaptiveGroups?.[0];
if (metricsData && metricsData.max) {
const objectCount = metricsData.max.objectCount || 0;
const totalSize = (metricsData.max.payloadSize || 0) + (metricsData.max.metadataSize || 0);
return {
objectCount,
totalSize: prettyBytes(totalSize)
};
}
}
return { objectCount: 0, totalSize: "0 B" };
}
async function createR2Bucket(complianceConfig, accountId, bucketName, location, jurisdiction, storageClass) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets`,
{
method: "POST",
body: JSON.stringify({
name: bucketName,
...storageClass !== void 0 && { storageClass },
...location !== void 0 && { locationHint: location }
}),
headers
}
);
}
async function updateR2BucketStorageClass(complianceConfig, accountId, bucketName, storageClass, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
headers["cf-r2-storage-class"] = storageClass;
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}`,
{
method: "PATCH",
headers
}
);
}
async function deleteR2Bucket(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}`,
{ method: "DELETE", headers }
);
}
function bucketAndKeyFromObjectPath(objectPath = "") {
const match2 = /^(?<bucket>[^/]+)\/(?<key>.*)/.exec(objectPath);
if (match2 === null || !match2.groups) {
throw new UserError(
`The object path must be in the form of {bucket}/{key} you provided ${objectPath}`
);
}
const { bucket, key } = match2.groups;
if (!isValidR2BucketName(bucket)) {
throw new UserError(
`The bucket name "${bucket}" is invalid. ${bucketFormatMessage}`
);
}
return { bucket, key };
}
async function getR2Object(complianceConfig, accountId, bucketName, objectName, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const response = await fetchR2Objects(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/objects/${objectName}`,
{
method: "GET",
headers
}
);
return response === null ? null : response.body;
}
async function putR2Object(complianceConfig, accountId, bucketName, objectName, object, options, jurisdiction, storageClass) {
const headerKeys = [
"content-length",
"content-type",
"content-disposition",
"content-encoding",
"content-language",
"cache-control",
"expires"
];
const headers = {};
for (const key of headerKeys) {
const value = options[key] || "";
if (value && typeof value === "string") {
headers[key] = value;
}
}
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
if (storageClass !== void 0) {
headers["cf-r2-storage-class"] = storageClass;
}
const result = await fetchR2Objects(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/objects/${objectName}`,
{
body: object,
headers,
method: "PUT",
duplex: "half"
}
);
if (result === null) {
throw new UserError("The specified bucket does not exist.");
}
}
async function deleteR2Object(complianceConfig, accountId, bucketName, objectName, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchR2Objects(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/objects/${objectName}`,
{ method: "DELETE", headers }
);
}
async function usingLocalBucket(persistTo, config, bucketName, closure) {
const persist = getLocalPersistencePath(persistTo, config);
const defaultPersistRoot = getDefaultPersistRoot(persist);
const mf = new import_miniflare2.Miniflare({
modules: true,
// TODO(soon): import `reduceError()` from `miniflare:shared`
script: `
function reduceError(e) {
return {
name: e?.name,
message: e?.message ?? String(e),
stack: e?.stack,
cause: e?.cause === undefined ? undefined : reduceError(e.cause),
};
}
export default {
async fetch(request, env, ctx) {
try {
if (request.method !== "PUT") return new Response(null, { status: 405 });
const url = new URL(request.url);
const key = url.pathname.substring(1);
const optsHeader = request.headers.get("Wrangler-R2-Put-Options");
const opts = JSON.parse(optsHeader);
await env.BUCKET.put(key, request.body, opts);
return new Response(null, { status: 204 });
} catch (e) {
const error = reduceError(e);
return Response.json(error, {
status: 500,
headers: { "MF-Experimental-Error-Stack": "true" },
});
}
}
}`,
defaultPersistRoot,
r2Buckets: { BUCKET: bucketName }
});
const bucket = await mf.getR2Bucket("BUCKET");
try {
return await closure(bucket, mf);
} finally {
await mf.dispose();
}
}
async function getR2Sippy(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/sippy`,
{ method: "GET", headers }
);
}
async function deleteR2Sippy(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/sippy`,
{ method: "DELETE", headers }
);
}
async function putR2Sippy(complianceConfig, accountId, bucketName, params, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction !== void 0) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/sippy`,
{ method: "PUT", body: JSON.stringify(params), headers }
);
}
async function getR2Catalog(complianceConfig, accountId, bucketName) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2-catalog/${bucketName}`,
{
method: "GET"
}
);
}
async function enableR2Catalog(complianceConfig, accountId, bucketName) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2-catalog/${bucketName}/enable`,
{
method: "POST"
}
);
}
async function disableR2Catalog(complianceConfig, accountId, bucketName) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2-catalog/${bucketName}/disable`,
{
method: "POST"
}
);
}
function eventNotificationHeaders(apiCredentials, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if ("apiToken" in apiCredentials) {
headers["Authorization"] = `Bearer ${apiCredentials.apiToken}`;
} else {
headers["X-Auth-Key"] = apiCredentials.authKey;
headers["X-Auth-Email"] = apiCredentials.authEmail;
}
if (jurisdiction !== "") {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
return headers;
}
function tableFromNotificationGetResponse(response) {
const rows = [];
for (const entry of response.queues) {
for (const {
prefix = "",
suffix = "",
actions,
ruleId,
createdAt = ""
} of entry.rules) {
rows.push({
rule_id: ruleId,
created_at: createdAt,
queue_name: entry.queueName,
prefix: prefix || "(all prefixes)",
suffix: suffix || "(all suffixes)",
event_type: actions.join(",")
});
}
}
return rows;
}
async function listEventNotificationConfig(config, apiCredentials, accountId, bucketName, jurisdiction) {
const headers = eventNotificationHeaders(apiCredentials, jurisdiction);
logger.log(`Fetching notification rules for bucket ${bucketName}...`);
const res = await fetchResult(
config,
`/accounts/${accountId}/event_notifications/r2/${bucketName}/configuration`,
{ method: "GET", headers }
);
if ("bucketName" in res && "queues" in res) {
return res;
}
const oldResult = res;
const [oldBucketName, oldDetail] = Object.entries(oldResult)[0];
const newResult = {
bucketName: oldBucketName,
queues: await Promise.all(
Object.values(oldDetail).map(async (oldQueue) => {
const newQueue = {
queueId: oldQueue.queue,
queueName: (await getQueueById(config, accountId, oldQueue.queue)).queue_name,
rules: oldQueue.rules.map((oldRule) => {
const newRule = {
ruleId: "",
prefix: oldRule.prefix,
suffix: oldRule.suffix,
actions: oldRule.actions
};
return newRule;
})
};
return newQueue;
})
)
};
return newResult;
}
async function putEventNotificationConfig(config, apiCredentials, accountId, bucketName, jurisdiction, queueName, eventTypes, prefix, suffix, description) {
const queue = await getQueue(config, queueName);
const headers = eventNotificationHeaders(apiCredentials, jurisdiction);
let actions = [];
for (const et of eventTypes) {
actions = actions.concat(actionsForEventCategories[et]);
}
const body = description === void 0 ? {
rules: [{ prefix, suffix, actions }]
} : {
rules: [{ prefix, suffix, actions, description }]
};
const ruleFor = eventTypes.map(
(et) => et === "object-create" ? "creation" : "deletion"
);
logger.log(
`Creating event notification rule for object ${ruleFor.join(
" and "
)} (${actions.join(",")})`
);
return await fetchResult(
config,
`/accounts/${accountId}/event_notifications/r2/${bucketName}/configuration/queues/${queue.queue_id}`,
{ method: "PUT", body: JSON.stringify(body), headers }
);
}
async function deleteEventNotificationConfig(config, apiCredentials, accountId, bucketName, jurisdiction, queueName, ruleId) {
const queue = await getQueue(config, queueName);
const headers = eventNotificationHeaders(apiCredentials, jurisdiction);
if (ruleId !== void 0) {
logger.log(`Deleting event notifications rule "${ruleId}"...`);
const body = ruleId !== void 0 ? {
ruleIds: [ruleId]
} : {};
return await fetchResult(
config,
`/accounts/${accountId}/event_notifications/r2/${bucketName}/configuration/queues/${queue.queue_id}`,
{ method: "DELETE", body: JSON.stringify(body), headers }
);
} else {
logger.log(
`Deleting event notification rules associated with queue ${queueName}...`
);
return await fetchResult(
config,
`/accounts/${accountId}/event_notifications/r2/${bucketName}/configuration/queues/${queue.queue_id}`,
{ method: "DELETE", headers }
);
}
}
async function getCustomDomain(complianceConfig, accountId, bucketName, domainName, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/custom/${domainName}`,
{
method: "GET",
headers
}
);
return result;
}
async function attachCustomDomainToBucket(complianceConfig, accountId, bucketName, domainConfig, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/custom`,
{
method: "POST",
headers,
body: JSON.stringify({
...domainConfig,
enabled: true
})
}
);
}
async function removeCustomDomainFromBucket(complianceConfig, accountId, bucketName, domainName, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/custom/${domainName}`,
{
method: "DELETE",
headers
}
);
}
function tableFromCustomDomainListResponse(domains) {
const rows = [];
for (const domainInfo of domains) {
rows.push({
domain: domainInfo.domain,
enabled: domainInfo.enabled ? "Yes" : "No",
ownership_status: domainInfo.status.ownership || "(unknown)",
ssl_status: domainInfo.status.ssl || "(unknown)",
min_tls_version: domainInfo.minTLS || "1.0",
zone_id: domainInfo.zoneId || "(none)",
zone_name: domainInfo.zoneName || "(none)"
});
}
return rows;
}
async function listCustomDomainsOfBucket(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/custom`,
{
method: "GET",
headers
}
);
return result.domains;
}
async function configureCustomDomainSettings(complianceConfig, accountId, bucketName, domainName, domainConfig, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/custom/${domainName}`,
{
method: "PUT",
headers,
body: JSON.stringify(domainConfig)
}
);
}
async function getR2DevDomain(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/managed`,
{
method: "GET",
headers
}
);
return result;
}
async function updateR2DevDomain(complianceConfig, accountId, bucketName, enabled, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/domains/managed`,
{
method: "PUT",
headers,
body: JSON.stringify({ enabled })
}
);
return result;
}
function formatCondition(condition) {
if (condition.type === "Age" && typeof condition.maxAge === "number") {
const days = condition.maxAge / 86400;
return `after ${days} days`;
} else if (condition.type === "Date" && condition.date) {
const date = new Date(condition.date);
const displayDate = date.toISOString().split("T")[0];
return `on ${displayDate}`;
}
return "";
}
function tableFromLifecycleRulesResponse(rules) {
const rows = [];
for (const rule of rules) {
const actions = [];
if (rule.deleteObjectsTransition) {
const action = "Expire objects";
const condition = formatCondition(rule.deleteObjectsTransition.condition);
actions.push(`${action} ${condition}`);
}
if (rule.storageClassTransitions && rule.storageClassTransitions.length > 0) {
for (const transition of rule.storageClassTransitions) {
const action = "Transition to Infrequent Access";
const condition = formatCondition(transition.condition);
actions.push(`${action} ${condition}`);
}
}
if (rule.abortMultipartUploadsTransition) {
const action = "Abort incomplete multipart uploads";
const condition = formatCondition(
rule.abortMultipartUploadsTransition.condition
);
actions.push(`${action} ${condition}`);
}
rows.push({
name: rule.id,
enabled: rule.enabled ? "Yes" : "No",
prefix: rule.conditions.prefix || "(all prefixes)",
action: actions.join(", ") || "(none)"
});
}
return rows;
}
async function getLifecycleRules(complianceConfig, accountId, bucket, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucket}/lifecycle`,
{
method: "GET",
headers
}
);
return result.rules;
}
async function putLifecycleRules(complianceConfig, accountId, bucket, rules, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucket}/lifecycle`,
{
method: "PUT",
headers,
body: JSON.stringify({ rules })
}
);
}
function tableFromBucketLockRulesResponse(rules) {
const rows = [];
for (const rule of rules) {
const conditionString = formatLockCondition(rule.condition);
rows.push({
name: rule.id,
enabled: rule.enabled ? "Yes" : "No",
prefix: rule.prefix || "(all prefixes)",
condition: conditionString
});
}
return rows;
}
function formatLockCondition(condition) {
if (condition.type === "Age" && typeof condition.maxAgeSeconds === "number") {
const days = condition.maxAgeSeconds / 86400;
if (days == 1) {
return `after ${days} day`;
} else {
return `after ${days} days`;
}
} else if (condition.type === "Date" && condition.date) {
const date = new Date(condition.date);
const displayDate = date.toISOString().split("T")[0];
return `on ${displayDate}`;
}
return `indefinitely`;
}
async function getBucketLockRules(complianceConfig, accountId, bucket, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucket}/lock`,
{
method: "GET",
headers
}
);
return result.rules;
}
async function putBucketLockRules(complianceConfig, accountId, bucket, rules, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucket}/lock`,
{
method: "PUT",
headers,
body: JSON.stringify({ rules })
}
);
}
function formatActionDescription(action) {
switch (action) {
case "expire":
return "expire objects";
case "transition":
return "transition to Infrequent Access storage class";
case "abort-multipart":
return "abort incomplete multipart uploads";
default:
return action;
}
}
function isValidDate(dateString) {
const regex2 = /^\d{4}-\d{2}-\d{2}$/;
if (!regex2.test(dateString)) {
return false;
}
const date = /* @__PURE__ */ new Date(`${dateString}T00:00:00.000Z`);
const timestamp = date.getTime();
if (isNaN(timestamp)) {
return false;
}
const [year, month, day] = dateString.split("-").map(Number);
return date.getUTCFullYear() === year && date.getUTCMonth() + 1 === month && date.getUTCDate() === day;
}
function isNonNegativeNumber(str) {
if (str === "") {
return false;
}
const num = Number(str);
return num >= 0;
}
async function getCORSPolicy(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/cors`,
{
method: "GET",
headers
}
);
return result.rules;
}
function tableFromCORSPolicyResponse(rules) {
const rows = [];
for (const rule of rules) {
rows.push({
allowed_origins: rule.allowed?.origins?.join(", ") || "(no origins)",
allowed_methods: rule.allowed?.methods?.join(", ") || "(no methods)",
allowed_headers: rule.allowed?.headers?.join(", ") || "(no headers)",
exposed_headers: rule.exposeHeaders?.join(", ") || "(no exposed headers)",
max_age_seconds: rule.maxAgeSeconds?.toString() || "(0 seconds)"
});
}
return rows;
}
async function putCORSPolicy(complianceConfig, accountId, bucketName, rules, jurisdiction) {
const headers = {
"Content-Type": "application/json"
};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/cors`,
{
method: "PUT",
headers,
body: JSON.stringify({ rules })
}
);
}
async function deleteCORSPolicy(complianceConfig, accountId, bucketName, jurisdiction) {
const headers = {};
if (jurisdiction) {
headers["cf-r2-jurisdiction"] = jurisdiction;
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${bucketName}/cors`,
{
method: "DELETE",
headers
}
);
}
function isValidR2BucketName(name2) {
return typeof name2 === "string" && /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(name2);
}
async function createFileReadableStream(filePath) {
const handle = await fs6.promises.open(filePath, "r");
let position = 0;
return new import_web.ReadableStream({
async pull(controller) {
const buffer = new Uint8Array(CHUNK_SIZE);
const { bytesRead } = await handle.read(buffer, 0, CHUNK_SIZE, position);
if (bytesRead === 0) {
await handle.close();
controller.close();
} else {
position += bytesRead;
controller.enqueue(buffer.subarray(0, bytesRead));
}
},
cancel() {
return handle.close();
}
});
}
var fs6, import_web, import_miniflare2, actionsForEventCategories, bucketFormatMessage, CHUNK_SIZE;
var init_helpers = __esm({
"src/r2/helpers.ts"() {
init_import_meta_url();
fs6 = __toESM(require("fs"));
import_web = require("stream/web");
import_miniflare2 = require("miniflare");
init_pretty_bytes();
init_cfetch();
init_internal();
init_get_local_persistence_path();
init_miniflare();
init_errors();
init_logger();
init_client2();
__name(listR2Buckets, "listR2Buckets");
__name(tablefromR2BucketsListResponse, "tablefromR2BucketsListResponse");
__name(getR2Bucket, "getR2Bucket");
__name(getR2BucketMetrics, "getR2BucketMetrics");
__name(createR2Bucket, "createR2Bucket");
__name(updateR2BucketStorageClass, "updateR2BucketStorageClass");
__name(deleteR2Bucket, "deleteR2Bucket");
__name(bucketAndKeyFromObjectPath, "bucketAndKeyFromObjectPath");
__name(getR2Object, "getR2Object");
__name(putR2Object, "putR2Object");
__name(deleteR2Object, "deleteR2Object");
__name(usingLocalBucket, "usingLocalBucket");
__name(getR2Sippy, "getR2Sippy");
__name(deleteR2Sippy, "deleteR2Sippy");
__name(putR2Sippy, "putR2Sippy");
__name(getR2Catalog, "getR2Catalog");
__name(enableR2Catalog, "enableR2Catalog");
__name(disableR2Catalog, "disableR2Catalog");
actionsForEventCategories = {
"object-create": ["PutObject", "CompleteMultipartUpload", "CopyObject"],
"object-delete": ["DeleteObject", "LifecycleDeletion"]
};
__name(eventNotificationHeaders, "eventNotificationHeaders");
__name(tableFromNotificationGetResponse, "tableFromNotificationGetResponse");
__name(listEventNotificationConfig, "listEventNotificationConfig");
__name(putEventNotificationConfig, "putEventNotificationConfig");
__name(deleteEventNotificationConfig, "deleteEventNotificationConfig");
__name(getCustomDomain, "getCustomDomain");
__name(attachCustomDomainToBucket, "attachCustomDomainToBucket");
__name(removeCustomDomainFromBucket, "removeCustomDomainFromBucket");
__name(tableFromCustomDomainListResponse, "tableFromCustomDomainListResponse");
__name(listCustomDomainsOfBucket, "listCustomDomainsOfBucket");
__name(configureCustomDomainSettings, "configureCustomDomainSettings");
__name(getR2DevDomain, "getR2DevDomain");
__name(updateR2DevDomain, "updateR2DevDomain");
__name(formatCondition, "formatCondition");
__name(tableFromLifecycleRulesResponse, "tableFromLifecycleRulesResponse");
__name(getLifecycleRules, "getLifecycleRules");
__name(putLifecycleRules, "putLifecycleRules");
__name(tableFromBucketLockRulesResponse, "tableFromBucketLockRulesResponse");
__name(formatLockCondition, "formatLockCondition");
__name(getBucketLockRules, "getBucketLockRules");
__name(putBucketLockRules, "putBucketLockRules");
__name(formatActionDescription, "formatActionDescription");
__name(isValidDate, "isValidDate");
__name(isNonNegativeNumber, "isNonNegativeNumber");
__name(getCORSPolicy, "getCORSPolicy");
__name(tableFromCORSPolicyResponse, "tableFromCORSPolicyResponse");
__name(putCORSPolicy, "putCORSPolicy");
__name(deleteCORSPolicy, "deleteCORSPolicy");
__name(isValidR2BucketName, "isValidR2BucketName");
bucketFormatMessage = `Bucket names must begin and end with an alphanumeric character, only contain lowercase letters, numbers, and hyphens, and be between 3 and 63 characters long.`;
CHUNK_SIZE = 1024;
__name(createFileReadableStream, "createFileReadableStream");
}
});
// src/config/diagnostics.ts
function indentText(str) {
return str.split("\n").map(
(line, index) => (index === 0 ? line : ` ${line}`).replace(/^\s*$/, "")
).join("\n");
}
var Diagnostics;
var init_diagnostics = __esm({
"src/config/diagnostics.ts"() {
init_import_meta_url();
Diagnostics = class {
/**
* Create a new Diagnostics object.
* @param description A general description of this collection of messages.
*/
constructor(description) {
this.description = description;
}
static {
__name(this, "Diagnostics");
}
errors = [];
warnings = [];
children = [];
/**
* Merge the given `diagnostics` into this as a child.
*/
addChild(diagnostics) {
if (diagnostics.hasErrors() || diagnostics.hasWarnings()) {
this.children.push(diagnostics);
}
}
/** Does this or any of its children have errors. */
hasErrors() {
if (this.errors.length > 0) {
return true;
} else {
return this.children.some((child) => child.hasErrors());
}
}
/** Render the errors of this and all its children. */
renderErrors() {
return this.render("errors");
}
/** Does this or any of its children have warnings. */
hasWarnings() {
if (this.warnings.length > 0) {
return true;
} else {
return this.children.some((child) => child.hasWarnings());
}
}
/** Render the warnings of this and all its children. */
renderWarnings() {
return this.render("warnings");
}
render(field) {
const hasMethod = field === "errors" ? "hasErrors" : "hasWarnings";
return indentText(
`${this.description}
` + // Output all the fields (errors or warnings) at this level
this[field].map((message) => `- ${indentText(message)}`).join("\n") + // Output all the child diagnostics at the next level
this.children.map(
(child) => child[hasMethod]() ? "\n- " + child.render(field) : ""
).filter((output) => output !== "").join("\n")
);
}
};
__name(indentText, "indentText");
}
});
// src/config/validation-helpers.ts
function deprecated(diagnostics, config, fieldPath, message, remove, title = "Deprecation", type = "warning") {
const BOLD = "\x1B[1m";
const NORMAL = "\x1B[0m";
const diagnosticMessage = `${BOLD}${title}${NORMAL}: "${fieldPath}":
${message}`;
const result = unwindPropertyPath(config, fieldPath);
if (result !== void 0 && result.field in result.container) {
diagnostics[`${type}s`].push(diagnosticMessage);
if (remove) {
delete result.container[result.field];
}
}
}
function experimental(diagnostics, config, fieldPath) {
const result = unwindPropertyPath(config, fieldPath);
if (result !== void 0 && result.field in result.container && !("WRANGLER_DISABLE_EXPERIMENTAL_WARNING" in process.env)) {
diagnostics.warnings.push(
`"${fieldPath}" fields are experimental and may change or break at any time.`
);
}
}
function inheritable(diagnostics, topLevelEnv, rawEnv, field, validate3, defaultValue, transformFn = (v7) => v7) {
validate3(diagnostics, field, rawEnv[field], topLevelEnv);
return (
// `rawEnv === topLevelEnv` is a special case where the user has provided an environment name
// but that named environment is not actually defined in the configuration.
// In that case we have reused the topLevelEnv as the rawEnv,
// and so we need to process the `transformFn()` anyway rather than just using the field in the `rawEnv`.
(rawEnv !== topLevelEnv ? rawEnv[field] : void 0) ?? transformFn(topLevelEnv?.[field]) ?? defaultValue
);
}
function inheritableInLegacyEnvironments(diagnostics, isLegacyEnv2, topLevelEnv, rawEnv, field, validate3, transformFn = (v7) => v7, defaultValue) {
return topLevelEnv === void 0 || isLegacyEnv2 === true ? inheritable(
diagnostics,
topLevelEnv,
rawEnv,
field,
validate3,
defaultValue,
transformFn
) : notAllowedInNamedServiceEnvironment(
diagnostics,
topLevelEnv,
rawEnv,
field
);
}
function notAllowedInNamedServiceEnvironment(diagnostics, topLevelEnv, rawEnv, field) {
if (field in rawEnv) {
diagnostics.errors.push(
`The "${field}" field is not allowed in named service environments.
Please remove the field from this environment.`
);
}
return topLevelEnv[field];
}
function notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, field, validate3, defaultValue) {
if (rawEnv[field] !== void 0) {
validate3(diagnostics, field, rawEnv[field], topLevelEnv);
} else {
if (rawConfig?.[field] !== void 0) {
diagnostics.warnings.push(
`"${field}" exists at the top level, but not on "env.${envName}".
This is not what you probably want, since "${field}" is not inherited by environments.
Please add "${field}" to "env.${envName}".`
);
}
}
return rawEnv[field] ?? defaultValue;
}
function unwindPropertyPath(root, path72) {
let container = root;
const parts = path72.split(".");
for (let i5 = 0; i5 < parts.length - 1; i5++) {
if (!hasProperty(container, parts[i5])) {
return;
}
container = container[parts[i5]];
}
return { container, field: parts[parts.length - 1] };
}
var appendEnvName, isString2, isValidName, isValidDateTimeStringFormat, isStringArray, isOneOf, all, isMutuallyExclusiveWith, isBoolean, validateRequiredProperty, validateAtLeastOnePropertyRequired, validateOptionalProperty, validateTypedArray, validateOptionalTypedArray, isRequiredProperty, isOptionalProperty, hasProperty, validateAdditionalProperties, getBindingNames, isBindingList, isNamespaceList, isRecord, validateUniqueNameProperty;
var init_validation_helpers = __esm({
"src/config/validation-helpers.ts"() {
init_import_meta_url();
__name(deprecated, "deprecated");
__name(experimental, "experimental");
__name(inheritable, "inheritable");
__name(inheritableInLegacyEnvironments, "inheritableInLegacyEnvironments");
appendEnvName = /* @__PURE__ */ __name((envName) => (fieldValue) => fieldValue ? `${fieldValue}-${envName}` : void 0, "appendEnvName");
__name(notAllowedInNamedServiceEnvironment, "notAllowedInNamedServiceEnvironment");
__name(notInheritable, "notInheritable");
__name(unwindPropertyPath, "unwindPropertyPath");
isString2 = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value !== void 0 && typeof value !== "string") {
diagnostics.errors.push(
`Expected "${field}" to be of type string but got ${JSON.stringify(
value
)}.`
);
return false;
}
return true;
}, "isString");
isValidName = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value === "string" && /^$|^[a-z0-9_][a-z0-9-_]*$/.test(value) || value === void 0) {
return true;
} else {
diagnostics.errors.push(
`Expected "${field}" to be of type string, alphanumeric and lowercase with dashes only but got ${JSON.stringify(
value
)}.`
);
return false;
}
}, "isValidName");
isValidDateTimeStringFormat = /* @__PURE__ */ __name((diagnostics, field, value) => {
let isValid2 = true;
if (value.includes("\u2013") || // en-dash
value.includes("\u2014")) {
diagnostics.errors.push(
`"${field}" field should use ISO-8601 accepted hyphens (-) rather than en-dashes (\u2013) or em-dashes (\u2014).`
);
isValid2 = false;
}
const data = new Date(value.replaceAll(/–|—/g, "-"));
if (isNaN(data.getTime())) {
diagnostics.errors.push(
`"${field}" field should be a valid ISO-8601 date (YYYY-MM-DD), but got ${JSON.stringify(value)}.`
);
isValid2 = false;
}
return isValid2;
}, "isValidDateTimeStringFormat");
isStringArray = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) {
diagnostics.errors.push(
`Expected "${field}" to be of type string array but got ${JSON.stringify(
value
)}.`
);
return false;
}
return true;
}, "isStringArray");
isOneOf = /* @__PURE__ */ __name((...choices) => (diagnostics, field, value) => {
if (value !== void 0 && !choices.some((choice) => value === choice)) {
diagnostics.errors.push(
`Expected "${field}" field to be one of ${JSON.stringify(
choices
)} but got ${JSON.stringify(value)}.`
);
return false;
}
return true;
}, "isOneOf");
all = /* @__PURE__ */ __name((...validations) => {
return (diagnostics, field, value, config) => {
let passedValidations = true;
for (const validate3 of validations) {
if (!validate3(diagnostics, field, value, config)) {
passedValidations = false;
}
}
return passedValidations;
};
}, "all");
isMutuallyExclusiveWith = /* @__PURE__ */ __name((container, ...fields) => {
return (diagnostics, field, value) => {
if (value === void 0) {
return true;
}
for (const exclusiveWith of fields) {
if (container[exclusiveWith] !== void 0) {
diagnostics.errors.push(
`Expected exactly one of the following fields ${JSON.stringify([
field,
...fields
])}.`
);
return false;
}
}
return true;
};
}, "isMutuallyExclusiveWith");
isBoolean = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value !== void 0 && typeof value !== "boolean") {
diagnostics.errors.push(
`Expected "${field}" to be of type boolean but got ${JSON.stringify(
value
)}.`
);
return false;
}
return true;
}, "isBoolean");
validateRequiredProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
if (container) {
container += ".";
}
if (value === void 0) {
diagnostics.errors.push(`"${container}${key}" is a required field.`);
return false;
} else if (typeof value !== type) {
diagnostics.errors.push(
`Expected "${container}${key}" to be of type ${type} but got ${JSON.stringify(
value
)}.`
);
return false;
} else if (choices) {
if (!isOneOf(...choices)(diagnostics, `${container}${key}`, value, void 0)) {
return false;
}
}
return true;
}, "validateRequiredProperty");
validateAtLeastOnePropertyRequired = /* @__PURE__ */ __name((diagnostics, container, properties) => {
const containerPath = container ? `${container}.` : "";
if (properties.every((property) => property.value === void 0)) {
diagnostics.errors.push(
`${properties.map(({ key }) => `"${containerPath}${key}"`).join(" or ")} is required.`
);
return false;
}
const errors = [];
for (const prop of properties) {
if (typeof prop.value === prop.type) {
return true;
}
errors.push(
`Expected "${containerPath}${prop.key}" to be of type ${prop.type} but got ${JSON.stringify(
prop.value
)}.`
);
}
diagnostics.errors.push(...errors);
return false;
}, "validateAtLeastOnePropertyRequired");
validateOptionalProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
if (value !== void 0) {
return validateRequiredProperty(
diagnostics,
container,
key,
value,
type,
choices
);
}
return true;
}, "validateOptionalProperty");
validateTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
let isValid2 = true;
if (!Array.isArray(value)) {
diagnostics.errors.push(
`Expected "${container}" to be an array of ${type}s but got ${JSON.stringify(
value
)}`
);
isValid2 = false;
} else {
for (let i5 = 0; i5 < value.length; i5++) {
isValid2 = validateRequiredProperty(
diagnostics,
container,
`[${i5}]`,
value[i5],
type
) && isValid2;
}
}
return isValid2;
}, "validateTypedArray");
validateOptionalTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
if (value !== void 0) {
return validateTypedArray(diagnostics, container, value, type);
}
return true;
}, "validateOptionalTypedArray");
isRequiredProperty = /* @__PURE__ */ __name((obj, prop, type, choices) => hasProperty(obj, prop) && typeof obj[prop] === type && (choices === void 0 || choices.includes(obj[prop])), "isRequiredProperty");
isOptionalProperty = /* @__PURE__ */ __name((obj, prop, type) => !hasProperty(obj, prop) || typeof obj[prop] === type, "isOptionalProperty");
hasProperty = /* @__PURE__ */ __name((obj, property) => property in obj, "hasProperty");
validateAdditionalProperties = /* @__PURE__ */ __name((diagnostics, fieldPath, restProps, knownProps) => {
const restPropSet = new Set(restProps);
for (const knownProp of knownProps) {
restPropSet.delete(knownProp);
}
if (restPropSet.size > 0) {
const fields = Array.from(restPropSet.keys()).map((field) => `"${field}"`);
diagnostics.warnings.push(
`Unexpected fields found in ${fieldPath} field: ${fields}`
);
return false;
}
return true;
}, "validateAdditionalProperties");
getBindingNames = /* @__PURE__ */ __name((value) => {
if (typeof value !== "object" || value === null) {
return [];
}
if (isBindingList(value)) {
return value.bindings.map(({ name: name2 }) => name2);
} else if (isNamespaceList(value)) {
return value.map(({ binding }) => binding);
} else if (isRecord(value)) {
if (value["binding"] !== void 0) {
return [value["binding"]];
}
return Object.keys(value).filter((k6) => value[k6] !== void 0);
} else {
return [];
}
}, "getBindingNames");
isBindingList = /* @__PURE__ */ __name((value) => isRecord(value) && "bindings" in value && Array.isArray(value.bindings) && value.bindings.every(
(binding) => isRecord(binding) && "name" in binding && typeof binding.name === "string"
), "isBindingList");
isNamespaceList = /* @__PURE__ */ __name((value) => Array.isArray(value) && value.every(
(entry) => isRecord(entry) && "binding" in entry && typeof entry.binding === "string"
), "isNamespaceList");
isRecord = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
validateUniqueNameProperty = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (Array.isArray(value)) {
const nameCount = /* @__PURE__ */ new Map();
Object.entries(value).forEach(([_4, entry]) => {
nameCount.set(entry.name, (nameCount.get(entry.name) ?? 0) + 1);
});
const duplicates = Array.from(nameCount.entries()).filter(([_4, count]) => count > 1).map(([name2]) => name2);
if (duplicates.length > 0) {
const list = duplicates.join('", "');
diagnostics.errors.push(
`"${field}" bindings must have unique "name" values; duplicate(s) found: "${list}"`
);
return false;
}
}
return true;
}, "validateUniqueNameProperty");
}
});
// src/config/validation.ts
function isPagesConfig(rawConfig) {
return rawConfig.pages_build_output_dir !== void 0;
}
function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args) {
const diagnostics = new Diagnostics(
`Processing ${configPath ? import_node_path9.default.relative(process.cwd(), configPath) : "wrangler"} configuration:`
);
validateOptionalProperty(
diagnostics,
"",
"legacy_env",
rawConfig.legacy_env,
"boolean"
);
validateOptionalProperty(
diagnostics,
"",
"send_metrics",
rawConfig.send_metrics,
"boolean"
);
validateOptionalProperty(
diagnostics,
"",
"keep_vars",
rawConfig.keep_vars,
"boolean"
);
validateOptionalProperty(
diagnostics,
"",
"pages_build_output_dir",
rawConfig.pages_build_output_dir,
"string"
);
validateOptionalProperty(
diagnostics,
"",
"$schema",
rawConfig.$schema,
"string"
);
const isLegacyEnv2 = typeof args["legacy-env"] === "boolean" ? args["legacy-env"] : rawConfig.legacy_env ?? true;
if (!isLegacyEnv2) {
diagnostics.warnings.push(
"Experimental: Service environments are in beta, and their behaviour is guaranteed to change in the future. DO NOT USE IN PRODUCTION."
);
}
const isDispatchNamespace = typeof args["dispatch-namespace"] === "string" && args["dispatch-namespace"].trim() !== "";
const topLevelEnv = normalizeAndValidateEnvironment(
diagnostics,
configPath,
rawConfig,
isDispatchNamespace
);
const isRedirectedConfig = configPath && configPath !== userConfigPath;
const definedEnvironments = Object.keys(rawConfig.env ?? {});
if (isRedirectedConfig && definedEnvironments.length > 0) {
diagnostics.errors.push(
dedent`
Redirected configurations cannot include environments but the following have been found:\n${definedEnvironments.map((env6) => ` - ${env6}`).join("\n")}
Such configurations are generated by tools, meaning that one of the tools
your application is using is generating the incorrect configuration.
Report this issue to the tool's author so that this can be fixed there.
`
);
}
const envName = args.env;
(0, import_node_assert.default)(envName === void 0 || typeof envName === "string");
let activeEnv = topLevelEnv;
if (envName) {
if (isRedirectedConfig) {
if (!isPagesConfig(rawConfig)) {
diagnostics.errors.push(dedent`
You have specified the environment "${envName}", but are using a redirected configuration, produced by a build tool such as Vite.
You need to set the environment in your build tool, rather than via Wrangler.
For example, if you are using Vite, refer to these docs: https://developers.cloudflare.com/workers/vite-plugin/reference/cloudflare-environments/
`);
}
} else {
const envDiagnostics = new Diagnostics(
`"env.${envName}" environment configuration`
);
const rawEnv = rawConfig.env?.[envName];
if (rawEnv !== void 0) {
activeEnv = normalizeAndValidateEnvironment(
envDiagnostics,
configPath,
rawEnv,
isDispatchNamespace,
envName,
topLevelEnv,
isLegacyEnv2,
rawConfig
);
diagnostics.addChild(envDiagnostics);
} else if (!isPagesConfig(rawConfig)) {
activeEnv = normalizeAndValidateEnvironment(
envDiagnostics,
configPath,
topLevelEnv,
// in this case reuse the topLevelEnv to ensure that nonInherited fields are not removed
isDispatchNamespace,
envName,
topLevelEnv,
isLegacyEnv2,
rawConfig
);
const envNames = rawConfig.env ? `The available configured environment names are: ${JSON.stringify(
Object.keys(rawConfig.env)
)}
` : "";
const message = `No environment found in configuration with name "${envName}".
Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.
${envNames}
Consider adding an environment configuration section to the ${configFileName(configPath)} file:
\`\`\`
[env.` + envName + "]\n```\n";
if (envNames.length > 0) {
diagnostics.errors.push(message);
} else {
diagnostics.warnings.push(message);
}
}
}
}
const config = {
configPath,
userConfigPath,
topLevelName: rawConfig.name,
pages_build_output_dir: normalizeAndValidatePagesBuildOutputDir(
configPath,
rawConfig.pages_build_output_dir
),
legacy_env: isLegacyEnv2,
send_metrics: rawConfig.send_metrics,
keep_vars: rawConfig.keep_vars,
...activeEnv,
dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}, args),
site: normalizeAndValidateSite(
diagnostics,
configPath,
rawConfig,
activeEnv.main
),
alias: normalizeAndValidateAliases(diagnostics, configPath, rawConfig),
wasm_modules: normalizeAndValidateModulePaths(
diagnostics,
configPath,
"wasm_modules",
rawConfig.wasm_modules
),
text_blobs: normalizeAndValidateModulePaths(
diagnostics,
configPath,
"text_blobs",
rawConfig.text_blobs
),
data_blobs: normalizeAndValidateModulePaths(
diagnostics,
configPath,
"data_blobs",
rawConfig.data_blobs
)
};
validateBindingsHaveUniqueNames(diagnostics, config);
validateAdditionalProperties(
diagnostics,
"top-level",
Object.keys(rawConfig),
[...Object.keys(config), "env", "$schema"]
);
applyPythonConfig(config, args);
return { config, diagnostics };
}
function applyPythonConfig(config, args) {
const mainModule = args.script ?? config.main;
if (typeof mainModule === "string" && mainModule.endsWith(".py")) {
config.no_bundle = true;
if (!config.rules.some((rule) => rule.type === "PythonModule")) {
config.rules.push({ type: "PythonModule", globs: ["**/*.py"] });
}
if (!config.compatibility_flags.includes("python_workers")) {
throw new UserError(
"The `python_workers` compatibility flag is required to use Python."
);
}
}
}
function normalizeAndValidateBuild(diagnostics, rawEnv, rawBuild, configPath) {
const { command: command2, cwd: cwd2, watch_dir = "./src", ...rest } = rawBuild;
validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
validateOptionalProperty(diagnostics, "build", "command", command2, "string");
validateOptionalProperty(diagnostics, "build", "cwd", cwd2, "string");
if (Array.isArray(watch_dir)) {
validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
} else {
validateOptionalProperty(
diagnostics,
"build",
"watch_dir",
watch_dir,
"string"
);
}
return {
command: command2,
watch_dir: (
// - `watch_dir` only matters when `command` is defined, so we apply
// a default only when `command` is defined
// - `configPath` will always be defined since `build` can only
// be configured in the Wrangler configuration file, but who knows, that may
// change in the future, so we do a check anyway
command2 && configPath ? Array.isArray(watch_dir) ? watch_dir.map(
(dir) => import_node_path9.default.relative(
process.cwd(),
import_node_path9.default.join(import_node_path9.default.dirname(configPath), `${dir}`)
)
) : import_node_path9.default.relative(
process.cwd(),
import_node_path9.default.join(import_node_path9.default.dirname(configPath), `${watch_dir}`)
) : watch_dir
),
cwd: cwd2
};
}
function normalizeAndValidateMainField(configPath, rawMain) {
const configDir = import_node_path9.default.dirname(configPath ?? "wrangler.toml");
if (rawMain !== void 0) {
if (typeof rawMain === "string") {
const directory = import_node_path9.default.resolve(configDir);
return import_node_path9.default.resolve(directory, rawMain);
} else {
return rawMain;
}
} else {
return;
}
}
function normalizeAndValidateBaseDirField(configPath, rawDir) {
const configDir = import_node_path9.default.dirname(configPath ?? "wrangler.toml");
if (rawDir !== void 0) {
if (typeof rawDir === "string") {
const directory = import_node_path9.default.resolve(configDir);
return import_node_path9.default.resolve(directory, rawDir);
} else {
return rawDir;
}
} else {
return;
}
}
function normalizeAndValidatePagesBuildOutputDir(configPath, rawPagesDir) {
const configDir = import_node_path9.default.dirname(configPath ?? "wrangler.toml");
if (rawPagesDir !== void 0) {
if (typeof rawPagesDir === "string") {
const directory = import_node_path9.default.resolve(configDir);
return import_node_path9.default.resolve(directory, rawPagesDir);
} else {
return rawPagesDir;
}
} else {
return;
}
}
function normalizeAndValidateDev(diagnostics, rawDev, args) {
(0, import_node_assert.default)(typeof args === "object" && args !== null && !Array.isArray(args));
const {
localProtocol: localProtocolArg,
upstreamProtocol: upstreamProtocolArg,
remote: remoteArg,
enableContainers: enableContainersArg
} = args;
(0, import_node_assert.default)(
localProtocolArg === void 0 || localProtocolArg === "http" || localProtocolArg === "https"
);
(0, import_node_assert.default)(
upstreamProtocolArg === void 0 || upstreamProtocolArg === "http" || upstreamProtocolArg === "https"
);
(0, import_node_assert.default)(remoteArg === void 0 || typeof remoteArg === "boolean");
(0, import_node_assert.default)(
enableContainersArg === void 0 || typeof enableContainersArg === "boolean"
);
const {
// On Windows, when specifying `localhost` as the socket hostname, `workerd`
// will only listen on the IPv4 loopback `127.0.0.1`, not the IPv6 `::1`:
// https://github.com/cloudflare/workerd/issues/1408
// On Node 17+, `fetch()` will only try to fetch the IPv6 address.
// For now, on Windows, we default to listening on IPv4 only and using
// `127.0.0.1` when sending control requests to `workerd` (e.g. with the
// `ProxyController`).
ip = process.platform === "win32" ? "127.0.0.1" : "localhost",
port,
inspector_port,
local_protocol = localProtocolArg ?? "http",
// In remote mode upstream_protocol must be https, otherwise it defaults to local_protocol.
upstream_protocol = upstreamProtocolArg ?? remoteArg ? "https" : local_protocol,
host,
enable_containers = enableContainersArg ?? true,
container_engine,
...rest
} = rawDev;
validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
validateOptionalProperty(diagnostics, "dev", "port", port, "number");
validateOptionalProperty(
diagnostics,
"dev",
"inspector_port",
inspector_port,
"number"
);
validateOptionalProperty(
diagnostics,
"dev",
"local_protocol",
local_protocol,
"string",
["http", "https"]
);
validateOptionalProperty(
diagnostics,
"dev",
"upstream_protocol",
upstream_protocol,
"string",
["http", "https"]
);
validateOptionalProperty(diagnostics, "dev", "host", host, "string");
validateOptionalProperty(
diagnostics,
"dev",
"enable_containers",
enable_containers,
"boolean"
);
validateOptionalProperty(
diagnostics,
"dev",
"container_engine",
container_engine,
"string"
);
return {
ip,
port,
inspector_port,
local_protocol,
upstream_protocol,
host,
enable_containers,
container_engine
};
}
function normalizeAndValidateAssets(diagnostics, topLevelEnv, rawEnv) {
return inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"assets",
validateAssetsConfig,
void 0
);
}
function normalizeAndValidateSite(diagnostics, configPath, rawConfig, mainEntryPoint) {
if (rawConfig?.site !== void 0) {
const { bucket, include = [], exclude: exclude2 = [], ...rest } = rawConfig.site;
validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
"entry-point"
]);
validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
validateTypedArray(diagnostics, "sites.include", include, "string");
validateTypedArray(diagnostics, "sites.exclude", exclude2, "string");
validateOptionalProperty(
diagnostics,
"site",
"entry-point",
rawConfig.site["entry-point"],
"string"
);
deprecated(
diagnostics,
rawConfig,
`site.entry-point`,
`Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:
\`\`\`
main = "${import_node_path9.default.join(
String(rawConfig.site["entry-point"]) || "workers-site",
import_node_path9.default.extname(String(rawConfig.site["entry-point"]) || "workers-site") ? "" : "index.js"
)}"
\`\`\``,
false,
void 0,
"warning"
);
let siteEntryPoint = rawConfig.site["entry-point"];
if (!mainEntryPoint && !siteEntryPoint) {
diagnostics.warnings.push(
`Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.
Add the top level \`main\` field to your configuration file:
\`\`\`
main = "workers-site/index.js"
\`\`\``
);
siteEntryPoint = "workers-site";
} else if (mainEntryPoint && siteEntryPoint) {
diagnostics.errors.push(
`Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.
They serve the same purpose: to point to the entry-point of your worker.
Delete the deprecated \`site.entry-point\` field from your config.`
);
}
if (configPath && siteEntryPoint) {
siteEntryPoint = import_node_path9.default.relative(
process.cwd(),
import_node_path9.default.join(import_node_path9.default.dirname(configPath), siteEntryPoint)
);
}
return {
bucket,
"entry-point": siteEntryPoint,
include,
exclude: exclude2
};
}
return void 0;
}
function normalizeAndValidateAliases(diagnostics, configPath, rawConfig) {
if (rawConfig?.alias === void 0) {
return void 0;
}
if (["string", "boolean", "number"].includes(typeof rawConfig?.alias) || typeof rawConfig?.alias !== "object") {
diagnostics.errors.push(
`Expected alias to be an object, but got ${typeof rawConfig?.alias}`
);
return void 0;
}
let isValid2 = true;
for (const [key, value] of Object.entries(rawConfig?.alias)) {
if (typeof value !== "string") {
diagnostics.errors.push(
`Expected alias["${key}"] to be a string, but got ${typeof value}`
);
isValid2 = false;
}
}
if (isValid2) {
return rawConfig.alias;
}
return;
}
function normalizeAndValidateModulePaths(diagnostics, configPath, field, rawMapping) {
if (rawMapping === void 0) {
return void 0;
}
const mapping = {};
for (const [name2, filePath] of Object.entries(rawMapping)) {
if (isString2(diagnostics, `${field}['${name2}']`, filePath, void 0)) {
if (configPath) {
mapping[name2] = configPath ? import_node_path9.default.relative(
process.cwd(),
import_node_path9.default.join(import_node_path9.default.dirname(configPath), filePath)
) : filePath;
}
}
}
return mapping;
}
function isValidRouteValue(item) {
if (!item) {
return false;
}
if (typeof item === "string") {
return true;
}
if (typeof item === "object") {
if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
return false;
}
const otherKeys = Object.keys(item).length - 1;
const hasZoneId = hasProperty(item, "zone_id") && typeof item.zone_id === "string";
const hasZoneName = hasProperty(item, "zone_name") && typeof item.zone_name === "string";
const hasCustomDomainFlag = hasProperty(item, "custom_domain") && typeof item.custom_domain === "boolean";
if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
return true;
} else if (otherKeys === 1 && (hasZoneId || hasZoneName || hasCustomDomainFlag)) {
return true;
}
}
return false;
}
function mutateEmptyStringAccountIDValue(diagnostics, rawEnv) {
if (rawEnv.account_id === "") {
diagnostics.warnings.push(
`The "account_id" field in your configuration is an empty string and will be ignored.
Please remove the "account_id" field from your configuration.`
);
rawEnv.account_id = void 0;
}
return rawEnv;
}
function mutateEmptyStringRouteValue(diagnostics, rawEnv) {
if (rawEnv["route"] === "") {
diagnostics.warnings.push(
`The "route" field in your configuration is an empty string and will be ignored.
Please remove the "route" field from your configuration.`
);
rawEnv["route"] = void 0;
}
return rawEnv;
}
function normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv) {
return inheritable(
diagnostics,
topLevelEnv,
mutateEmptyStringRouteValue(diagnostics, rawEnv),
"route",
isRoute,
void 0
);
}
function validateRoutes2(diagnostics, topLevelEnv, rawEnv) {
return inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"routes",
all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
void 0
);
}
function normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv) {
if (rawEnv.placement) {
validateRequiredProperty(
diagnostics,
"placement",
"mode",
rawEnv.placement.mode,
"string",
["off", "smart"]
);
validateOptionalProperty(
diagnostics,
"placement",
"hint",
rawEnv.placement.hint,
"string"
);
if (rawEnv.placement.hint && rawEnv.placement.mode !== "smart") {
diagnostics.errors.push(
`"placement.hint" cannot be set if "placement.mode" is not "smart"`
);
}
}
return inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"placement",
() => true,
void 0
);
}
function validateTailConsumer(diagnostics, field, value) {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"${field}" should be an object but got ${JSON.stringify(value)}.`
);
return false;
}
let isValid2 = true;
isValid2 = isValid2 && validateRequiredProperty(
diagnostics,
field,
"service",
value.service,
"string"
);
isValid2 = isValid2 && validateOptionalProperty(
diagnostics,
field,
"environment",
value.environment,
"string"
);
return isValid2;
}
function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDispatchNamespace, envName = "top level", topLevelEnv, isLegacyEnv2, rawConfig) {
deprecated(
diagnostics,
rawEnv,
// @ts-expect-error Removed from the config type
"node_compat",
`The "node_compat" field is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`,
true,
"Removed",
"error"
);
experimental(diagnostics, rawEnv, "unsafe");
const route = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
const account_id = inheritableInLegacyEnvironments(
diagnostics,
isLegacyEnv2,
topLevelEnv,
mutateEmptyStringAccountIDValue(diagnostics, rawEnv),
"account_id",
isString2,
void 0,
void 0
);
const routes = validateRoutes2(diagnostics, topLevelEnv, rawEnv);
const workers_dev = inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"workers_dev",
isBoolean,
void 0
);
const preview_urls = inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"preview_urls",
isBoolean,
true
);
const build5 = normalizeAndValidateBuild(
diagnostics,
rawEnv,
rawEnv.build ?? topLevelEnv?.build ?? {},
configPath
);
const environment = {
// Inherited fields
account_id,
compatibility_date: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"compatibility_date",
validateCompatibilityDate,
void 0
),
compatibility_flags: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"compatibility_flags",
isStringArray,
[]
),
jsx_factory: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"jsx_factory",
isString2,
"React.createElement"
),
jsx_fragment: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"jsx_fragment",
isString2,
"React.Fragment"
),
tsconfig: validateAndNormalizeTsconfig(
diagnostics,
topLevelEnv,
rawEnv,
configPath
),
rules: validateAndNormalizeRules(diagnostics, topLevelEnv, rawEnv, envName),
name: inheritableInLegacyEnvironments(
diagnostics,
isLegacyEnv2,
topLevelEnv,
rawEnv,
"name",
isDispatchNamespace ? isString2 : isValidName,
appendEnvName(envName),
void 0
),
main: normalizeAndValidateMainField(
configPath,
inheritable(diagnostics, topLevelEnv, rawEnv, "main", isString2, void 0)
),
find_additional_modules: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"find_additional_modules",
isBoolean,
void 0
),
preserve_file_names: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"preserve_file_names",
isBoolean,
void 0
),
base_dir: normalizeAndValidateBaseDirField(
configPath,
inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"base_dir",
isString2,
void 0
)
),
route,
routes,
triggers: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"triggers",
validateTriggers,
{ crons: void 0 }
),
assets: normalizeAndValidateAssets(diagnostics, topLevelEnv, rawEnv),
limits: normalizeAndValidateLimits(diagnostics, topLevelEnv, rawEnv),
placement: normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv),
build: build5,
workers_dev,
preview_urls,
// Not inherited fields
vars: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"vars",
validateVars(envName),
{}
),
define: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"define",
validateDefines(envName),
{}
),
durable_objects: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"durable_objects",
validateBindingsProperty(envName, validateDurableObjectBinding),
{
bindings: []
}
),
workflows: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"workflows",
all(
validateBindingArray(envName, validateWorkflowBinding),
validateUniqueNameProperty
),
[]
),
migrations: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"migrations",
validateMigrations,
[]
),
kv_namespaces: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"kv_namespaces",
validateBindingArray(envName, validateKVBinding),
[]
),
cloudchamber: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"cloudchamber",
validateCloudchamberConfig,
{}
),
containers: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"containers",
validateContainerApp(envName, rawEnv.name, configPath),
void 0
),
send_email: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"send_email",
validateBindingArray(envName, validateSendEmailBinding),
[]
),
queues: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"queues",
validateQueues(envName),
{ producers: [], consumers: [] }
),
r2_buckets: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"r2_buckets",
validateBindingArray(envName, validateR2Binding),
[]
),
d1_databases: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"d1_databases",
validateBindingArray(envName, validateD1Binding),
[]
),
vectorize: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"vectorize",
validateBindingArray(envName, validateVectorizeBinding),
[]
),
hyperdrive: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"hyperdrive",
validateBindingArray(envName, validateHyperdriveBinding),
[]
),
services: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"services",
validateBindingArray(envName, validateServiceBinding),
[]
),
analytics_engine_datasets: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"analytics_engine_datasets",
validateBindingArray(envName, validateAnalyticsEngineBinding),
[]
),
dispatch_namespaces: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"dispatch_namespaces",
validateBindingArray(envName, validateWorkerNamespaceBinding),
[]
),
mtls_certificates: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"mtls_certificates",
validateBindingArray(envName, validateMTlsCertificateBinding),
[]
),
tail_consumers: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"tail_consumers",
validateTailConsumers,
void 0
),
unsafe: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"unsafe",
validateUnsafeSettings(envName),
{}
),
browser: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"browser",
validateNamedSimpleBinding(envName),
void 0
),
ai: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"ai",
validateAIBinding(envName),
void 0
),
images: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"images",
validateNamedSimpleBinding(envName),
void 0
),
pipelines: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"pipelines",
validateBindingArray(envName, validatePipelineBinding),
[]
),
secrets_store_secrets: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"secrets_store_secrets",
validateBindingArray(envName, validateSecretsStoreSecretBinding),
[]
),
unsafe_hello_world: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"unsafe_hello_world",
validateBindingArray(envName, validateHelloWorldBinding),
[]
),
version_metadata: notInheritable(
diagnostics,
topLevelEnv,
rawConfig,
rawEnv,
envName,
"version_metadata",
validateVersionMetadataBinding(envName),
void 0
),
logfwdr: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"logfwdr",
validateCflogfwdrObject(envName),
{
bindings: []
}
),
no_bundle: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"no_bundle",
isBoolean,
void 0
),
minify: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"minify",
isBoolean,
void 0
),
keep_names: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"keep_names",
isBoolean,
void 0
),
first_party_worker: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"first_party_worker",
isBoolean,
void 0
),
logpush: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"logpush",
isBoolean,
void 0
),
upload_source_maps: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"upload_source_maps",
isBoolean,
void 0
),
observability: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"observability",
validateObservability,
void 0
),
compliance_region: inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"compliance_region",
isOneOf("public", "fedramp_high"),
void 0
)
};
warnIfDurableObjectsHaveNoMigrations(
diagnostics,
environment.durable_objects,
environment.migrations,
configPath
);
return environment;
}
function validateAndNormalizeTsconfig(diagnostics, topLevelEnv, rawEnv, configPath) {
const tsconfig = inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"tsconfig",
isString2,
void 0
);
return configPath && tsconfig ? import_node_path9.default.relative(
process.cwd(),
import_node_path9.default.join(import_node_path9.default.dirname(configPath), tsconfig)
) : tsconfig;
}
function validateContainerApp(envName, topLevelName, configPath) {
return (diagnostics, field, value, config) => {
if (!value) {
return true;
}
if (!Array.isArray(value)) {
diagnostics.errors.push(
`"containers" field should be an array, but got ${JSON.stringify(value)}`
);
return false;
}
for (const containerAppOptional of value) {
if (!isOptionalProperty(value, "name", "string")) {
diagnostics.errors.push(
`Field "name", when present, should be a string, but got ${JSON.stringify(value)}`
);
}
validateRequiredProperty(
diagnostics,
field,
"class_name",
containerAppOptional.class_name,
"string"
);
validateOptionalProperty(
diagnostics,
field,
"name",
containerAppOptional.name,
"string"
);
if (!containerAppOptional.name) {
if (!topLevelName || !isOptionalProperty(containerAppOptional, "class_name", "string")) {
diagnostics.errors.push(
`Must have either a top level "name" and "containers.class_name" field defined, or have field "containers.name" defined.`
);
}
let name2 = `${topLevelName}-${containerAppOptional.class_name}`;
name2 += config === void 0 ? "" : `-${envName}`;
containerAppOptional.name = name2.toLowerCase().replace(/ /g, "-");
}
if (!containerAppOptional.configuration?.image && !containerAppOptional.image) {
diagnostics.errors.push(
`"containers.image" field must be defined for each container app. This should be the path to your Dockerfile or an image URI pointing to the Cloudflare registry.`
);
}
if ("configuration" in containerAppOptional) {
diagnostics.warnings.push(
`"containers.configuration" is deprecated. Use top level "containers" fields instead. "configuration.image" should be "image", limits should be set via "instance_type".`
);
if (typeof containerAppOptional.configuration !== "object" || Array.isArray(containerAppOptional.configuration)) {
diagnostics.errors.push(
`"containers.configuration" should be an object`
);
}
if (containerAppOptional.instance_type && (containerAppOptional.configuration.disk !== void 0 || containerAppOptional.configuration.vcpu !== void 0 || containerAppOptional.configuration.memory_mib !== void 0)) {
diagnostics.errors.push(
`Cannot set custom limits via "containers.configuration" and use preset "instance_type" limits at the same time.`
);
}
}
validateOptionalProperty(
diagnostics,
field,
"image_build_context",
containerAppOptional.image_build_context,
"string"
);
let resolvedImage = containerAppOptional.image ?? containerAppOptional.configuration?.image;
let resolvedBuildContextPath = void 0;
try {
if (isDockerfile(resolvedImage, configPath)) {
const baseDir = configPath ? import_node_path9.default.dirname(configPath) : process.cwd();
resolvedImage = import_node_path9.default.resolve(baseDir, resolvedImage);
resolvedBuildContextPath = containerAppOptional.image_build_context ? import_node_path9.default.resolve(baseDir, containerAppOptional.image_build_context) : import_node_path9.default.dirname(resolvedImage);
}
} catch (err) {
if (err instanceof Error && err.message) {
diagnostics.errors.push(err.message);
} else {
throw err;
}
}
containerAppOptional.image = resolvedImage;
containerAppOptional.image_build_context = resolvedBuildContextPath;
if (containerAppOptional.rollout_step_percentage !== void 0) {
const rolloutStep = containerAppOptional.rollout_step_percentage;
if (typeof rolloutStep === "number") {
const allowedSingleValues = [5, 10, 20, 25, 50, 100];
if (!allowedSingleValues.includes(rolloutStep)) {
diagnostics.errors.push(
`"containers.rollout_step_percentage" must be one of [5, 10, 20, 25, 50, 100], but got ${rolloutStep}`
);
}
} else if (Array.isArray(rolloutStep)) {
const nonNumber = [];
const outOfRange = [];
let index = 0;
let ascending = true;
for (const step of rolloutStep) {
if (typeof step !== "number") {
nonNumber.push(step);
} else {
if (step < 10 || step > 100) {
outOfRange.push(step);
}
if (ascending && index > 0 && step < rolloutStep[index - 1]) {
diagnostics.errors.push(
`"containers.rollout_step_percentage" array elements must be in ascending order, but got "${rolloutStep}"`
);
ascending = false;
}
if (index === rolloutStep.length - 1 && step !== 100) {
diagnostics.errors.push(
`The final step in "containers.rollout_step_percentage" must be 100, but got "${step}"`
);
}
index++;
}
}
if (nonNumber.length) {
diagnostics.errors.push(
`"containers.rollout_step_percentage" array elements must be numbers, but got "${nonNumber.join(", ")}"`
);
}
if (outOfRange.length) {
diagnostics.errors.push(
`"containers.rollout_step_percentage" array elements must be between 10 and 100, but got "${outOfRange.join(", ")}"`
);
}
} else {
diagnostics.errors.push(
`"containers.rollout_step_percentage" must be a number or array of numbers, but got "${rolloutStep}"`
);
}
}
validateOptionalProperty(
diagnostics,
field,
"rollout_kind",
containerAppOptional.rollout_kind,
"string",
["full_auto", "full_manual", "none"]
);
if (!isOptionalProperty(
containerAppOptional,
"rollout_active_grace_period",
"number"
) || containerAppOptional.rollout_active_grace_period < 0) {
diagnostics.errors.push(
`"containers.rollout_active_grace_period" field should be a positive number but got "${containerAppOptional.rollout_active_grace_period}"`
);
}
validateOptionalProperty(
diagnostics,
field,
"max_instances",
containerAppOptional.max_instances,
"number"
);
if (containerAppOptional.max_instances !== void 0 && containerAppOptional.max_instances < 0) {
diagnostics.errors.push(
`"containers.max_instances" field should be a positive number, but got ${containerAppOptional.max_instances}`
);
}
if (containerAppOptional.rollout_step_percentage !== void 0 && containerAppOptional.max_instances !== void 0 && Array.isArray(containerAppOptional.rollout_step_percentage)) {
const rolloutStepsCount = containerAppOptional.rollout_step_percentage.length;
if (rolloutStepsCount > containerAppOptional.max_instances) {
diagnostics.errors.push(
`"containers.rollout_step_percentage" cannot have more steps (${rolloutStepsCount}) than "max_instances" (${containerAppOptional.max_instances})`
);
}
}
validateOptionalProperty(
diagnostics,
field,
"image_vars",
containerAppOptional.image_vars,
"object"
);
validateOptionalProperty(
diagnostics,
field,
"scheduling_policy",
containerAppOptional.scheduling_policy,
"string",
["regional", "moon", "default"]
);
if ("instances" in containerAppOptional) {
diagnostics.warnings.push(
`"containers.instances" is deprecated. Use "containers.max_instances" instead.`
);
}
if ("durable_objects" in containerAppOptional) {
diagnostics.warnings.push(
`"containers.durable_objects" is deprecated. Use the "class_name" field instead.`
);
}
validateAdditionalProperties(
diagnostics,
field,
Object.keys(containerAppOptional),
[
"name",
"instances",
"max_instances",
"image",
"image_build_context",
"image_vars",
"class_name",
"scheduling_policy",
"instance_type",
"configuration",
"constraints",
"rollout_step_percentage",
"rollout_kind",
"durable_objects",
"rollout_active_grace_period"
]
);
if ("configuration" in containerAppOptional) {
validateAdditionalProperties(
diagnostics,
`${field}.configuration`,
Object.keys(containerAppOptional.configuration),
["image", "secrets", "labels", "disk", "vcpu", "memory_mib"]
);
}
if (typeof containerAppOptional.instance_type === "string") {
validateOptionalProperty(
diagnostics,
field,
"instance_type",
containerAppOptional.instance_type,
"string",
["dev", "basic", "standard"]
);
} else if (validateOptionalProperty(
diagnostics,
field,
"instance_type",
containerAppOptional.instance_type,
"object"
) && containerAppOptional.instance_type) {
const instanceTypeProperties = ["vcpu", "memory_mib", "disk_mb"];
instanceTypeProperties.forEach((key) => {
if (!isOptionalProperty(
containerAppOptional.instance_type,
key,
"number"
)) {
diagnostics.errors.push(
`"containers.instance_type.${key}", when present, should be a number.`
);
}
});
validateAdditionalProperties(
diagnostics,
`${field}.instance_type`,
Object.keys(containerAppOptional.instance_type),
instanceTypeProperties
);
}
}
if (diagnostics.errors.length > 0) {
return false;
}
return true;
};
}
function validateWorkerNamespaceOutbound(diagnostics, field, value) {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"${field}" should be an object, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
isValid2 = isValid2 && validateRequiredProperty(
diagnostics,
field,
"service",
value.service,
"string"
);
isValid2 = isValid2 && validateOptionalProperty(
diagnostics,
field,
"environment",
value.environment,
"string"
);
isValid2 = isValid2 && validateOptionalTypedArray(
diagnostics,
`${field}.parameters`,
value.parameters,
"string"
);
return isValid2;
}
function validateQueues(envName) {
return (diagnostics, field, value, config) => {
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (typeof value !== "object" || Array.isArray(value) || value === null) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.`
);
return false;
}
let isValid2 = true;
if (!validateAdditionalProperties(
diagnostics,
fieldPath,
Object.keys(value),
["consumers", "producers"]
)) {
isValid2 = false;
}
if (hasProperty(value, "consumers")) {
const consumers = value.consumers;
if (!Array.isArray(consumers)) {
diagnostics.errors.push(
`The field "${fieldPath}.consumers" should be an array but got ${JSON.stringify(
consumers
)}.`
);
isValid2 = false;
}
for (let i5 = 0; i5 < consumers.length; i5++) {
const consumer = consumers[i5];
const consumerPath = `${fieldPath}.consumers[${i5}]`;
if (!validateConsumer(diagnostics, consumerPath, consumer, config)) {
isValid2 = false;
}
}
}
if (hasProperty(value, "producers")) {
if (!validateBindingArray(envName, validateQueueBinding)(
diagnostics,
`${field}.producers`,
value.producers,
config
)) {
isValid2 = false;
}
}
return isValid2;
};
}
function normalizeAndValidateLimits(diagnostics, topLevelEnv, rawEnv) {
if (rawEnv.limits) {
validateRequiredProperty(
diagnostics,
"limits",
"cpu_ms",
rawEnv.limits.cpu_ms,
"number"
);
}
return inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"limits",
() => true,
void 0
);
}
function warnIfDurableObjectsHaveNoMigrations(diagnostics, durableObjects, migrations, configPath) {
if (Array.isArray(durableObjects.bindings) && durableObjects.bindings.length > 0) {
const exportedDurableObjects = (durableObjects.bindings || []).filter(
(binding) => !binding.script_name
);
if (exportedDurableObjects.length > 0 && migrations.length === 0) {
if (!exportedDurableObjects.some(
(exportedDurableObject) => typeof exportedDurableObject.class_name !== "string"
)) {
const durableObjectClassnames = exportedDurableObjects.map(
(durable) => durable.class_name
);
diagnostics.warnings.push(dedent`
In your ${configFileName(configPath)} file, you have configured \`durable_objects\` exported by this Worker (${durableObjectClassnames.join(", ")}), but no \`migrations\` for them. This may not work as expected until you add a \`migrations\` section to your ${configFileName(configPath)} file. Add the following configuration:
\`\`\`
${formatConfigSnippet(
{
migrations: [{ tag: "v1", new_classes: durableObjectClassnames }]
},
configPath
)}
\`\`\`
Refer to https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/ for more details.`);
}
}
}
}
function isRemoteValid(targetObject, fieldPath, diagnostics) {
if (!isOptionalProperty(targetObject, "experimental_remote", "boolean")) {
diagnostics.errors.push(
`"${fieldPath}" should, optionally, have a boolean "experimental_remote" field but got ${JSON.stringify(
targetObject
)}.`
);
return false;
}
return true;
}
var import_node_assert, import_node_path9, ENGLISH, isRoute, isRouteArray, validateTailConsumers, validateAndNormalizeRules, validateTriggers, validateRules, validateRule, validateDefines, validateVars, validateBindingsProperty, validateUnsafeSettings, validateDurableObjectBinding, validateWorkflowBinding, validateCflogfwdrObject, validateCflogfwdrBinding, validateAssetsConfig, validateNamedSimpleBinding, validateAIBinding, validateVersionMetadataBinding, validateUnsafeBinding, validateBindingArray, validateCloudchamberConfig, validateKVBinding, validateSendEmailBinding, validateQueueBinding, validateR2Binding, validateD1Binding, validateVectorizeBinding, validateHyperdriveBinding, validateBindingsHaveUniqueNames, validateServiceBinding, validateAnalyticsEngineBinding, validateWorkerNamespaceBinding, validateMTlsCertificateBinding, validateConsumer, validateCompatibilityDate, validatePipelineBinding, validateSecretsStoreSecretBinding, validateHelloWorldBinding, validateMigrations, validateObservability;
var init_validation = __esm({
"src/config/validation.ts"() {
init_import_meta_url();
import_node_assert = __toESM(require("assert"));
import_node_path9 = __toESM(require("path"));
init_containers_shared();
init_esm2();
init_errors();
init_experimental_flags();
init_helpers();
init_print_bindings();
init_diagnostics();
init_validation_helpers();
init_config2();
ENGLISH = new Intl.ListFormat("en-US");
__name(isPagesConfig, "isPagesConfig");
__name(normalizeAndValidateConfig, "normalizeAndValidateConfig");
__name(applyPythonConfig, "applyPythonConfig");
__name(normalizeAndValidateBuild, "normalizeAndValidateBuild");
__name(normalizeAndValidateMainField, "normalizeAndValidateMainField");
__name(normalizeAndValidateBaseDirField, "normalizeAndValidateBaseDirField");
__name(normalizeAndValidatePagesBuildOutputDir, "normalizeAndValidatePagesBuildOutputDir");
__name(normalizeAndValidateDev, "normalizeAndValidateDev");
__name(normalizeAndValidateAssets, "normalizeAndValidateAssets");
__name(normalizeAndValidateSite, "normalizeAndValidateSite");
__name(normalizeAndValidateAliases, "normalizeAndValidateAliases");
__name(normalizeAndValidateModulePaths, "normalizeAndValidateModulePaths");
__name(isValidRouteValue, "isValidRouteValue");
__name(mutateEmptyStringAccountIDValue, "mutateEmptyStringAccountIDValue");
__name(mutateEmptyStringRouteValue, "mutateEmptyStringRouteValue");
isRoute = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value !== void 0 && !isValidRouteValue(value)) {
diagnostics.errors.push(
`Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
value
)}.`
);
return false;
}
return true;
}, "isRoute");
isRouteArray = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value === void 0) {
return true;
}
if (!Array.isArray(value)) {
diagnostics.errors.push(
`Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
);
return false;
}
const invalidRoutes = [];
for (const item of value) {
if (!isValidRouteValue(item)) {
invalidRoutes.push(item);
}
}
if (invalidRoutes.length > 0) {
diagnostics.errors.push(
`Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
invalidRoutes,
null,
2
)}.`
);
}
return invalidRoutes.length === 0;
}, "isRouteArray");
__name(normalizeAndValidateRoute, "normalizeAndValidateRoute");
__name(validateRoutes2, "validateRoutes");
__name(normalizeAndValidatePlacement, "normalizeAndValidatePlacement");
__name(validateTailConsumer, "validateTailConsumer");
validateTailConsumers = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (!value) {
return true;
}
if (!Array.isArray(value)) {
diagnostics.errors.push(
`Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
);
return false;
}
let isValid2 = true;
for (let i5 = 0; i5 < value.length; i5++) {
isValid2 = validateTailConsumer(diagnostics, `${field}[${i5}]`, value[i5]) && isValid2;
}
return isValid2;
}, "validateTailConsumers");
__name(normalizeAndValidateEnvironment, "normalizeAndValidateEnvironment");
__name(validateAndNormalizeTsconfig, "validateAndNormalizeTsconfig");
validateAndNormalizeRules = /* @__PURE__ */ __name((diagnostics, topLevelEnv, rawEnv, envName) => {
return inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"rules",
validateRules(envName),
[]
);
}, "validateAndNormalizeRules");
validateTriggers = /* @__PURE__ */ __name((diagnostics, triggersFieldName, triggersValue) => {
if (triggersValue === void 0 || triggersValue === null) {
return true;
}
if (typeof triggersValue !== "object") {
diagnostics.errors.push(
`Expected "${triggersFieldName}" to be of type object but got ${JSON.stringify(
triggersValue
)}.`
);
return false;
}
let isValid2 = true;
if ("crons" in triggersValue && !Array.isArray(triggersValue.crons)) {
diagnostics.errors.push(
`Expected "${triggersFieldName}.crons" to be of type array, but got ${JSON.stringify(triggersValue)}.`
);
isValid2 = false;
}
isValid2 = validateAdditionalProperties(
diagnostics,
triggersFieldName,
Object.keys(triggersValue),
["crons"]
) && isValid2;
return isValid2;
}, "validateTriggers");
validateRules = /* @__PURE__ */ __name((envName) => (diagnostics, field, envValue, config) => {
if (!envValue) {
return true;
}
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (!Array.isArray(envValue)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an array but got ${JSON.stringify(
envValue
)}.`
);
return false;
}
let isValid2 = true;
for (let i5 = 0; i5 < envValue.length; i5++) {
isValid2 = validateRule(diagnostics, `${fieldPath}[${i5}]`, envValue[i5], config) && isValid2;
}
return isValid2;
}, "validateRules");
validateRule = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"${field}" should be an object but got ${JSON.stringify(value)}.`
);
return false;
}
let isValid2 = true;
const rule = value;
if (!isRequiredProperty(rule, "type", "string", [
"ESModule",
"CommonJS",
"CompiledWasm",
"Text",
"Data"
])) {
diagnostics.errors.push(
`bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
);
isValid2 = false;
}
isValid2 = validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") && isValid2;
if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
diagnostics.errors.push(
`the field "fallthrough", when present, should be a boolean.`
);
isValid2 = false;
}
return isValid2;
}, "validateRule");
validateDefines = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
let isValid2 = true;
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (typeof value === "object" && value !== null) {
for (const varName in value) {
if (typeof value[varName] !== "string") {
diagnostics.errors.push(
`The field "${fieldPath}.${varName}" should be a string but got ${JSON.stringify(
value[varName]
)}.`
);
isValid2 = false;
}
}
} else {
if (value !== void 0) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.
`
);
isValid2 = false;
}
}
const configDefines = Object.keys(config?.define ?? {});
if (configDefines.length > 0) {
if (typeof value === "object" && value !== null) {
const configEnvDefines = config === void 0 ? [] : Object.keys(value);
for (const varName of configDefines) {
if (!(varName in value)) {
diagnostics.warnings.push(
`"define.${varName}" exists at the top level, but not on "${fieldPath}".
This is not what you probably want, since "define" configuration is not inherited by environments.
Please add "define.${varName}" to "env.${envName}".`
);
}
}
for (const varName of configEnvDefines) {
if (!configDefines.includes(varName)) {
diagnostics.warnings.push(
`"${varName}" exists on "env.${envName}", but not on the top level.
This is not what you probably want, since "define" configuration within environments can only override existing top level "define" configuration
Please remove "${fieldPath}.${varName}", or add "define.${varName}".`
);
}
}
}
}
return isValid2;
}, "validateDefines");
validateVars = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
let isValid2 = true;
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
const configVars = Object.keys(config?.vars ?? {});
if (configVars.length > 0) {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.
`
);
isValid2 = false;
} else {
for (const varName of configVars) {
if (!(varName in value)) {
diagnostics.warnings.push(
`"vars.${varName}" exists at the top level, but not on "${fieldPath}".
This is not what you probably want, since "vars" configuration is not inherited by environments.
Please add "vars.${varName}" to "env.${envName}".`
);
}
}
}
}
return isValid2;
}, "validateVars");
validateBindingsProperty = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, value, config) => {
let isValid2 = true;
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (value !== void 0) {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
} else if (!hasProperty(value, "bindings")) {
diagnostics.errors.push(
`The field "${fieldPath}" is missing the required "bindings" property.`
);
isValid2 = false;
} else if (!Array.isArray(value.bindings)) {
diagnostics.errors.push(
`The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
value.bindings
)}.`
);
isValid2 = false;
} else {
for (let i5 = 0; i5 < value.bindings.length; i5++) {
const binding = value.bindings[i5];
const bindingDiagnostics = new Diagnostics(
`"${fieldPath}.bindings[${i5}]": ${JSON.stringify(binding)}`
);
isValid2 = validateBinding(
bindingDiagnostics,
`${fieldPath}.bindings[${i5}]`,
binding,
config
) && isValid2;
diagnostics.addChild(bindingDiagnostics);
}
}
const configBindingNames = getBindingNames(
config?.[field]
);
if (isValid2 && configBindingNames.length > 0) {
const envBindingNames = new Set(getBindingNames(value));
const missingBindings = configBindingNames.filter(
(name2) => !envBindingNames.has(name2)
);
if (missingBindings.length > 0) {
diagnostics.warnings.push(
`The following bindings are at the top level, but not on "env.${envName}".
This is not what you probably want, since "${field}" configuration is not inherited by environments.
Please add a binding for each to "${fieldPath}.bindings":
` + missingBindings.map((name2) => `- ${name2}`).join("\n")
);
}
}
}
return isValid2;
}, "validateBindingsProperty");
validateUnsafeSettings = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.`
);
return false;
}
if (hasProperty(value, "bindings") && value.bindings !== void 0) {
const validateBindingsFn = validateBindingsProperty(
envName,
validateUnsafeBinding
);
const valid = validateBindingsFn(diagnostics, field, value, config);
if (!valid) {
return false;
}
}
if (hasProperty(value, "metadata") && value.metadata !== void 0 && (typeof value.metadata !== "object" || value.metadata === null || Array.isArray(value.metadata))) {
diagnostics.errors.push(
`The field "${fieldPath}.metadata" should be an object but got ${JSON.stringify(
value.metadata
)}.`
);
return false;
}
if (hasProperty(value, "capnp") && value.capnp !== void 0) {
if (typeof value.capnp !== "object" || value.capnp === null || Array.isArray(value.capnp)) {
diagnostics.errors.push(
`The field "${fieldPath}.capnp" should be an object but got ${JSON.stringify(
value.capnp
)}.`
);
return false;
}
if (hasProperty(value.capnp, "compiled_schema")) {
if (hasProperty(value.capnp, "base_path") || hasProperty(value.capnp, "source_schemas")) {
diagnostics.errors.push(
`The field "${fieldPath}.capnp" cannot contain both "compiled_schema" and one of "base_path" or "source_schemas".`
);
return false;
}
if (typeof value.capnp.compiled_schema !== "string") {
diagnostics.errors.push(
`The field "${fieldPath}.capnp.compiled_schema", when present, should be a string but got ${JSON.stringify(
value.capnp.compiled_schema
)}.`
);
return false;
}
} else {
if (!isRequiredProperty(value.capnp, "base_path", "string")) {
diagnostics.errors.push(
`The field "${fieldPath}.capnp.base_path", when present, should be a string but got ${JSON.stringify(
value.capnp.base_path
)}`
);
}
if (!validateTypedArray(
diagnostics,
`${fieldPath}.capnp.source_schemas`,
value.capnp.source_schemas,
"string"
)) {
return false;
}
}
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"bindings",
"metadata",
"capnp"
]);
return true;
}, "validateUnsafeSettings");
validateDurableObjectBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`Expected "${field}" to be an object but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "name", "string")) {
diagnostics.errors.push(`binding should have a string "name" field.`);
isValid2 = false;
}
if (!isRequiredProperty(value, "class_name", "string")) {
diagnostics.errors.push(`binding should have a string "class_name" field.`);
isValid2 = false;
}
if (!isOptionalProperty(value, "script_name", "string")) {
diagnostics.errors.push(
`the field "script_name", when present, should be a string.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "environment", "string")) {
diagnostics.errors.push(
`the field "environment", when present, should be a string.`
);
isValid2 = false;
}
if ("environment" in value && !("script_name" in value)) {
diagnostics.errors.push(
`binding should have a "script_name" field if "environment" is present.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"class_name",
"environment",
"name",
"script_name"
]);
return isValid2;
}, "validateDurableObjectBinding");
validateWorkflowBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"workflows" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "name", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
} else if (value.name.length > 64) {
diagnostics.errors.push(
`"${field}" binding "name" field must be 64 characters or less, but got ${value.name.length} characters.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "class_name", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "class_name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "script_name", "string")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "script_name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "experimental_remote", "boolean")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a boolean "experimental_remote" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"name",
"class_name",
"script_name",
"experimental_remote"
]);
return isValid2;
}, "validateWorkflowBinding");
validateCflogfwdrObject = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, topLevelEnv) => {
const bindingsValidation = validateBindingsProperty(
envName,
validateCflogfwdrBinding
);
if (!bindingsValidation(diagnostics, field, value, topLevelEnv)) {
return false;
}
const v7 = value;
if (v7?.schema !== void 0) {
diagnostics.errors.push(
`"${field}" binding "schema" property has been replaced with the "unsafe.capnp" object, which expects a "base_path" and an array of "source_schemas" to compile, or a "compiled_schema" property.`
);
return false;
}
return true;
}, "validateCflogfwdrObject");
validateCflogfwdrBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`Expected "${field}" to be an object but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "name", "string")) {
diagnostics.errors.push(`binding should have a string "name" field.`);
isValid2 = false;
}
if (!isRequiredProperty(value, "destination", "string")) {
diagnostics.errors.push(
`binding should have a string "destination" field.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"destination",
"name"
]);
return isValid2;
}, "validateCflogfwdrBinding");
validateAssetsConfig = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value === void 0) {
return true;
}
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"${field}" should be an object, but got value ${JSON.stringify(
field
)} of type ${typeof value}`
);
return false;
}
let isValid2 = true;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"directory",
value.directory,
"string"
) && isValid2;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"binding",
value.binding,
"string"
) && isValid2;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"html_handling",
value.html_handling,
"string",
[
"auto-trailing-slash",
"force-trailing-slash",
"drop-trailing-slash",
"none"
]
) && isValid2;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"not_found_handling",
value.not_found_handling,
"string",
["single-page-application", "404-page", "none"]
) && isValid2;
if (value.run_worker_first !== void 0) {
if (typeof value.run_worker_first === "boolean") {
isValid2 = validateOptionalProperty(
diagnostics,
field,
"run_worker_first",
value.run_worker_first,
"boolean"
) && isValid2;
} else if (Array.isArray(value.run_worker_first)) {
isValid2 = validateOptionalTypedArray(
diagnostics,
"assets.run_worker_first",
value.run_worker_first,
"string"
) && isValid2;
} else {
diagnostics.errors.push(
`The field "${field}.run_worker_first" should be an array of strings or a boolean, but got ${JSON.stringify(
value.run_worker_first
)}.`
);
isValid2 = false;
}
}
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"directory",
"binding",
"html_handling",
"not_found_handling",
"run_worker_first"
]) && isValid2;
return isValid2;
}, "validateAssetsConfig");
validateNamedSimpleBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(`binding should have a string "binding" field.`);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"experimental_remote"
]);
return isValid2;
}, "validateNamedSimpleBinding");
validateAIBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(`binding should have a string "binding" field.`);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
return isValid2;
}, "validateAIBinding");
validateVersionMetadataBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an object but got ${JSON.stringify(
value
)}.`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(`binding should have a string "binding" field.`);
isValid2 = false;
}
return isValid2;
}, "validateVersionMetadataBinding");
validateUnsafeBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`Expected ${field} to be an object but got ${JSON.stringify(value)}.`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "name", "string")) {
diagnostics.errors.push(`binding should have a string "name" field.`);
isValid2 = false;
}
if (isRequiredProperty(value, "type", "string")) {
const safeBindings = [
"plain_text",
"secret_text",
"json",
"wasm_module",
"data_blob",
"text_blob",
"browser",
"ai",
"kv_namespace",
"durable_object_namespace",
"d1_database",
"r2_bucket",
"service",
"logfwdr",
"mtls_certificate",
"pipeline"
];
if (safeBindings.includes(value.type)) {
diagnostics.warnings.push(
`The binding type "${value.type}" is directly supported by wrangler.
Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.
For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration`
);
}
if (value.type === "metadata" && isRequiredProperty(value, "name", "string")) {
diagnostics.warnings.push(
"The deployment object in the metadata binding is now deprecated. Please switch using the version_metadata binding for access to version specific fields: https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata"
);
}
} else {
diagnostics.errors.push(`binding should have a string "type" field.`);
isValid2 = false;
}
return isValid2;
}, "validateUnsafeBinding");
validateBindingArray = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, envValue, config) => {
if (envValue === void 0) {
return true;
}
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (!Array.isArray(envValue)) {
diagnostics.errors.push(
`The field "${fieldPath}" should be an array but got ${JSON.stringify(
envValue
)}.`
);
return false;
}
let isValid2 = true;
for (let i5 = 0; i5 < envValue.length; i5++) {
isValid2 = validateBinding(
diagnostics,
`${fieldPath}[${i5}]`,
envValue[i5],
config
) && isValid2;
}
const configValue = config?.[field];
if (Array.isArray(configValue)) {
const configBindingNames = configValue.map((value) => value.binding);
if (configBindingNames.length > 0) {
const envBindingNames = new Set(envValue.map((value) => value.binding));
for (const configBindingName of configBindingNames) {
if (!envBindingNames.has(configBindingName)) {
diagnostics.warnings.push(
`There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".
This is not what you probably want, since "${field}" configuration is not inherited by environments.
Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
);
}
}
}
}
return isValid2;
}, "validateBindingArray");
__name(validateContainerApp, "validateContainerApp");
validateCloudchamberConfig = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(
`"cloudchamber" should be an object, but got ${JSON.stringify(value)}`
);
return false;
}
const optionalAttrsByType = {
string: ["memory", "image", "location"],
boolean: ["ipv4"],
number: ["vcpu"]
};
let isValid2 = true;
Object.entries(optionalAttrsByType).forEach(([attrType, attrNames]) => {
attrNames.forEach((key) => {
if (!isOptionalProperty(value, key, attrType)) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a ${attrType} "${key}" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
});
});
if ("instance_type" in value && value.instance_type !== void 0) {
if (typeof value.instance_type !== "string" || !["dev", "basic", "standard"].includes(value.instance_type)) {
diagnostics.errors.push(
`"instance_type" should be one of 'dev', 'basic', or 'standard', but got ${value.instance_type}`
);
}
if ("memory" in value && value.memory !== void 0 || "vcpu" in value && value.vcpu !== void 0) {
diagnostics.errors.push(
`"${field}" configuration should not set either "memory" or "vcpu" with "instance_type"`
);
}
}
return isValid2;
}, "validateCloudchamberConfig");
validateKVBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (getFlag("RESOURCES_PROVISION") ? !isOptionalProperty(value, "id", "string") || value.id !== void 0 && value.id.length === 0 : !isRequiredProperty(value, "id", "string") || value.id.length === 0) {
diagnostics.errors.push(
`"${field}" bindings should have a string "id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "preview_id", "string")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"id",
"preview_id",
"experimental_remote"
]);
return isValid2;
}, "validateKVBinding");
validateSendEmailBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"send_email" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "name", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "destination_address", "string")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "destination_address" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "allowed_destination_addresses", "object")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a []string "allowed_destination_addresses" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if ("destination_address" in value && "allowed_destination_addresses" in value) {
diagnostics.errors.push(
`"${field}" bindings should have either a "destination_address" or "allowed_destination_addresses" field, but not both.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"allowed_destination_addresses",
"destination_address",
"name",
"binding",
"experimental_remote"
]);
return isValid2;
}, "validateSendEmailBinding");
validateQueueBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"queue" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
if (!validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"queue",
"delivery_delay",
"experimental_remote"
])) {
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "queue", "string") || value.queue.length === 0) {
diagnostics.errors.push(
`"${field}" bindings should have a string "queue" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
const options = [{ key: "delivery_delay", type: "number" }];
for (const optionalOpt of options) {
if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
diagnostics.errors.push(
`"${field}" should, optionally, have a ${optionalOpt.type} "${optionalOpt.key}" field but got ${JSON.stringify(value)}.`
);
isValid2 = false;
}
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
return isValid2;
}, "validateQueueBinding");
validateR2Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"r2_buckets" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (getFlag("RESOURCES_PROVISION") ? !isOptionalProperty(value, "bucket_name", "string") || value.bucket_name !== void 0 && value.bucket_name.length === 0 : !isRequiredProperty(value, "bucket_name", "string") || value.bucket_name.length === 0) {
diagnostics.errors.push(
`"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (isValid2 && hasProperty(value, "bucket_name") && !isValidR2BucketName(value.bucket_name)) {
diagnostics.errors.push(
`${field}.bucket_name=${JSON.stringify(value.bucket_name)} is invalid. ${bucketFormatMessage}`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (isValid2 && hasProperty(value, "preview_bucket_name") && !isValidR2BucketName(value.preview_bucket_name)) {
diagnostics.errors.push(
`${field}.preview_bucket_name= ${JSON.stringify(value.preview_bucket_name)} is invalid. ${bucketFormatMessage}`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "jurisdiction", "string")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "jurisdiction" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"bucket_name",
"preview_bucket_name",
"jurisdiction",
"experimental_remote"
]);
return isValid2;
}, "validateR2Binding");
validateD1Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"d1_databases" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (getFlag("RESOURCES_PROVISION") ? !isOptionalProperty(value, "database_id", "string") : (
// TODO: allow name only, where we look up the ID dynamically
// !isOptionalProperty(value, "database_name", "string") &&
!isRequiredProperty(value, "database_id", "string")
)) {
diagnostics.errors.push(
`"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "preview_database_id", "string")) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "preview_database_id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"database_id",
"database_internal_env",
"database_name",
"migrations_dir",
"migrations_table",
"preview_database_id",
"experimental_remote"
]);
return isValid2;
}, "validateD1Binding");
validateVectorizeBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"vectorize" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "index_name", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have an "index_name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"index_name",
"experimental_remote"
]);
return isValid2;
}, "validateVectorizeBinding");
validateHyperdriveBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"hyperdrive" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "id", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a "id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"id",
"localConnectionString"
]);
return isValid2;
}, "validateHyperdriveBinding");
validateBindingsHaveUniqueNames = /* @__PURE__ */ __name((diagnostics, config) => {
let hasDuplicates = false;
const bindingNamesArray = Object.entries(friendlyBindingNames);
const bindingsGroupedByType = Object.fromEntries(
bindingNamesArray.map(([bindingType, binding]) => [
binding,
getBindingNames(
bindingType === "queues" ? config[bindingType]?.producers : config[bindingType]
)
])
);
const bindingsGroupedByName = {};
for (const bindingType in bindingsGroupedByType) {
const bindingNames = bindingsGroupedByType[bindingType];
for (const bindingName of bindingNames) {
if (!(bindingName in bindingsGroupedByName)) {
bindingsGroupedByName[bindingName] = [];
}
if (bindingName === "ASSETS" && isPagesConfig(config)) {
diagnostics.errors.push(
`The name 'ASSETS' is reserved in Pages projects. Please use a different name for your ${bindingType} binding.`
);
}
bindingsGroupedByName[bindingName].push(bindingType);
}
}
for (const bindingName in bindingsGroupedByName) {
const bindingTypes = bindingsGroupedByName[bindingName];
if (bindingTypes.length < 2) {
continue;
}
hasDuplicates = true;
const sameType = bindingTypes.filter((type, i5) => bindingTypes.indexOf(type) !== i5).filter(
(type, i5, duplicateBindingTypes) => duplicateBindingTypes.indexOf(type) === i5
);
const differentTypes = bindingTypes.filter(
(type, i5) => bindingTypes.indexOf(type) === i5
);
if (differentTypes.length > 1) {
diagnostics.errors.push(
`${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
);
}
sameType.forEach((bindingType) => {
diagnostics.errors.push(
`${bindingName} assigned to multiple ${bindingType} bindings.`
);
});
}
if (hasDuplicates) {
const problem = "Bindings must have unique names, so that they can all be referenced in the worker.";
const resolution = "Please change your bindings to have unique names.";
diagnostics.errors.push(`${problem}
${resolution}`);
}
return !hasDuplicates;
}, "validateBindingsHaveUniqueNames");
validateServiceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"services" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "service", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "service" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "environment", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "entrypoint", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "entrypoint" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
return isValid2;
}, "validateServiceBinding");
validateAnalyticsEngineBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"analytics_engine" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "dataset", "string") || value.dataset?.length === 0) {
diagnostics.errors.push(
`"${field}" bindings should, optionally, have a string "dataset" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"dataset"
]);
return isValid2;
}, "validateAnalyticsEngineBinding");
validateWorkerNamespaceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"${field}" binding should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "namespace", "string")) {
diagnostics.errors.push(
`"${field}" should have a string "namespace" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (hasProperty(value, "outbound")) {
if (!validateWorkerNamespaceOutbound(
diagnostics,
`${field}.outbound`,
value.outbound ?? {}
)) {
diagnostics.errors.push(`"${field}" has an invalid outbound definition.`);
isValid2 = false;
}
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
return isValid2;
}, "validateWorkerNamespaceBinding");
__name(validateWorkerNamespaceOutbound, "validateWorkerNamespaceOutbound");
validateMTlsCertificateBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"mtls_certificates" bindings should be objects, but got ${JSON.stringify(
value
)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "certificate_id", "string") || value.certificate_id.length === 0) {
diagnostics.errors.push(
`"${field}" bindings should have a string "certificate_id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"certificate_id",
"experimental_remote"
]);
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
return isValid2;
}, "validateMTlsCertificateBinding");
__name(validateQueues, "validateQueues");
validateConsumer = /* @__PURE__ */ __name((diagnostics, field, value, _config) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"${field}" should be a objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"queue",
"type",
"max_batch_size",
"max_batch_timeout",
"max_retries",
"dead_letter_queue",
"max_concurrency",
"visibility_timeout_ms",
"retry_delay"
])) {
isValid2 = false;
}
if (!isRequiredProperty(value, "queue", "string")) {
diagnostics.errors.push(
`"${field}" should have a string "queue" field but got ${JSON.stringify(
value
)}.`
);
}
const options = [
{ key: "type", type: "string" },
{ key: "max_batch_size", type: "number" },
{ key: "max_batch_timeout", type: "number" },
{ key: "max_retries", type: "number" },
{ key: "dead_letter_queue", type: "string" },
{ key: "max_concurrency", type: "number" },
{ key: "visibility_timeout_ms", type: "number" },
{ key: "retry_delay", type: "number" }
];
for (const optionalOpt of options) {
if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
diagnostics.errors.push(
`"${field}" should, optionally, have a ${optionalOpt.type} "${optionalOpt.key}" field but got ${JSON.stringify(value)}.`
);
isValid2 = false;
}
}
return isValid2;
}, "validateConsumer");
validateCompatibilityDate = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value === void 0) {
return true;
}
if (typeof value !== "string") {
diagnostics.errors.push(
`Expected "${field}" to be of type string but got ${JSON.stringify(value)}.`
);
return false;
}
return isValidDateTimeStringFormat(diagnostics, field, value);
}, "validateCompatibilityDate");
validatePipelineBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"pipeline" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "pipeline", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a string "pipeline" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) {
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"pipeline",
"experimental_remote"
]);
return isValid2;
}, "validatePipelineBinding");
validateSecretsStoreSecretBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"secrets_store_secrets" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "store_id", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a string "store_id" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isRequiredProperty(value, "secret_name", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a string "secret_name" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"store_id",
"secret_name"
]);
return isValid2;
}, "validateSecretsStoreSecretBinding");
validateHelloWorldBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(
`"unsafe_hello_world" bindings should be objects, but got ${JSON.stringify(value)}`
);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "binding", "string")) {
diagnostics.errors.push(
`"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
if (!isOptionalProperty(value, "enable_timer", "boolean")) {
diagnostics.errors.push(
`"${field}" bindings must have a boolean "enable_timer" field but got ${JSON.stringify(
value
)}.`
);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"enable_timer"
]);
return isValid2;
}, "validateHelloWorldBinding");
__name(normalizeAndValidateLimits, "normalizeAndValidateLimits");
validateMigrations = /* @__PURE__ */ __name((diagnostics, field, value) => {
const rawMigrations = value ?? [];
if (!Array.isArray(rawMigrations)) {
diagnostics.errors.push(
`The optional "${field}" field should be an array, but got ${JSON.stringify(
rawMigrations
)}`
);
return false;
}
let valid = true;
for (let i5 = 0; i5 < rawMigrations.length; i5++) {
const {
tag,
new_classes,
new_sqlite_classes,
renamed_classes,
deleted_classes,
transferred_classes,
...rest
} = rawMigrations[i5];
valid = validateAdditionalProperties(
diagnostics,
"migrations",
Object.keys(rest),
[]
) && valid;
valid = validateRequiredProperty(
diagnostics,
`migrations[${i5}]`,
`tag`,
tag,
"string"
) && valid;
valid = validateOptionalTypedArray(
diagnostics,
`migrations[${i5}].new_classes`,
new_classes,
"string"
) && valid;
valid = validateOptionalTypedArray(
diagnostics,
`migrations[${i5}].new_sqlite_classes`,
new_sqlite_classes,
"string"
) && valid;
if (renamed_classes !== void 0) {
if (!Array.isArray(renamed_classes)) {
diagnostics.errors.push(
`Expected "migrations[${i5}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
renamed_classes
)}.`
);
valid = false;
} else if (renamed_classes.some(
(c6) => typeof c6 !== "object" || !isRequiredProperty(c6, "from", "string") || !isRequiredProperty(c6, "to", "string")
)) {
diagnostics.errors.push(
`Expected "migrations[${i5}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
renamed_classes
)}.`
);
valid = false;
}
}
if (transferred_classes !== void 0) {
if (!Array.isArray(transferred_classes)) {
diagnostics.errors.push(
`Expected "migrations[${i5}].transferred_classes" to be an array of "{from: string, from_script: string, to: string}" objects but got ${JSON.stringify(
transferred_classes
)}.`
);
valid = false;
} else if (transferred_classes.some(
(c6) => typeof c6 !== "object" || !isRequiredProperty(c6, "from", "string") || !isRequiredProperty(c6, "from_script", "string") || !isRequiredProperty(c6, "to", "string")
)) {
diagnostics.errors.push(
`Expected "migrations[${i5}].transferred_classes" to be an array of "{from: string, from_script: string, to: string}" objects but got ${JSON.stringify(
transferred_classes
)}.`
);
valid = false;
}
}
valid = validateOptionalTypedArray(
diagnostics,
`migrations[${i5}].deleted_classes`,
deleted_classes,
"string"
) && valid;
}
return valid;
}, "validateMigrations");
validateObservability = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (value === void 0) {
return true;
}
if (typeof value !== "object") {
diagnostics.errors.push(
`"${field}" should be an object but got ${JSON.stringify(value)}.`
);
return false;
}
const val2 = value;
let isValid2 = true;
isValid2 = validateAtLeastOnePropertyRequired(diagnostics, field, [
{
key: "enabled",
value: val2.enabled,
type: "boolean"
},
{
key: "logs.enabled",
value: val2.logs?.enabled,
type: "boolean"
}
]) && isValid2;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"head_sampling_rate",
val2.head_sampling_rate,
"number"
) && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "logs", val2.logs, "object") && isValid2;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(val2), [
"enabled",
"head_sampling_rate",
"logs"
]) && isValid2;
if (typeof val2.logs === "object") {
isValid2 = validateOptionalProperty(
diagnostics,
field,
"logs.enabled",
val2.logs.enabled,
"boolean"
) && isValid2;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"logs.head_sampling_rate",
val2.logs.head_sampling_rate,
"number"
) && isValid2;
isValid2 = validateOptionalProperty(
diagnostics,
field,
"logs.invocation_logs",
val2.logs.invocation_logs,
"boolean"
) && isValid2;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(val2.logs), [
"enabled",
"head_sampling_rate",
"invocation_logs"
]) && isValid2;
}
const samplingRate = val2?.head_sampling_rate;
if (samplingRate && (samplingRate < 0 || samplingRate > 1)) {
diagnostics.errors.push(
`"${field}.head_sampling_rate" must be a value between 0 and 1.`
);
}
return isValid2;
}, "validateObservability");
__name(warnIfDurableObjectsHaveNoMigrations, "warnIfDurableObjectsHaveNoMigrations");
__name(isRemoteValid, "isRemoteValid");
}
});
// src/config/config.ts
var defaultWranglerConfig;
var init_config = __esm({
"src/config/config.ts"() {
init_import_meta_url();
defaultWranglerConfig = {
/* COMPUTED_FIELDS */
configPath: void 0,
userConfigPath: void 0,
topLevelName: void 0,
/*====================================================*/
/* Fields supported by both Workers & Pages */
/*====================================================*/
/* TOP-LEVEL ONLY FIELDS */
pages_build_output_dir: void 0,
send_metrics: void 0,
dev: {
ip: process.platform === "win32" ? "127.0.0.1" : "localhost",
port: void 0,
// the default of 8787 is set at runtime
inspector_port: void 0,
// the default of 9229 is set at runtime
local_protocol: "http",
upstream_protocol: "http",
host: void 0,
// Note this one is also workers only
enable_containers: true,
container_engine: void 0
},
/** INHERITABLE ENVIRONMENT FIELDS **/
name: void 0,
compatibility_date: void 0,
compatibility_flags: [],
limits: void 0,
placement: void 0,
/** NON-INHERITABLE ENVIRONMENT FIELDS **/
vars: {},
durable_objects: { bindings: [] },
kv_namespaces: [],
queues: {
producers: [],
consumers: []
// WORKERS SUPPORT ONLY!!
},
r2_buckets: [],
d1_databases: [],
vectorize: [],
hyperdrive: [],
workflows: [],
secrets_store_secrets: [],
services: [],
analytics_engine_datasets: [],
ai: void 0,
images: void 0,
version_metadata: void 0,
unsafe_hello_world: [],
/*====================================================*/
/* Fields supported by Workers only */
/*====================================================*/
/* TOP-LEVEL ONLY FIELDS */
legacy_env: true,
site: void 0,
wasm_modules: void 0,
text_blobs: void 0,
data_blobs: void 0,
keep_vars: void 0,
alias: void 0,
/** INHERITABLE ENVIRONMENT FIELDS **/
account_id: void 0,
main: void 0,
find_additional_modules: void 0,
preserve_file_names: void 0,
base_dir: void 0,
workers_dev: void 0,
preview_urls: true,
route: void 0,
routes: void 0,
tsconfig: void 0,
jsx_factory: "React.createElement",
jsx_fragment: "React.Fragment",
migrations: [],
triggers: {
crons: void 0
},
rules: [],
build: { command: void 0, watch_dir: "./src", cwd: void 0 },
no_bundle: void 0,
minify: void 0,
keep_names: void 0,
dispatch_namespaces: [],
first_party_worker: void 0,
logfwdr: { bindings: [] },
logpush: void 0,
upload_source_maps: void 0,
assets: void 0,
observability: { enabled: true },
/** The default here is undefined so that we can delegate to the CLOUDFLARE_COMPLIANCE_REGION environment variable. */
compliance_region: void 0,
/** NON-INHERITABLE ENVIRONMENT FIELDS **/
define: {},
cloudchamber: {},
containers: void 0,
send_email: [],
browser: void 0,
unsafe: {},
mtls_certificates: [],
tail_consumers: void 0,
pipelines: []
};
}
});
// src/config/validation-pages.ts
function validatePagesConfig(config, envNames, projectName) {
if (!config.pages_build_output_dir) {
throw new FatalError(`Attempting to validate Pages configuration file, but "pages_build_output_dir" field was not found.
"pages_build_output_dir" is required for Pages projects.`);
}
const diagnostics = new Diagnostics(
`Running configuration file validation for Pages:`
);
validateMainField(config, diagnostics);
validateProjectName(projectName, diagnostics);
validatePagesEnvironmentNames(envNames, diagnostics);
validateUnsupportedFields(config, diagnostics);
validateDurableObjectBinding2(config, diagnostics);
return diagnostics;
}
function validateMainField(config, diagnostics) {
if (config.main !== void 0) {
diagnostics.errors.push(
`Configuration file cannot contain both both "main" and "pages_build_output_dir" configuration keys.
Please use "main" if you are deploying a Worker, or "pages_build_output_dir" if you are deploying a Pages project.`
);
}
}
function validateProjectName(name2, diagnostics) {
if (name2 === void 0 || name2.trim() === "") {
diagnostics.errors.push(
`Missing top-level field "name" in configuration file.
Pages requires the name of your project to be configured at the top-level of your Wrangler configuration file. This is because, in Pages, environments target the same project.`
);
}
}
function validatePagesEnvironmentNames(envNames, diagnostics) {
if (!envNames?.length) {
return;
}
const unsupportedPagesEnvNames = envNames.filter(
(name2) => name2 !== "preview" && name2 !== "production"
);
if (unsupportedPagesEnvNames.length > 0) {
diagnostics.errors.push(
`Configuration file contains the following environment names that are not supported by Pages projects:
${unsupportedPagesEnvNames.map((name2) => `"${name2}"`).join()}.
The supported named-environments for Pages are "preview" and "production".`
);
}
}
function validateUnsupportedFields(config, diagnostics) {
const unsupportedFields = new Set(Object.keys(config));
for (const field of supportedPagesConfigFields) {
if (field === "queues" && config.queues?.consumers?.length) {
continue;
}
unsupportedFields.delete(field);
}
for (const field of unsupportedFields) {
if (config[field] === void 0 || JSON.stringify(config[field]) === JSON.stringify(defaultWranglerConfig[field])) {
unsupportedFields.delete(field);
}
}
if (unsupportedFields.size > 0) {
const fields = Array.from(unsupportedFields.keys());
fields.forEach((field) => {
if (field === "queues" && config.queues?.consumers?.length) {
diagnostics.errors.push(
`Configuration file for Pages projects does not support "queues.consumers"`
);
} else {
diagnostics.errors.push(
`Configuration file for Pages projects does not support "${field}"`
);
}
});
}
}
function validateDurableObjectBinding2(config, diagnostics) {
if (config.durable_objects.bindings.length > 0) {
const invalidBindings = config.durable_objects.bindings.filter(
(binding) => !isRequiredProperty(binding, "script_name", "string")
);
if (invalidBindings.length > 0) {
diagnostics.errors.push(
`Durable Objects bindings should specify a "script_name".
Pages requires Durable Object bindings to specify the name of the Worker where the Durable Object is defined.`
);
}
}
}
var supportedPagesConfigFields;
var init_validation_pages = __esm({
"src/config/validation-pages.ts"() {
init_import_meta_url();
init_errors();
init_config();
init_diagnostics();
init_validation_helpers();
supportedPagesConfigFields = [
"pages_build_output_dir",
"name",
"compatibility_date",
"compatibility_flags",
"send_metrics",
"no_bundle",
"limits",
"placement",
"vars",
"durable_objects",
"kv_namespaces",
"queues",
// `producers` ONLY
"r2_buckets",
"d1_databases",
"vectorize",
"hyperdrive",
"services",
"analytics_engine_datasets",
"ai",
"version_metadata",
"dev",
"mtls_certificates",
"browser",
"upload_source_maps",
// normalizeAndValidateConfig() sets these values
"configPath",
"userConfigPath",
"topLevelName"
];
__name(validatePagesConfig, "validatePagesConfig");
__name(validateMainField, "validateMainField");
__name(validateProjectName, "validateProjectName");
__name(validatePagesEnvironmentNames, "validatePagesEnvironmentNames");
__name(validateUnsupportedFields, "validateUnsupportedFields");
__name(validateDurableObjectBinding2, "validateDurableObjectBinding");
}
});
// src/config/index.ts
function configFormat(configPath) {
if (configPath?.endsWith("toml")) {
return "toml";
} else if (configPath?.endsWith("json") || configPath?.endsWith("jsonc")) {
return "jsonc";
}
return "none";
}
function configFileName(configPath) {
const format9 = configFormat(configPath);
if (format9 === "toml") {
return "wrangler.toml";
} else if (format9 === "jsonc") {
return "wrangler.json";
} else {
return "Wrangler configuration";
}
}
function formatConfigSnippet(snippet, configPath, formatted = true) {
const format9 = configFormat(configPath);
if (format9 === "toml") {
return import_toml3.default.stringify(snippet);
} else {
return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
}
}
async function updateConfigFile(snippet, configPath, env6, offerToUpdate = true) {
const resource = Object.keys(snippet())[0];
const envString = env6 ? ` in the "${env6}" environment` : "";
logger.log(
`To access your new ${friendlyBindingNames[resource]} in your Worker, add the following snippet to your configuration file${envString}:`
);
logger.log(formatConfigSnippet(snippet(), configPath));
if (configPath && offerToUpdate && configFormat(configPath) === "jsonc") {
const autoAdd = await select(
"Would you like Wrangler to add it on your behalf?",
{
choices: [
{ title: "Yes", value: "yes" },
{
title: "Yes, but let me choose the binding name",
value: "yes-but"
},
{ title: "No", value: "no" }
],
defaultOption: 0,
fallbackOption: 2
}
);
let bindingName;
if (autoAdd === "yes-but") {
bindingName = await prompt("What binding name would you like to use?");
}
if (autoAdd !== "no") {
experimental_patchConfig(
configPath,
env6 ? { env: { [env6]: snippet(bindingName) } } : snippet(bindingName),
true
);
}
}
}
function readConfig(args, options = {}) {
const { rawConfig, configPath, userConfigPath } = experimental_readRawConfig(
args,
options
);
const { diagnostics, config } = normalizeAndValidateConfig(
rawConfig,
configPath,
userConfigPath,
args
);
if (diagnostics.hasWarnings() && !options?.hideWarnings) {
logger.warn(diagnostics.renderWarnings());
}
if (diagnostics.hasErrors()) {
throw new UserError(diagnostics.renderErrors());
}
return config;
}
function readPagesConfig(args, options = {}) {
let rawConfig;
let configPath;
let userConfigPath;
try {
({ rawConfig, configPath, userConfigPath } = experimental_readRawConfig(
args,
options
));
} catch (e7) {
logger.error(e7);
throw new FatalError(
`Your ${configFileName(configPath)} file is not a valid Pages configuration file`,
EXIT_CODE_INVALID_PAGES_CONFIG
);
}
if (!isPagesConfig(rawConfig)) {
throw new FatalError(
`Your ${configFileName(configPath)} file is not a valid Pages configuration file`,
EXIT_CODE_INVALID_PAGES_CONFIG
);
}
const { config, diagnostics } = normalizeAndValidateConfig(
rawConfig,
configPath,
userConfigPath,
args
);
if (diagnostics.hasWarnings() && !options.hideWarnings) {
logger.warn(diagnostics.renderWarnings());
}
if (diagnostics.hasErrors()) {
throw new UserError(diagnostics.renderErrors());
}
logger.debug(
`Configuration file belonging to \u26A1\uFE0F Pages \u26A1\uFE0F project detected.`
);
const envNames = rawConfig.env ? Object.keys(rawConfig.env) : [];
const projectName = rawConfig?.name;
const pagesDiagnostics = validatePagesConfig(config, envNames, projectName);
if (pagesDiagnostics.hasWarnings()) {
logger.warn(pagesDiagnostics.renderWarnings());
}
if (pagesDiagnostics.hasErrors()) {
throw new UserError(pagesDiagnostics.renderErrors());
}
return config;
}
var import_toml3, parseRawConfigFile, experimental_readRawConfig;
var init_config2 = __esm({
"src/config/index.ts"() {
init_import_meta_url();
import_toml3 = __toESM(require_toml());
init_dialogs();
init_errors();
init_logger();
init_errors3();
init_parse();
init_print_bindings();
init_config_helpers();
init_patch_config();
init_validation();
init_validation_pages();
__name(configFormat, "configFormat");
__name(configFileName, "configFileName");
__name(formatConfigSnippet, "formatConfigSnippet");
__name(updateConfigFile, "updateConfigFile");
__name(readConfig, "readConfig");
__name(readPagesConfig, "readPagesConfig");
parseRawConfigFile = /* @__PURE__ */ __name((configPath) => {
if (configPath.endsWith(".toml")) {
return parseTOML(readFileSync6(configPath), configPath);
}
if (configPath.endsWith(".json") || configPath.endsWith(".jsonc")) {
return parseJSONC(readFileSync6(configPath), configPath);
}
return {};
}, "parseRawConfigFile");
experimental_readRawConfig = /* @__PURE__ */ __name((args, options = {}) => {
const { configPath, userConfigPath } = resolveWranglerConfigPath(
args,
options
);
const rawConfig = parseRawConfigFile(configPath ?? "");
return { rawConfig, configPath, userConfigPath };
}, "experimental_readRawConfig");
}
});
// src/config-cache.ts
function getCacheFolder() {
if (__cacheFolder || __cacheFolder === null) {
return __cacheFolder;
}
const closestNodeModulesDirectory = findUpSync("node_modules", {
type: "directory"
});
__cacheFolder = closestNodeModulesDirectory ? path11.join(closestNodeModulesDirectory, ".cache/wrangler") : null;
if (!__cacheFolder) {
logger.debug("No folder available to cache configuration");
}
return __cacheFolder;
}
function showCacheMessage(fields, folder) {
if (!cacheMessageShown && !isNonInteractiveOrCI()) {
if (fields.length > 0) {
logger.debug(
`Retrieving cached values for ${arrayFormatter.format(
fields
)} from ${path11.relative(process.cwd(), folder)}`
);
cacheMessageShown = true;
}
}
}
function getConfigCache(fileName) {
try {
const cacheFolder = getCacheFolder();
if (cacheFolder) {
const configCacheLocation = path11.join(cacheFolder, fileName);
const configCache = JSON.parse(
(0, import_fs9.readFileSync)(configCacheLocation, "utf-8")
);
showCacheMessage(Object.keys(configCache), cacheFolder);
return configCache;
} else {
return {};
}
} catch {
return {};
}
}
function saveToConfigCache(fileName, newValues) {
const cacheFolder = getCacheFolder();
if (cacheFolder) {
logger.debug(`Saving to cache: ${JSON.stringify(newValues)}`);
const configCacheLocation = path11.join(cacheFolder, fileName);
const existingValues = getConfigCache(fileName);
(0, import_fs9.mkdirSync)(path11.dirname(configCacheLocation), { recursive: true });
(0, import_fs9.writeFileSync)(
configCacheLocation,
JSON.stringify({ ...existingValues, ...newValues }, null, 2)
);
}
}
function purgeConfigCaches() {
const cacheFolder = getCacheFolder();
if (cacheFolder) {
(0, import_fs9.rmSync)(cacheFolder, { recursive: true, force: true });
}
__cacheFolder = void 0;
}
var import_fs9, path11, cacheMessageShown, __cacheFolder, arrayFormatter;
var init_config_cache = __esm({
"src/config-cache.ts"() {
init_import_meta_url();
import_fs9 = require("fs");
path11 = __toESM(require("path"));
init_find_up();
init_is_interactive();
init_logger();
cacheMessageShown = false;
__name(getCacheFolder, "getCacheFolder");
arrayFormatter = new Intl.ListFormat("en-US", {
style: "long",
type: "conjunction"
});
__name(showCacheMessage, "showCacheMessage");
__name(getConfigCache, "getConfigCache");
__name(saveToConfigCache, "saveToConfigCache");
__name(purgeConfigCaches, "purgeConfigCaches");
}
});
// ../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js
var require_is_docker = __commonJS({
"../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var fs24 = require("fs");
var isDocker;
function hasDockerEnv() {
try {
fs24.statSync("/.dockerenv");
return true;
} catch (_4) {
return false;
}
}
__name(hasDockerEnv, "hasDockerEnv");
function hasDockerCGroup() {
try {
return fs24.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
} catch (_4) {
return false;
}
}
__name(hasDockerCGroup, "hasDockerCGroup");
module3.exports = () => {
if (isDocker === void 0) {
isDocker = hasDockerEnv() || hasDockerCGroup();
}
return isDocker;
};
}
});
// ../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js
var require_is_wsl = __commonJS({
"../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var os12 = require("os");
var fs24 = require("fs");
var isDocker = require_is_docker();
var isWsl = /* @__PURE__ */ __name(() => {
if (process.platform !== "linux") {
return false;
}
if (os12.release().toLowerCase().includes("microsoft")) {
if (isDocker()) {
return false;
}
return true;
}
try {
return fs24.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
} catch (_4) {
return false;
}
}, "isWsl");
if (process.env.__IS_WSL_TEST__) {
module3.exports = isWsl;
} else {
module3.exports = isWsl();
}
}
});
// ../../node_modules/.pnpm/define-lazy-prop@2.0.0/node_modules/define-lazy-prop/index.js
var require_define_lazy_prop = __commonJS({
"../../node_modules/.pnpm/define-lazy-prop@2.0.0/node_modules/define-lazy-prop/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = (object, propertyName, fn2) => {
const define = /* @__PURE__ */ __name((value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true }), "define");
Object.defineProperty(object, propertyName, {
configurable: true,
enumerable: true,
get() {
const result = fn2();
define(result);
return result;
},
set(value) {
define(value);
}
});
return object;
};
}
});
// ../../node_modules/.pnpm/open@8.4.0/node_modules/open/index.js
var require_open = __commonJS({
"../../node_modules/.pnpm/open@8.4.0/node_modules/open/index.js"(exports2, module3) {
init_import_meta_url();
var path72 = require("path");
var childProcess2 = require("child_process");
var { promises: fs24, constants: fsConstants } = require("fs");
var isWsl = require_is_wsl();
var isDocker = require_is_docker();
var defineLazyProperty = require_define_lazy_prop();
var localXdgOpenPath = path72.join(__dirname, "xdg-open");
var { platform: platform3, arch: arch2 } = 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 fs24.access(configFilePath, fsConstants.F_OK);
isConfigFileExists = true;
} catch {
}
if (!isConfigFileExists) {
return defaultMountPoint;
}
const configContent = await fs24.readFile(configFilePath, { encoding: "utf8" });
const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
if (!configMountPoint) {
return defaultMountPoint;
}
mountPoint = configMountPoint.groups.mountPoint.trim();
mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
return mountPoint;
};
})();
var pTryEach = /* @__PURE__ */ __name(async (array, mapper) => {
let latestError;
for (const item of array) {
try {
return await mapper(item);
} catch (error2) {
latestError = error2;
}
}
throw latestError;
}, "pTryEach");
var baseOpen = /* @__PURE__ */ __name(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 command2;
const cliArguments = [];
const childProcessOptions = {};
if (platform3 === "darwin") {
command2 = "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 (platform3 === "win32" || isWsl && !isDocker()) {
const mountPoint = await getWslDrivesMountPoint();
command2 = 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) {
command2 = app;
} else {
const isBundled = !__dirname || __dirname === "/";
let exeLocalXdgOpen = false;
try {
await fs24.access(localXdgOpenPath, fsConstants.X_OK);
exeLocalXdgOpen = true;
} catch {
}
const useSystemXdgOpen = process.versions.electron || platform3 === "android" || isBundled || !exeLocalXdgOpen;
command2 = 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 (platform3 === "darwin" && appArguments.length > 0) {
cliArguments.push("--args", ...appArguments);
}
const subprocess = childProcess2.spawn(command2, cliArguments, childProcessOptions);
if (options.wait) {
return new Promise((resolve25, reject) => {
subprocess.once("error", reject);
subprocess.once("close", (exitCode) => {
if (options.allowNonzeroExitCode && exitCode > 0) {
reject(new Error(`Exited with code ${exitCode}`));
return;
}
resolve25(subprocess);
});
});
}
subprocess.unref();
return subprocess;
}, "baseOpen");
var open4 = /* @__PURE__ */ __name((target, options) => {
if (typeof target !== "string") {
throw new TypeError("Expected a `target`");
}
return baseOpen({
...options,
target
});
}, "open");
var openApp = /* @__PURE__ */ __name((name2, options) => {
if (typeof name2 !== "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: name2,
arguments: appArguments
}
});
}, "openApp");
function detectArchBinary(binary) {
if (typeof binary === "string" || Array.isArray(binary)) {
return binary;
}
const { [arch2]: archBinary } = binary;
if (!archBinary) {
throw new Error(`${arch2} is not supported`);
}
return archBinary;
}
__name(detectArchBinary, "detectArchBinary");
function detectPlatformBinary({ [platform3]: platformBinary }, { wsl }) {
if (wsl && isWsl) {
return detectArchBinary(wsl);
}
if (!platformBinary) {
throw new Error(`${platform3} is not supported`);
}
return detectArchBinary(platformBinary);
}
__name(detectPlatformBinary, "detectPlatformBinary");
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"
}));
open4.apps = apps;
open4.openApp = openApp;
module3.exports = open4;
}
});
// src/open-in-browser.ts
async function openInBrowser(url4) {
const childProcess2 = await (0, import_open.default)(url4);
childProcess2.on("error", () => {
logger.warn("Failed to open");
});
}
var import_open;
var init_open_in_browser = __esm({
"src/open-in-browser.ts"() {
init_import_meta_url();
import_open = __toESM(require_open());
init_logger();
__name(openInBrowser, "openInBrowser");
}
});
// src/user/access.ts
async function domainUsesAccess(domain2) {
logger.debug("Checking if domain has Access enabled:", domain2);
if (usesAccessCache.has(domain2)) {
logger.debug(
"Using cached Access switch for:",
domain2,
usesAccessCache.get(domain2)
);
return usesAccessCache.get(domain2);
}
logger.debug("Access switch not cached for:", domain2);
try {
const controller = new AbortController();
const cancel3 = setTimeout(() => {
controller.abort();
}, 1e3);
const output = await (0, import_undici.fetch)(`https://${domain2}`, {
redirect: "manual",
signal: controller.signal
});
clearTimeout(cancel3);
const usesAccess = !!(output.status === 302 && output.headers.get("location")?.includes("cloudflareaccess.com"));
logger.debug("Caching access switch for:", domain2);
usesAccessCache.set(domain2, usesAccess);
return usesAccess;
} catch {
usesAccessCache.set(domain2, false);
return false;
}
}
async function getAccessToken(domain2) {
if (!await domainUsesAccess(domain2)) {
return void 0;
}
if (cache[domain2]) {
return cache[domain2];
}
const output = (0, import_child_process4.spawnSync)("cloudflared", ["access", "login", domain2]);
if (output.error) {
throw new UserError(
"To use Wrangler with Cloudflare Access, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
);
}
const stringOutput = output.stdout.toString();
const matches = stringOutput.match(/fetched your token:\n\n(.*)/m);
if (matches && matches.length >= 2) {
cache[domain2] = matches[1];
return matches[1];
}
throw new Error("Failed to authenticate with Cloudflare Access");
}
var import_child_process4, import_undici, cache, usesAccessCache;
var init_access = __esm({
"src/user/access.ts"() {
init_import_meta_url();
import_child_process4 = require("child_process");
import_undici = __toESM(require_undici());
init_errors();
init_logger();
cache = {};
usesAccessCache = /* @__PURE__ */ new Map();
__name(domainUsesAccess, "domainUsesAccess");
__name(getAccessToken, "getAccessToken");
}
});
// src/user/auth-variables.ts
var getCloudflareAccountIdFromEnv, getCloudflareAPITokenFromEnv, getCloudflareGlobalAuthKeyFromEnv, getCloudflareGlobalAuthEmailFromEnv, getClientIdFromEnv, getAuthDomainFromEnv, getAuthUrlFromEnv, getTokenUrlFromEnv, getRevokeUrlFromEnv, getCloudflareAccessToken;
var init_auth_variables = __esm({
"src/user/auth-variables.ts"() {
init_import_meta_url();
init_factory();
init_misc_variables();
init_access();
getCloudflareAccountIdFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_ACCOUNT_ID",
deprecatedName: "CF_ACCOUNT_ID"
});
getCloudflareAPITokenFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_API_TOKEN",
deprecatedName: "CF_API_TOKEN"
});
getCloudflareGlobalAuthKeyFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_API_KEY",
deprecatedName: "CF_API_KEY"
});
getCloudflareGlobalAuthEmailFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_EMAIL",
deprecatedName: "CF_EMAIL"
});
getClientIdFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_CLIENT_ID",
defaultValue: /* @__PURE__ */ __name(() => getCloudflareApiEnvironmentFromEnv() === "staging" ? "4b2ea6cc-9421-4761-874b-ce550e0e3def" : "54d11594-84e4-41aa-b438-e81b8fa78ee7", "defaultValue")
});
getAuthDomainFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_AUTH_DOMAIN",
defaultValue: /* @__PURE__ */ __name(() => getCloudflareApiEnvironmentFromEnv() === "staging" ? "dash.staging.cloudflare.com" : "dash.cloudflare.com", "defaultValue")
});
getAuthUrlFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_AUTH_URL",
defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/auth`, "defaultValue")
});
getTokenUrlFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_TOKEN_URL",
defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/token`, "defaultValue")
});
getRevokeUrlFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_REVOKE_URL",
defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/revoke`, "defaultValue")
});
getCloudflareAccessToken = /* @__PURE__ */ __name(async () => {
const env6 = getEnvironmentVariableFactory({
variableName: "WRANGLER_CF_AUTHORIZATION_TOKEN"
})();
if (env6 !== void 0) {
return env6;
}
return getAccessToken(getAuthDomainFromEnv());
}, "getCloudflareAccessToken");
}
});
// src/user/choose-account.ts
async function getAccountChoices(complianceConfig) {
const accountIdFromEnv = getCloudflareAccountIdFromEnv();
if (accountIdFromEnv) {
return [{ id: accountIdFromEnv, name: "" }];
} else {
try {
const response = await fetchPagedListResult(complianceConfig, `/memberships`);
const accounts = response.map((r7) => r7.account);
if (accounts.length === 0) {
throw new UserError(
`Failed to automatically retrieve account IDs for the logged in user.
In a non-interactive environment, it is mandatory to specify an account ID, either by assigning its value to CLOUDFLARE_ACCOUNT_ID, or as \`account_id\` in your ${configFileName(void 0)} file.`
);
} else {
return accounts;
}
} catch (err) {
if (err.code === 9109) {
throw new UserError(
`Failed to automatically retrieve account IDs for the logged in user.
You may have incorrect permissions on your API token. You can skip this account check by adding an \`account_id\` in your ${configFileName(void 0)} file, or by setting the value of CLOUDFLARE_ACCOUNT_ID"`
);
} else {
throw err;
}
}
}
}
var init_choose_account = __esm({
"src/user/choose-account.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_errors();
init_auth_variables();
__name(getAccountChoices, "getAccountChoices");
}
});
// src/user/generate-auth-url.ts
var generateAuthUrl;
var init_generate_auth_url = __esm({
"src/user/generate-auth-url.ts"() {
init_import_meta_url();
generateAuthUrl = /* @__PURE__ */ __name(({
authUrl,
clientId,
callbackUrl,
scopes,
stateQueryParam,
codeChallenge
}) => {
return authUrl + `?response_type=code&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(callbackUrl)}&scope=${encodeURIComponent([...scopes, "offline_access"].join(" "))}&state=${stateQueryParam}&code_challenge=${encodeURIComponent(codeChallenge)}&code_challenge_method=S256`;
}, "generateAuthUrl");
}
});
// src/user/generate-random-state.ts
function generateRandomState(lengthOfState) {
const output = new Uint32Array(lengthOfState);
import_node_crypto.webcrypto.getRandomValues(output);
return Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("");
}
var import_node_crypto;
var init_generate_random_state = __esm({
"src/user/generate-random-state.ts"() {
init_import_meta_url();
import_node_crypto = require("crypto");
init_user2();
__name(generateRandomState, "generateRandomState");
}
});
// src/user/user.ts
function getAuthFromEnv() {
const globalApiKey = getCloudflareGlobalAuthKeyFromEnv();
const globalApiEmail = getCloudflareGlobalAuthEmailFromEnv();
const apiToken = getCloudflareAPITokenFromEnv();
if (globalApiKey && globalApiEmail) {
return { authKey: globalApiKey, authEmail: globalApiEmail };
} else if (apiToken) {
return { apiToken };
}
}
function validateScopeKeys(scopes) {
return scopes.every((scope) => scope in DefaultScopes);
}
function getCallbackUrl(host = "localhost", port = 8976) {
return `http://${host}:${port}/oauth/callback`;
}
function getAuthTokens(config) {
try {
if (getAuthFromEnv()) {
return;
}
const { oauth_token, refresh_token, expiration_time, scopes, api_token } = config || readAuthConfigFile();
if (oauth_token) {
return {
accessToken: {
value: oauth_token,
// If there is no `expiration_time` field then set it to an old date, to cause it to expire immediately.
expiry: expiration_time ?? "2000-01-01:00:00:00+00:00"
},
refreshToken: { value: refresh_token ?? "" },
scopes
};
} else if (api_token) {
logger.warn(
"It looks like you have used Wrangler v1's `config` command to login with an API token.\nThis is no longer supported in the current version of Wrangler.\nIf you wish to authenticate via an API token then please set the `CLOUDFLARE_API_TOKEN` environment variable."
);
return { apiToken: api_token };
}
} catch {
return void 0;
}
}
function reinitialiseAuthTokens(config) {
LocalState = {
...getAuthTokens(config)
};
}
function getAPIToken() {
if (LocalState.apiToken) {
return { apiToken: LocalState.apiToken };
}
const localAPIToken = getAuthFromEnv();
if (localAPIToken) {
return localAPIToken;
}
const storedAccessToken = LocalState.accessToken?.value;
if (storedAccessToken) {
return { apiToken: storedAccessToken };
}
return void 0;
}
function toErrorClass(rawError) {
return new (RawErrorToErrorClassMap[rawError] || ErrorUnknown)();
}
function isReturningFromAuthServer(query) {
if (query.error) {
if (Array.isArray(query.error)) {
throw toErrorClass(query.error[0]);
}
throw toErrorClass(query.error);
}
const code = query.code;
if (!code) {
return false;
}
const state2 = LocalState;
const stateQueryParam = query.state;
if (stateQueryParam !== state2.stateQueryParam) {
logger.warn(
"Received query string parameter doesn't match the one sent! Possible malicious activity somewhere."
);
throw new ErrorInvalidReturnedStateParam();
}
(0, import_node_assert2.default)(!Array.isArray(code));
state2.authorizationCode = code;
state2.hasAuthCodeBeenExchangedForAccessToken = false;
return true;
}
async function getAuthURL(scopes, clientId, callbackHost, callbackPort) {
const { codeChallenge, codeVerifier } = await generatePKCECodes();
const stateQueryParam = generateRandomState(RECOMMENDED_STATE_LENGTH);
Object.assign(LocalState, {
codeChallenge,
codeVerifier,
stateQueryParam
});
return generateAuthUrl({
authUrl: getAuthUrlFromEnv(),
clientId,
callbackUrl: getCallbackUrl(callbackHost, callbackPort),
scopes,
stateQueryParam,
codeChallenge
});
}
async function exchangeRefreshTokenForAccessToken() {
if (!LocalState.refreshToken) {
logger.warn("No refresh token is present.");
}
const params = new URLSearchParams({
grant_type: "refresh_token",
refresh_token: LocalState.refreshToken?.value ?? "",
client_id: getClientIdFromEnv()
});
const response = await fetchAuthToken(params);
if (response.status >= 400) {
let tokenExchangeResErr = void 0;
try {
tokenExchangeResErr = await response.text();
tokenExchangeResErr = JSON.parse(tokenExchangeResErr);
} catch {
}
if (tokenExchangeResErr !== void 0) {
throw typeof tokenExchangeResErr === "string" ? new Error(tokenExchangeResErr) : tokenExchangeResErr;
} else {
throw new ErrorUnknown(
"Failed to parse Error from exchangeRefreshTokenForAccessToken"
);
}
} else {
try {
const json = await getJSONFromResponse(response);
if ("error" in json) {
throw json.error;
}
const { access_token, expires_in, refresh_token, scope } = json;
let scopes = [];
const accessToken = {
value: access_token,
expiry: new Date(Date.now() + expires_in * 1e3).toISOString()
};
LocalState.accessToken = accessToken;
if (refresh_token) {
LocalState.refreshToken = {
value: refresh_token
};
}
if (scope) {
scopes = scope.split(" ");
LocalState.scopes = scopes;
}
const accessContext = {
token: accessToken,
scopes,
refreshToken: LocalState.refreshToken
};
return accessContext;
} catch (error2) {
if (typeof error2 === "string") {
throw toErrorClass(error2);
} else {
throw error2;
}
}
}
}
async function exchangeAuthCodeForAccessToken() {
const { authorizationCode, codeVerifier = "" } = LocalState;
if (!codeVerifier) {
logger.warn("No code verifier is being sent.");
} else if (!authorizationCode) {
logger.warn("No authorization grant code is being passed.");
}
const params = new URLSearchParams({
grant_type: `authorization_code`,
code: authorizationCode ?? "",
redirect_uri: getCallbackUrl(),
client_id: getClientIdFromEnv(),
code_verifier: codeVerifier
});
const response = await fetchAuthToken(params);
if (!response.ok) {
const { error: error2 } = await getJSONFromResponse(response);
if (error2 === "invalid_grant") {
logger.log("Expired! Auth code or refresh token needs to be renewed.");
}
throw toErrorClass(error2);
}
const json = await getJSONFromResponse(response);
if ("error" in json) {
throw new Error(json.error);
}
const { access_token, expires_in, refresh_token, scope } = json;
let scopes = [];
LocalState.hasAuthCodeBeenExchangedForAccessToken = true;
const expiryDate = new Date(Date.now() + expires_in * 1e3);
const accessToken = {
value: access_token,
expiry: expiryDate.toISOString()
};
LocalState.accessToken = accessToken;
if (refresh_token) {
LocalState.refreshToken = {
value: refresh_token
};
}
if (scope) {
scopes = scope.split(" ");
LocalState.scopes = scopes;
}
const accessContext = {
token: accessToken,
scopes,
refreshToken: LocalState.refreshToken
};
return accessContext;
}
function base64urlEncode(value) {
let base642 = btoa(value);
base642 = base642.replace(/\+/g, "-");
base642 = base642.replace(/\//g, "_");
base642 = base642.replace(/=/g, "");
return base642;
}
async function generatePKCECodes() {
const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
import_node_crypto2.webcrypto.getRandomValues(output);
const codeVerifier = base64urlEncode(
Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("")
);
const buffer = await import_node_crypto2.webcrypto.subtle.digest(
"SHA-256",
new import_node_util2.TextEncoder().encode(codeVerifier)
);
const hash = new Uint8Array(buffer);
let binary = "";
const hashLength = hash.byteLength;
for (let i5 = 0; i5 < hashLength; i5++) {
binary += String.fromCharCode(hash[i5]);
}
const codeChallenge = base64urlEncode(binary);
return { codeChallenge, codeVerifier };
}
function getAuthConfigFilePath() {
const environment = getCloudflareApiEnvironmentFromEnv();
const filePath = `${USER_AUTH_CONFIG_PATH}/${environment === "production" ? "default.toml" : `${environment}.toml`}`;
return import_node_path10.default.join(getGlobalWranglerConfigPath(), filePath);
}
function writeAuthConfigFile(config) {
const configPath = getAuthConfigFilePath();
(0, import_node_fs5.mkdirSync)(import_node_path10.default.dirname(configPath), {
recursive: true
});
(0, import_node_fs5.writeFileSync)(import_node_path10.default.join(configPath), import_toml4.default.stringify(config), {
encoding: "utf-8"
});
reinitialiseAuthTokens();
}
function readAuthConfigFile() {
const toml = parseTOML(readFileSync6(getAuthConfigFilePath()));
return toml;
}
async function loginOrRefreshIfRequired(complianceConfig, props) {
if (!getAPIToken()) {
return !isNonInteractiveOrCI() && await login(complianceConfig, props);
} else if (isAccessTokenExpired()) {
const didRefresh = await refreshToken();
if (didRefresh) {
return true;
} else {
return !isNonInteractiveOrCI() && await login(complianceConfig, props);
}
} else {
return true;
}
}
async function getOauthToken(options) {
const urlToOpen = await getAuthURL(
options.scopes,
options.clientId,
options.callbackHost,
options.callbackPort
);
let server;
let loginTimeoutHandle;
const timerPromise = new Promise((_4, reject) => {
loginTimeoutHandle = setTimeout(() => {
server.close();
clearTimeout(loginTimeoutHandle);
reject(
new UserError(
"Timed out waiting for authorization code, please try again."
)
);
}, 12e4);
});
const loginPromise = new Promise((resolve25, reject) => {
server = import_node_http.default.createServer(async (req, res) => {
function finish(token, error2) {
clearTimeout(loginTimeoutHandle);
server.close((closeErr) => {
if (error2 || closeErr) {
reject(error2 || closeErr);
} else {
(0, import_node_assert2.default)(token);
resolve25(token);
}
});
}
__name(finish, "finish");
(0, import_node_assert2.default)(req.url, "This request doesn't have a URL");
const { pathname, query } = import_node_url4.default.parse(req.url, true);
if (req.method !== "GET") {
return res.end("OK");
}
switch (pathname) {
case "/oauth/callback": {
let hasAuthCode = false;
try {
hasAuthCode = isReturningFromAuthServer(query);
} catch (err) {
if (err instanceof ErrorAccessDenied) {
res.writeHead(307, {
Location: options.denied.url
});
res.end(() => {
finish(null, new UserError(options.denied.error));
});
return;
} else {
finish(null, err);
return;
}
}
if (!hasAuthCode) {
finish(null, new ErrorNoAuthCode());
return;
} else {
const exchange = await exchangeAuthCodeForAccessToken();
res.writeHead(307, {
Location: options.granted.url
});
res.end(() => {
finish(exchange);
});
return;
}
}
}
});
if (options.callbackHost !== "localhost" || options.callbackPort !== 8976) {
logger.log(
`Temporary login server listening on ${options.callbackHost}:${options.callbackPort}`
);
}
server.listen(options.callbackPort, options.callbackHost);
});
if (options.browser) {
logger.log(`Opening a link in your default browser: ${urlToOpen}`);
await openInBrowser(urlToOpen);
} else {
logger.log(`Visit this link to authenticate: ${urlToOpen}`);
}
return Promise.race([timerPromise, loginPromise]);
}
async function login(complianceConfig, props = {
browser: true,
callbackHost: "localhost",
callbackPort: 8976
}) {
const authFromEnv = getAuthFromEnv();
if (authFromEnv) {
logger.error(
"You are logged in with an API Token. Unset the CLOUDFLARE_API_TOKEN in the environment to log in via OAuth."
);
return false;
}
const complianceRegion = getCloudflareComplianceRegion(complianceConfig);
if (complianceRegion === "fedramp_high") {
const configurationSource = complianceConfig?.compliance_region ? "`compliance_region` configuration property" : "`CLOUDFLARE_API_ENVIRONMENT` environment variable";
throw new UserError(esm_default2`
OAuth login is not supported in the \`${complianceRegion}\` compliance region.
Please use a Cloudflare API token (\`CLOUDFLARE_API_TOKEN\` environment variable) or remove the ${configurationSource}.
`);
}
logger.log("Attempting to login via OAuth...");
const oauth = await getOauthToken({
browser: !!props.browser,
scopes: props.scopes ?? DefaultScopeKeys,
clientId: getClientIdFromEnv(),
denied: {
url: "https://welcome.developers.workers.dev/wrangler-oauth-consent-denied",
error: "Error: Consent denied. You must grant consent to Wrangler in order to login.\nIf you don't want to do this consider passing an API token via the `CLOUDFLARE_API_TOKEN` environment variable"
},
granted: {
url: "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted"
},
callbackHost: props.callbackHost,
callbackPort: props.callbackPort
});
writeAuthConfigFile({
oauth_token: oauth.token?.value ?? "",
expiration_time: oauth.token?.expiry,
refresh_token: oauth.refreshToken?.value,
scopes: oauth.scopes
});
logger.log(`Successfully logged in.`);
purgeConfigCaches();
return true;
}
function isAccessTokenExpired() {
const { accessToken } = LocalState;
return Boolean(accessToken && /* @__PURE__ */ new Date() >= new Date(accessToken.expiry));
}
async function refreshToken() {
try {
const {
token: { value: oauth_token, expiry: expiration_time } = {
value: "",
expiry: ""
},
refreshToken: { value: refresh_token } = {},
scopes
} = await exchangeRefreshTokenForAccessToken();
writeAuthConfigFile({
oauth_token,
expiration_time,
refresh_token,
scopes
});
return true;
} catch {
return false;
}
}
async function logout() {
const authFromEnv = getAuthFromEnv();
if (authFromEnv) {
logger.log(
"You are logged in with an API Token. Unset the CLOUDFLARE_API_TOKEN in the environment to log out."
);
return;
}
if (!LocalState.accessToken) {
if (!LocalState.refreshToken) {
logger.log("Not logged in, exiting...");
return;
}
const body2 = `client_id=${encodeURIComponent(getClientIdFromEnv())}&token_type_hint=refresh_token&token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
const response2 = await (0, import_undici2.fetch)(getRevokeUrlFromEnv(), {
method: "POST",
body: body2,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
await response2.text();
logger.log(
"\u{1F481} Wrangler is configured with an OAuth token. The token has been successfully revoked"
);
}
const body = `client_id=${encodeURIComponent(getClientIdFromEnv())}&token_type_hint=refresh_token&token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
const response = await (0, import_undici2.fetch)(getRevokeUrlFromEnv(), {
method: "POST",
body,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
await response.text();
(0, import_node_fs5.rmSync)(getAuthConfigFilePath());
logger.log(`Successfully logged out.`);
}
function listScopes(message = "\u{1F481} Available scopes:") {
logger.log(message);
printScopes(DefaultScopeKeys);
}
async function getAccountId(complianceConfig) {
const cachedAccount2 = getAccountFromCache();
if (cachedAccount2 && !getCloudflareAccountIdFromEnv()) {
return cachedAccount2.id;
}
const accounts = await getAccountChoices(complianceConfig);
if (accounts.length === 1) {
saveAccountToCache({ id: accounts[0].id, name: accounts[0].name });
return accounts[0].id;
}
try {
const accountID = await select("Select an account", {
choices: accounts.map((account2) => ({
title: account2.name,
value: account2.id
}))
});
const account = accounts.find(
(a5) => a5.id === accountID
);
saveAccountToCache({ id: account.id, name: account.name });
return accountID;
} catch (e7) {
if (e7 instanceof NoDefaultValueProvided) {
throw new UserError(
`More than one account available but unable to select one in non-interactive mode.
Please set the appropriate \`account_id\` in your ${configFileName(void 0)} file or assign it to the \`CLOUDFLARE_ACCOUNT_ID\` environment variable.
Available accounts are (\`<name>\`: \`<account_id>\`):
${accounts.map((account) => ` \`${account.name}\`: \`${account.id}\``).join("\n")}`
);
}
throw e7;
}
}
async function requireAuth(config) {
const loggedIn = await loginOrRefreshIfRequired(config);
if (!loggedIn) {
if (isNonInteractiveOrCI()) {
throw new UserError(
"In a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for wrangler to work. Please go to https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN."
);
} else {
throw new UserError("Did not login, quitting...");
}
}
const accountId = config.account_id || await getAccountId(config);
if (!accountId) {
throw new UserError("No account id found, quitting...");
}
return accountId;
}
function requireApiToken() {
const credentials = getAPIToken();
if (!credentials) {
throw new UserError("No API token found.");
}
return credentials;
}
function saveAccountToCache(account) {
saveToConfigCache(
"wrangler-account.json",
{ account }
);
}
function getAccountFromCache() {
return getConfigCache(
"wrangler-account.json"
).account;
}
function getScopes() {
return LocalState.scopes;
}
function printScopes(scopes) {
const data = scopes.map((scope) => ({
Scope: scope,
Description: DefaultScopes[scope]
}));
logger.table(data);
}
async function fetchAuthToken(body) {
const headers = {
"Content-Type": "application/x-www-form-urlencoded"
};
if (await domainUsesAccess(getAuthDomainFromEnv())) {
headers["Cookie"] = `CF_Authorization=${await getCloudflareAccessToken()}`;
}
return await (0, import_undici2.fetch)(getTokenUrlFromEnv(), {
method: "POST",
body: body.toString(),
headers
});
}
async function getJSONFromResponse(response) {
const text = await response.text();
try {
return JSON.parse(text);
} catch (e7) {
if (text.match(/<!DOCTYPE html>/)) {
logger.error(
"The body of the response was HTML rather than JSON. Check the debug logs to see the full body of the response."
);
if (text.match(/challenge-platform/)) {
logger.error(
`It looks like you might have hit a bot challenge page. This may be transient but if not, please contact Cloudflare to find out what can be done. When you contact Cloudflare, please provide your Ray ID: ${response.headers.get("cf-ray")}`
);
}
}
logger.debug("Full body of response\n\n", text);
throw new Error(
`Invalid JSON in response: status: ${response.status} ${response.statusText}`,
{ cause: e7 }
);
}
}
var import_node_assert2, import_node_crypto2, import_node_fs5, import_node_http, import_node_path10, import_node_url4, import_node_util2, import_toml4, import_undici2, USER_AUTH_CONFIG_PATH, DefaultScopes, DefaultScopeKeys, LocalState, ErrorOAuth2, ErrorUnknown, ErrorNoAuthCode, ErrorInvalidReturnedStateParam, ErrorInvalidJson, ErrorInvalidScope, ErrorInvalidRequest, ErrorInvalidToken, ErrorAuthenticationGrant, ErrorUnauthorizedClient, ErrorAccessDenied, ErrorUnsupportedResponseType, ErrorServerError, ErrorTemporarilyUnavailable, ErrorAccessTokenResponse, ErrorInvalidClient, ErrorInvalidGrant, ErrorUnsupportedGrantType, RawErrorToErrorClassMap, RECOMMENDED_CODE_VERIFIER_LENGTH, RECOMMENDED_STATE_LENGTH, PKCE_CHARSET;
var init_user = __esm({
"src/user/user.ts"() {
init_import_meta_url();
import_node_assert2 = __toESM(require("assert"));
import_node_crypto2 = require("crypto");
import_node_fs5 = require("fs");
import_node_http = __toESM(require("http"));
import_node_path10 = __toESM(require("path"));
import_node_url4 = __toESM(require("url"));
import_node_util2 = require("util");
import_toml4 = __toESM(require_toml());
init_esm2();
import_undici2 = __toESM(require_undici());
init_config2();
init_config_cache();
init_dialogs();
init_misc_variables();
init_errors();
init_global_wrangler_config_path();
init_is_interactive();
init_logger();
init_open_in_browser();
init_parse();
init_access();
init_auth_variables();
init_choose_account();
init_generate_auth_url();
init_generate_random_state();
__name(getAuthFromEnv, "getAuthFromEnv");
USER_AUTH_CONFIG_PATH = "config";
DefaultScopes = {
"account:read": "See your account info such as account details, analytics, and memberships.",
"user:read": "See your user info such as name, email address, and account memberships.",
"workers:write": "See and change Cloudflare Workers data such as zones, KV storage, namespaces, scripts, and routes.",
"workers_kv:write": "See and change Cloudflare Workers KV Storage data such as keys and namespaces.",
"workers_routes:write": "See and change Cloudflare Workers data such as filters and routes.",
"workers_scripts:write": "See and change Cloudflare Workers scripts, durable objects, subdomains, triggers, and tail data.",
"workers_tail:read": "See Cloudflare Workers tail and script data.",
"d1:write": "See and change D1 Databases.",
"pages:write": "See and change Cloudflare Pages projects, settings and deployments.",
"zone:read": "Grants read level access to account zone.",
"ssl_certs:write": "See and manage mTLS certificates for your account",
"ai:write": "See and change Workers AI catalog and assets",
"queues:write": "See and change Cloudflare Queues settings and data",
"pipelines:write": "See and change Cloudflare Pipelines configurations and data",
"secrets_store:write": "See and change secrets + stores within the Secrets Store",
"containers:write": "Manage Workers Containers",
"cloudchamber:write": "Manage Cloudchamber"
};
DefaultScopeKeys = Object.keys(DefaultScopes);
__name(validateScopeKeys, "validateScopeKeys");
__name(getCallbackUrl, "getCallbackUrl");
LocalState = {
...getAuthTokens()
};
__name(getAuthTokens, "getAuthTokens");
__name(reinitialiseAuthTokens, "reinitialiseAuthTokens");
__name(getAPIToken, "getAPIToken");
ErrorOAuth2 = class extends UserError {
static {
__name(this, "ErrorOAuth2");
}
toString() {
return "ErrorOAuth2";
}
};
ErrorUnknown = class extends Error {
static {
__name(this, "ErrorUnknown");
}
toString() {
return "ErrorUnknown";
}
};
ErrorNoAuthCode = class extends ErrorOAuth2 {
static {
__name(this, "ErrorNoAuthCode");
}
toString() {
return "ErrorNoAuthCode";
}
};
ErrorInvalidReturnedStateParam = class extends ErrorOAuth2 {
static {
__name(this, "ErrorInvalidReturnedStateParam");
}
toString() {
return "ErrorInvalidReturnedStateParam";
}
};
ErrorInvalidJson = class extends ErrorOAuth2 {
static {
__name(this, "ErrorInvalidJson");
}
toString() {
return "ErrorInvalidJson";
}
};
ErrorInvalidScope = class extends ErrorOAuth2 {
static {
__name(this, "ErrorInvalidScope");
}
toString() {
return "ErrorInvalidScope";
}
};
ErrorInvalidRequest = class extends ErrorOAuth2 {
static {
__name(this, "ErrorInvalidRequest");
}
toString() {
return "ErrorInvalidRequest";
}
};
ErrorInvalidToken = class extends ErrorOAuth2 {
static {
__name(this, "ErrorInvalidToken");
}
toString() {
return "ErrorInvalidToken";
}
};
ErrorAuthenticationGrant = class extends ErrorOAuth2 {
static {
__name(this, "ErrorAuthenticationGrant");
}
toString() {
return "ErrorAuthenticationGrant";
}
};
ErrorUnauthorizedClient = class extends ErrorAuthenticationGrant {
static {
__name(this, "ErrorUnauthorizedClient");
}
toString() {
return "ErrorUnauthorizedClient";
}
};
ErrorAccessDenied = class extends ErrorAuthenticationGrant {
static {
__name(this, "ErrorAccessDenied");
}
toString() {
return "ErrorAccessDenied";
}
};
ErrorUnsupportedResponseType = class extends ErrorAuthenticationGrant {
static {
__name(this, "ErrorUnsupportedResponseType");
}
toString() {
return "ErrorUnsupportedResponseType";
}
};
ErrorServerError = class extends ErrorAuthenticationGrant {
static {
__name(this, "ErrorServerError");
}
toString() {
return "ErrorServerError";
}
};
ErrorTemporarilyUnavailable = class extends ErrorAuthenticationGrant {
static {
__name(this, "ErrorTemporarilyUnavailable");
}
toString() {
return "ErrorTemporarilyUnavailable";
}
};
ErrorAccessTokenResponse = class extends ErrorOAuth2 {
static {
__name(this, "ErrorAccessTokenResponse");
}
toString() {
return "ErrorAccessTokenResponse";
}
};
ErrorInvalidClient = class extends ErrorAccessTokenResponse {
static {
__name(this, "ErrorInvalidClient");
}
toString() {
return "ErrorInvalidClient";
}
};
ErrorInvalidGrant = class extends ErrorAccessTokenResponse {
static {
__name(this, "ErrorInvalidGrant");
}
toString() {
return "ErrorInvalidGrant";
}
};
ErrorUnsupportedGrantType = class extends ErrorAccessTokenResponse {
static {
__name(this, "ErrorUnsupportedGrantType");
}
toString() {
return "ErrorUnsupportedGrantType";
}
};
RawErrorToErrorClassMap = {
invalid_request: ErrorInvalidRequest,
invalid_grant: ErrorInvalidGrant,
unauthorized_client: ErrorUnauthorizedClient,
access_denied: ErrorAccessDenied,
unsupported_response_type: ErrorUnsupportedResponseType,
invalid_scope: ErrorInvalidScope,
server_error: ErrorServerError,
temporarily_unavailable: ErrorTemporarilyUnavailable,
invalid_client: ErrorInvalidClient,
unsupported_grant_type: ErrorUnsupportedGrantType,
invalid_json: ErrorInvalidJson,
invalid_token: ErrorInvalidToken
};
__name(toErrorClass, "toErrorClass");
RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
RECOMMENDED_STATE_LENGTH = 32;
PKCE_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
__name(isReturningFromAuthServer, "isReturningFromAuthServer");
__name(getAuthURL, "getAuthURL");
__name(exchangeRefreshTokenForAccessToken, "exchangeRefreshTokenForAccessToken");
__name(exchangeAuthCodeForAccessToken, "exchangeAuthCodeForAccessToken");
__name(base64urlEncode, "base64urlEncode");
__name(generatePKCECodes, "generatePKCECodes");
__name(getAuthConfigFilePath, "getAuthConfigFilePath");
__name(writeAuthConfigFile, "writeAuthConfigFile");
__name(readAuthConfigFile, "readAuthConfigFile");
__name(loginOrRefreshIfRequired, "loginOrRefreshIfRequired");
__name(getOauthToken, "getOauthToken");
__name(login, "login");
__name(isAccessTokenExpired, "isAccessTokenExpired");
__name(refreshToken, "refreshToken");
__name(logout, "logout");
__name(listScopes, "listScopes");
__name(getAccountId, "getAccountId");
__name(requireAuth, "requireAuth");
__name(requireApiToken, "requireApiToken");
__name(saveAccountToCache, "saveAccountToCache");
__name(getAccountFromCache, "getAccountFromCache");
__name(getScopes, "getScopes");
__name(printScopes, "printScopes");
__name(fetchAuthToken, "fetchAuthToken");
__name(getJSONFromResponse, "getJSONFromResponse");
}
});
// src/user/index.ts
var init_user2 = __esm({
"src/user/index.ts"() {
init_import_meta_url();
init_user();
init_choose_account();
}
});
// src/cfetch/internal.ts
async function performApiFetch(complianceConfig, resource, init3 = {}, queryParams, abortSignal, apiToken) {
const method = init3.method ?? "GET";
(0, import_node_assert3.default)(
resource.startsWith("/"),
`CF API fetch - resource path must start with a "/" but got "${resource}"`
);
await requireLoggedIn(complianceConfig);
apiToken ??= requireApiToken();
const headers = cloneHeaders(new import_undici3.Headers(init3.headers));
addAuthorizationHeaderIfUnspecified(headers, apiToken);
addUserAgent(headers);
const queryString = queryParams ? `?${queryParams.toString()}` : "";
logger.debug(
`-- START CF API REQUEST: ${method} ${getCloudflareApiBaseUrl(complianceConfig)}${resource}`
);
logger.debugWithSanitization("QUERY STRING:", queryString);
logHeaders(headers);
logger.debugWithSanitization("INIT:", JSON.stringify({ ...init3 }, null, 2));
if (init3.body instanceof import_undici3.FormData) {
logger.debugWithSanitization(
"BODY:",
await new import_undici3.Response(init3.body).text(),
null,
2
);
}
logger.debug("-- END CF API REQUEST");
return await (0, import_undici3.fetch)(
`${getCloudflareApiBaseUrl(complianceConfig)}${resource}${queryString}`,
{
method,
...init3,
headers,
signal: abortSignal
}
);
}
function logHeaders(headers) {
headers = cloneHeaders(headers);
headers.delete("Authorization");
logger.debugWithSanitization(
"HEADERS:",
JSON.stringify(Object.fromEntries(headers), null, 2)
);
}
async function fetchInternal(complianceConfig, resource, init3 = {}, queryParams, abortSignal, apiToken) {
const method = init3.method ?? "GET";
const response = await performApiFetch(
complianceConfig,
resource,
init3,
queryParams,
abortSignal,
apiToken
);
const jsonText = await response.text();
logger.debug(
"-- START CF API RESPONSE:",
response.statusText,
response.status
);
logHeaders(response.headers);
logger.debugWithSanitization("RESPONSE:", jsonText);
logger.debug("-- END CF API RESPONSE");
if (!jsonText && (response.status === 204 || response.status === 205)) {
const emptyBody = `{"result": {}, "success": true, "errors": [], "messages": []}`;
return parseJSON(emptyBody);
}
try {
return parseJSON(jsonText);
} catch {
throw new APIError({
text: "Received a malformed response from the API",
notes: [
{
text: truncate(jsonText, 100)
},
{
text: `${method} ${resource} -> ${response.status} ${response.statusText}`
}
],
status: response.status
});
}
}
function truncate(text, maxLength) {
const { length } = text;
if (length <= maxLength) {
return text;
}
return `${text.substring(0, maxLength)}... (length = ${length})`;
}
function cloneHeaders(headers) {
return new import_undici3.Headers(headers);
}
async function requireLoggedIn(complianceConfig) {
const loggedIn = await loginOrRefreshIfRequired(complianceConfig);
if (!loggedIn) {
throw new UserError("Not logged in.");
}
}
function addAuthorizationHeaderIfUnspecified(headers, auth) {
if (!headers.has("Authorization")) {
if ("apiToken" in auth) {
headers.set("Authorization", `Bearer ${auth.apiToken}`);
} else {
headers.set("X-Auth-Key", auth.authKey);
headers.set("X-Auth-Email", auth.authEmail);
}
}
}
function addUserAgent(headers) {
headers.set("User-Agent", `wrangler/${version}`);
}
async function fetchKVGetValue(complianceConfig, accountId, namespaceId, key) {
await requireLoggedIn(complianceConfig);
const auth = requireApiToken();
const headers = new import_undici3.Headers();
addAuthorizationHeaderIfUnspecified(headers, auth);
const resource = `${getCloudflareApiBaseUrl(complianceConfig)}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
const response = await (0, import_undici3.fetch)(resource, {
method: "GET",
headers
});
if (response.ok) {
return await response.arrayBuffer();
} else {
throw new Error(
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
);
}
}
async function fetchR2Objects(complianceConfig, resource, bodyInit = {}) {
await requireLoggedIn(complianceConfig);
const auth = requireApiToken();
const headers = cloneHeaders(bodyInit.headers);
addAuthorizationHeaderIfUnspecified(headers, auth);
addUserAgent(headers);
const response = await (0, import_undici3.fetch)(
`${getCloudflareApiBaseUrl(complianceConfig)}${resource}`,
{
...bodyInit,
headers
}
);
if (response.ok && response.body) {
return response;
} else if (response.status === 404) {
return null;
} else {
throw new Error(
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
);
}
}
async function fetchWorkerDefinitionFromDash(complianceConfig, resource, bodyInit = {}) {
await requireLoggedIn(complianceConfig);
const auth = requireApiToken();
const headers = cloneHeaders(bodyInit.headers);
addAuthorizationHeaderIfUnspecified(headers, auth);
addUserAgent(headers);
let response = await (0, import_undici3.fetch)(
`${getCloudflareApiBaseUrl(complianceConfig)}${resource}`,
{
...bodyInit,
headers
}
);
if (!response.ok || !response.body) {
logger.error(response.ok, response.body);
throw new Error(
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
);
}
const usesModules = response.headers.get("content-type")?.startsWith("multipart");
if (usesModules) {
if (!response.formData) {
response = new import_undici3.Response(await response.text(), response);
}
const form = await response.formData();
const files = Array.from(form.entries()).map(
([filename, contents]) => contents instanceof File ? contents : new File([contents], filename)
);
return {
entrypoint: response.headers.get("cf-entrypoint") ?? "src/index.js",
modules: files
};
} else {
const contents = await response.text();
const file = new File([contents], "index.js", { type: "text" });
return {
entrypoint: "index.js",
modules: [file]
};
}
}
var import_node_assert3, import_undici3;
var init_internal = __esm({
"src/cfetch/internal.ts"() {
init_import_meta_url();
import_node_assert3 = __toESM(require("assert"));
import_undici3 = __toESM(require_undici());
init_package();
init_misc_variables();
init_errors();
init_logger();
init_parse();
init_user2();
__name(performApiFetch, "performApiFetch");
__name(logHeaders, "logHeaders");
__name(fetchInternal, "fetchInternal");
__name(truncate, "truncate");
__name(cloneHeaders, "cloneHeaders");
__name(requireLoggedIn, "requireLoggedIn");
__name(addAuthorizationHeaderIfUnspecified, "addAuthorizationHeaderIfUnspecified");
__name(addUserAgent, "addUserAgent");
__name(fetchKVGetValue, "fetchKVGetValue");
__name(fetchR2Objects, "fetchR2Objects");
__name(fetchWorkerDefinitionFromDash, "fetchWorkerDefinitionFromDash");
}
});
// src/cfetch/index.ts
async function fetchResult(complianceConfig, resource, init3 = {}, queryParams, abortSignal, apiToken) {
const json = await fetchInternal(
complianceConfig,
resource,
init3,
queryParams,
abortSignal,
apiToken
);
if (json.success) {
return json.result;
} else {
throwFetchError(resource, json);
}
}
async function fetchGraphqlResult(complianceConfig, init3 = {}, abortSignal) {
const json = await fetchInternal(
complianceConfig,
"/graphql",
{ ...init3, method: "POST" },
//Cloudflare API v4 doesn't allow GETs to /graphql
void 0,
abortSignal
);
if (json) {
return json;
} else {
throw new Error("A request to the Cloudflare API (/graphql) failed.");
}
}
async function fetchListResult(complianceConfig, resource, init3 = {}, queryParams) {
const results = [];
let getMoreResults = true;
let cursor;
while (getMoreResults) {
if (cursor) {
queryParams = new import_node_url5.URLSearchParams(queryParams);
queryParams.set("cursor", cursor);
}
const json = await fetchInternal(
complianceConfig,
resource,
init3,
queryParams
);
if (json.success) {
results.push(...json.result);
if (hasCursor(json.result_info)) {
cursor = json.result_info?.cursor;
} else {
getMoreResults = false;
}
} else {
throwFetchError(resource, json);
}
}
return results;
}
async function fetchPagedListResult(complianceConfig, resource, init3 = {}, queryParams) {
const results = [];
let getMoreResults = true;
let page = 1;
while (getMoreResults) {
queryParams = new import_node_url5.URLSearchParams(queryParams);
queryParams.set("page", String(page));
const json = await fetchInternal(
complianceConfig,
resource,
init3,
queryParams
);
if (json.success) {
results.push(...json.result);
if (hasMorePages(json.result_info)) {
page = page + 1;
} else {
getMoreResults = false;
}
} else {
throwFetchError(resource, json);
}
}
return results;
}
function hasMorePages(result_info) {
const page = result_info?.page;
const per_page = result_info?.per_page;
const total = result_info?.total_count;
return page !== void 0 && per_page !== void 0 && total !== void 0 && page * per_page < total;
}
function throwFetchError(resource, response) {
if (typeof vitest !== "undefined" && !("errors" in response)) {
throw response;
}
for (const error3 of response.errors) {
maybeThrowFriendlyError(error3);
}
const error2 = new APIError({
text: `A request to the Cloudflare API (${resource}) failed.`,
notes: [
...response.errors.map((err) => ({ text: renderError(err) })),
...response.messages?.map((text) => ({ text })) ?? []
]
});
const code = response.errors[0]?.code;
if (code) {
error2.code = code;
}
error2.accountTag = extractAccountTag(resource);
throw error2;
}
function extractAccountTag(resource) {
const re = new RegExp("/accounts/([a-zA-Z0-9]+)/?");
const matches = re.exec(resource);
return matches?.[1];
}
function hasCursor(result_info) {
const cursor = result_info?.cursor;
return cursor !== void 0 && cursor !== null && cursor !== "";
}
function renderError(err, level = 0) {
const indent = " ".repeat(level);
const chainedMessages = err.error_chain?.map(
(chainedError) => `
${indent}- ${renderError(chainedError, level + 1)}`
).join("\n") ?? "";
return (err.code ? `${err.message} [code: ${err.code}]` : err.message) + (err.documentation_url ? `
${indent}To learn more about this error, visit: ${err.documentation_url}` : "") + chainedMessages;
}
var import_node_url5;
var init_cfetch = __esm({
"src/cfetch/index.ts"() {
init_import_meta_url();
import_node_url5 = require("url");
init_parse();
init_errors2();
init_internal();
init_internal();
__name(fetchResult, "fetchResult");
__name(fetchGraphqlResult, "fetchGraphqlResult");
__name(fetchListResult, "fetchListResult");
__name(fetchPagedListResult, "fetchPagedListResult");
__name(hasMorePages, "hasMorePages");
__name(throwFetchError, "throwFetchError");
__name(extractAccountTag, "extractAccountTag");
__name(hasCursor, "hasCursor");
__name(renderError, "renderError");
}
});
// src/ai/fetcher.ts
function getAIFetcher(complianceConfig) {
return async function(request4) {
const accountId = await getAccountId(complianceConfig);
const reqHeaders = new import_miniflare4.Headers(request4.headers);
reqHeaders.delete("Host");
reqHeaders.delete("Content-Length");
reqHeaders.set("X-Forwarded", request4.url);
const res = await performApiFetch(
complianceConfig,
`/accounts/${accountId}/ai/run/proxy`,
{
method: request4.method,
headers: Object.fromEntries(reqHeaders.entries()),
body: request4.body,
duplex: "half"
}
);
const respHeaders = new import_miniflare4.Headers(res.headers);
respHeaders.delete("Host");
respHeaders.delete("Content-Length");
return new import_miniflare4.Response(res.body, { status: res.status, headers: respHeaders });
};
}
var import_miniflare4, EXTERNAL_AI_WORKER_NAME, EXTERNAL_AI_WORKER_SCRIPT;
var init_fetcher = __esm({
"src/ai/fetcher.ts"() {
init_import_meta_url();
import_miniflare4 = require("miniflare");
init_cfetch();
init_user2();
EXTERNAL_AI_WORKER_NAME = "__WRANGLER_EXTERNAL_AI_WORKER";
EXTERNAL_AI_WORKER_SCRIPT = `
import { Ai } from 'cloudflare-internal:ai-api'
export default function (env) {
return new Ai(env.FETCHER);
}
`;
__name(getAIFetcher, "getAIFetcher");
}
});
// ../../node_modules/.pnpm/glob-to-regexp@0.4.1/node_modules/glob-to-regexp/index.js
var require_glob_to_regexp = __commonJS({
"../../node_modules/.pnpm/glob-to-regexp@0.4.1/node_modules/glob-to-regexp/index.js"(exports2, module3) {
init_import_meta_url();
module3.exports = function(glob, opts) {
if (typeof glob !== "string") {
throw new TypeError("Expected a string");
}
var str = String(glob);
var reStr = "";
var extended = opts ? !!opts.extended : false;
var globstar = opts ? !!opts.globstar : false;
var inGroup = false;
var flags2 = opts && typeof opts.flags === "string" ? opts.flags : "";
var c6;
for (var i5 = 0, len = str.length; i5 < len; i5++) {
c6 = str[i5];
switch (c6) {
case "/":
case "$":
case "^":
case "+":
case ".":
case "(":
case ")":
case "=":
case "!":
case "|":
reStr += "\\" + c6;
break;
case "?":
if (extended) {
reStr += ".";
break;
}
case "[":
case "]":
if (extended) {
reStr += c6;
break;
}
case "{":
if (extended) {
inGroup = true;
reStr += "(";
break;
}
case "}":
if (extended) {
inGroup = false;
reStr += ")";
break;
}
case ",":
if (inGroup) {
reStr += "|";
break;
}
reStr += "\\" + c6;
break;
case "*":
var prevChar = str[i5 - 1];
var starCount = 1;
while (str[i5 + 1] === "*") {
starCount++;
i5++;
}
var nextChar = str[i5 + 1];
if (!globstar) {
reStr += ".*";
} else {
var isGlobstar = starCount > 1 && (prevChar === "/" || prevChar === void 0) && (nextChar === "/" || nextChar === void 0);
if (isGlobstar) {
reStr += "((?:[^/]*(?:/|$))*)";
i5++;
} else {
reStr += "([^/]*)";
}
}
break;
default:
reStr += c6;
}
}
if (!flags2 || !~flags2.indexOf("g")) {
reStr = "^" + reStr + "$";
}
return new RegExp(reStr, flags2);
};
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/homedir.js
var require_homedir = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/homedir.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var os12 = require("os");
module3.exports = os12.homedir || /* @__PURE__ */ __name(function homedir3() {
var home = process.env.HOME;
var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
if (process.platform === "win32") {
return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
}
if (process.platform === "darwin") {
return home || (user ? "/Users/" + user : null);
}
if (process.platform === "linux") {
return home || (process.getuid() === 0 ? "/root" : user ? "/home/" + user : null);
}
return home || null;
}, "homedir");
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/caller.js
var require_caller = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/caller.js"(exports2, module3) {
init_import_meta_url();
module3.exports = function() {
var origPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = function(_4, stack2) {
return stack2;
};
var stack = new Error().stack;
Error.prepareStackTrace = origPrepareStackTrace;
return stack[2].getFileName();
};
}
});
// ../../node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js
var require_path_parse = __commonJS({
"../../node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var isWindows4 = process.platform === "win32";
var splitWindowsRe = /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
var win32 = {};
function win32SplitPath(filename) {
return splitWindowsRe.exec(filename).slice(1);
}
__name(win32SplitPath, "win32SplitPath");
win32.parse = function(pathString) {
if (typeof pathString !== "string") {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = win32SplitPath(pathString);
if (!allParts || allParts.length !== 5) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[1],
dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
var splitPathRe = /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
var posix2 = {};
function posixSplitPath(filename) {
return splitPathRe.exec(filename).slice(1);
}
__name(posixSplitPath, "posixSplitPath");
posix2.parse = function(pathString) {
if (typeof pathString !== "string") {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = posixSplitPath(pathString);
if (!allParts || allParts.length !== 5) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[1],
dir: allParts[0].slice(0, -1),
base: allParts[2],
ext: allParts[4],
name: allParts[3]
};
};
if (isWindows4)
module3.exports = win32.parse;
else
module3.exports = posix2.parse;
module3.exports.posix = posix2.parse;
module3.exports.win32 = win32.parse;
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/node-modules-paths.js
var require_node_modules_paths = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/node-modules-paths.js"(exports2, module3) {
init_import_meta_url();
var path72 = require("path");
var parse7 = path72.parse || require_path_parse();
var getNodeModulesDirs = /* @__PURE__ */ __name(function getNodeModulesDirs2(absoluteStart, modules) {
var prefix = "/";
if (/^([A-Za-z]:)/.test(absoluteStart)) {
prefix = "";
} else if (/^\\\\/.test(absoluteStart)) {
prefix = "\\\\";
}
var paths = [absoluteStart];
var parsed = parse7(absoluteStart);
while (parsed.dir !== paths[paths.length - 1]) {
paths.push(parsed.dir);
parsed = parse7(parsed.dir);
}
return paths.reduce(function(dirs, aPath) {
return dirs.concat(modules.map(function(moduleDir) {
return path72.resolve(prefix, aPath, moduleDir);
}));
}, []);
}, "getNodeModulesDirs");
module3.exports = /* @__PURE__ */ __name(function nodeModulesPaths(start, opts, request4) {
var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"];
if (opts && typeof opts.paths === "function") {
return opts.paths(
request4,
start,
function() {
return getNodeModulesDirs(start, modules);
},
opts
);
}
var dirs = getNodeModulesDirs(start, modules);
return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
}, "nodeModulesPaths");
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/normalize-options.js
var require_normalize_options = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/normalize-options.js"(exports2, module3) {
init_import_meta_url();
module3.exports = function(x6, opts) {
return opts || {};
};
}
});
// ../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js
var require_implementation = __commonJS({
"../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = "[object Function]";
var concatty = /* @__PURE__ */ __name(function concatty2(a5, b6) {
var arr = [];
for (var i5 = 0; i5 < a5.length; i5 += 1) {
arr[i5] = a5[i5];
}
for (var j6 = 0; j6 < b6.length; j6 += 1) {
arr[j6 + a5.length] = b6[j6];
}
return arr;
}, "concatty");
var slicy = /* @__PURE__ */ __name(function slicy2(arrLike, offset) {
var arr = [];
for (var i5 = offset || 0, j6 = 0; i5 < arrLike.length; i5 += 1, j6 += 1) {
arr[j6] = arrLike[i5];
}
return arr;
}, "slicy");
var joiny = /* @__PURE__ */ __name(function(arr, joiner) {
var str = "";
for (var i5 = 0; i5 < arr.length; i5 += 1) {
str += arr[i5];
if (i5 + 1 < arr.length) {
str += joiner;
}
}
return str;
}, "joiny");
module3.exports = /* @__PURE__ */ __name(function bind(that) {
var target = this;
if (typeof target !== "function" || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = /* @__PURE__ */ __name(function() {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
}, "binder");
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i5 = 0; i5 < boundLength; i5++) {
boundArgs[i5] = "$" + i5;
}
bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
if (target.prototype) {
var Empty = /* @__PURE__ */ __name(function Empty2() {
}, "Empty");
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
}, "bind");
}
});
// ../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js
var require_function_bind = __commonJS({
"../../node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var implementation = require_implementation();
module3.exports = Function.prototype.bind || implementation;
}
});
// ../../node_modules/.pnpm/has@1.0.3/node_modules/has/src/index.js
var require_src2 = __commonJS({
"../../node_modules/.pnpm/has@1.0.3/node_modules/has/src/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var bind = require_function_bind();
module3.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
}
});
// ../../node_modules/.pnpm/is-core-module@2.13.0/node_modules/is-core-module/core.json
var require_core = __commonJS({
"../../node_modules/.pnpm/is-core-module@2.13.0/node_modules/is-core-module/core.json"(exports2, module3) {
module3.exports = {
assert: true,
"node:assert": [">= 14.18 && < 15", ">= 16"],
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
async_hooks: ">= 8",
"node:async_hooks": [">= 14.18 && < 15", ">= 16"],
buffer_ieee754: ">= 0.5 && < 0.9.7",
buffer: true,
"node:buffer": [">= 14.18 && < 15", ">= 16"],
child_process: true,
"node:child_process": [">= 14.18 && < 15", ">= 16"],
cluster: ">= 0.5",
"node:cluster": [">= 14.18 && < 15", ">= 16"],
console: true,
"node:console": [">= 14.18 && < 15", ">= 16"],
constants: true,
"node:constants": [">= 14.18 && < 15", ">= 16"],
crypto: true,
"node:crypto": [">= 14.18 && < 15", ">= 16"],
_debug_agent: ">= 1 && < 8",
_debugger: "< 8",
dgram: true,
"node:dgram": [">= 14.18 && < 15", ">= 16"],
diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
dns: true,
"node:dns": [">= 14.18 && < 15", ">= 16"],
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
domain: ">= 0.7.12",
"node:domain": [">= 14.18 && < 15", ">= 16"],
events: true,
"node:events": [">= 14.18 && < 15", ">= 16"],
freelist: "< 6",
fs: true,
"node:fs": [">= 14.18 && < 15", ">= 16"],
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": [">= 14.18 && < 15", ">= 16"],
_http_agent: ">= 0.11.1",
"node:_http_agent": [">= 14.18 && < 15", ">= 16"],
_http_client: ">= 0.11.1",
"node:_http_client": [">= 14.18 && < 15", ">= 16"],
_http_common: ">= 0.11.1",
"node:_http_common": [">= 14.18 && < 15", ">= 16"],
_http_incoming: ">= 0.11.1",
"node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
_http_outgoing: ">= 0.11.1",
"node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
_http_server: ">= 0.11.1",
"node:_http_server": [">= 14.18 && < 15", ">= 16"],
http: true,
"node:http": [">= 14.18 && < 15", ">= 16"],
http2: ">= 8.8",
"node:http2": [">= 14.18 && < 15", ">= 16"],
https: true,
"node:https": [">= 14.18 && < 15", ">= 16"],
inspector: ">= 8",
"node:inspector": [">= 14.18 && < 15", ">= 16"],
"inspector/promises": [">= 19"],
"node:inspector/promises": [">= 19"],
_linklist: "< 8",
module: true,
"node:module": [">= 14.18 && < 15", ">= 16"],
net: true,
"node:net": [">= 14.18 && < 15", ">= 16"],
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
os: true,
"node:os": [">= 14.18 && < 15", ">= 16"],
path: true,
"node:path": [">= 14.18 && < 15", ">= 16"],
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
perf_hooks: ">= 8.5",
"node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
process: ">= 1",
"node:process": [">= 14.18 && < 15", ">= 16"],
punycode: ">= 0.5",
"node:punycode": [">= 14.18 && < 15", ">= 16"],
querystring: true,
"node:querystring": [">= 14.18 && < 15", ">= 16"],
readline: true,
"node:readline": [">= 14.18 && < 15", ">= 16"],
"readline/promises": ">= 17",
"node:readline/promises": ">= 17",
repl: true,
"node:repl": [">= 14.18 && < 15", ">= 16"],
smalloc: ">= 0.11.5 && < 3",
_stream_duplex: ">= 0.9.4",
"node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
_stream_transform: ">= 0.9.4",
"node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
_stream_wrap: ">= 1.4.1",
"node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
_stream_passthrough: ">= 0.9.4",
"node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
_stream_readable: ">= 0.9.4",
"node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
_stream_writable: ">= 0.9.4",
"node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
stream: true,
"node:stream": [">= 14.18 && < 15", ">= 16"],
"stream/consumers": ">= 16.7",
"node:stream/consumers": ">= 16.7",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"stream/web": ">= 16.5",
"node:stream/web": ">= 16.5",
string_decoder: true,
"node:string_decoder": [">= 14.18 && < 15", ">= 16"],
sys: [">= 0.4 && < 0.7", ">= 0.8"],
"node:sys": [">= 14.18 && < 15", ">= 16"],
"test/reporters": ">= 19.9 && < 20.2",
"node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
"node:test": [">= 16.17 && < 17", ">= 18"],
timers: true,
"node:timers": [">= 14.18 && < 15", ">= 16"],
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
_tls_common: ">= 0.11.13",
"node:_tls_common": [">= 14.18 && < 15", ">= 16"],
_tls_legacy: ">= 0.11.3 && < 10",
_tls_wrap: ">= 0.11.3",
"node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
tls: true,
"node:tls": [">= 14.18 && < 15", ">= 16"],
trace_events: ">= 10",
"node:trace_events": [">= 14.18 && < 15", ">= 16"],
tty: true,
"node:tty": [">= 14.18 && < 15", ">= 16"],
url: true,
"node:url": [">= 14.18 && < 15", ">= 16"],
util: true,
"node:util": [">= 14.18 && < 15", ">= 16"],
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
v8: ">= 1",
"node:v8": [">= 14.18 && < 15", ">= 16"],
vm: true,
"node:vm": [">= 14.18 && < 15", ">= 16"],
wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
"node:wasi": [">= 18.17 && < 19", ">= 20"],
worker_threads: ">= 11.7",
"node:worker_threads": [">= 14.18 && < 15", ">= 16"],
zlib: ">= 0.5",
"node:zlib": [">= 14.18 && < 15", ">= 16"]
};
}
});
// ../../node_modules/.pnpm/is-core-module@2.13.0/node_modules/is-core-module/index.js
var require_is_core_module = __commonJS({
"../../node_modules/.pnpm/is-core-module@2.13.0/node_modules/is-core-module/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var has = require_src2();
function specifierIncluded(current, specifier) {
var nodeParts = current.split(".");
var parts = specifier.split(" ");
var op = parts.length > 1 ? parts[0] : "=";
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split(".");
for (var i5 = 0; i5 < 3; ++i5) {
var cur = parseInt(nodeParts[i5] || 0, 10);
var ver = parseInt(versionParts[i5] || 0, 10);
if (cur === ver) {
continue;
}
if (op === "<") {
return cur < ver;
}
if (op === ">=") {
return cur >= ver;
}
return false;
}
return op === ">=";
}
__name(specifierIncluded, "specifierIncluded");
function matchesRange(current, range) {
var specifiers = range.split(/ ?&& ?/);
if (specifiers.length === 0) {
return false;
}
for (var i5 = 0; i5 < specifiers.length; ++i5) {
if (!specifierIncluded(current, specifiers[i5])) {
return false;
}
}
return true;
}
__name(matchesRange, "matchesRange");
function versionIncluded(nodeVersion2, specifierValue) {
if (typeof specifierValue === "boolean") {
return specifierValue;
}
var current = typeof nodeVersion2 === "undefined" ? process.versions && process.versions.node : nodeVersion2;
if (typeof current !== "string") {
throw new TypeError(typeof nodeVersion2 === "undefined" ? "Unable to determine current node version" : "If provided, a valid node version is required");
}
if (specifierValue && typeof specifierValue === "object") {
for (var i5 = 0; i5 < specifierValue.length; ++i5) {
if (matchesRange(current, specifierValue[i5])) {
return true;
}
}
return false;
}
return matchesRange(current, specifierValue);
}
__name(versionIncluded, "versionIncluded");
var data = require_core();
module3.exports = /* @__PURE__ */ __name(function isCore(x6, nodeVersion2) {
return has(data, x6) && versionIncluded(nodeVersion2, data[x6]);
}, "isCore");
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/async.js
var require_async = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/async.js"(exports2, module3) {
init_import_meta_url();
var fs24 = require("fs");
var getHomedir = require_homedir();
var path72 = require("path");
var caller = require_caller();
var nodeModulesPaths = require_node_modules_paths();
var normalizeOptions = require_normalize_options();
var isCore = require_is_core_module();
var realpathFS = process.platform !== "win32" && fs24.realpath && typeof fs24.realpath.native === "function" ? fs24.realpath.native : fs24.realpath;
var homedir3 = getHomedir();
var defaultPaths = /* @__PURE__ */ __name(function() {
return [
path72.join(homedir3, ".node_modules"),
path72.join(homedir3, ".node_libraries")
];
}, "defaultPaths");
var defaultIsFile = /* @__PURE__ */ __name(function isFile(file, cb2) {
fs24.stat(file, function(err, stat8) {
if (!err) {
return cb2(null, stat8.isFile() || stat8.isFIFO());
}
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb2(null, false);
return cb2(err);
});
}, "isFile");
var defaultIsDir = /* @__PURE__ */ __name(function isDirectory2(dir, cb2) {
fs24.stat(dir, function(err, stat8) {
if (!err) {
return cb2(null, stat8.isDirectory());
}
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb2(null, false);
return cb2(err);
});
}, "isDirectory");
var defaultRealpath = /* @__PURE__ */ __name(function realpath2(x6, cb2) {
realpathFS(x6, function(realpathErr, realPath) {
if (realpathErr && realpathErr.code !== "ENOENT") cb2(realpathErr);
else cb2(null, realpathErr ? x6 : realPath);
});
}, "realpath");
var maybeRealpath = /* @__PURE__ */ __name(function maybeRealpath2(realpath2, x6, opts, cb2) {
if (opts && opts.preserveSymlinks === false) {
realpath2(x6, cb2);
} else {
cb2(null, x6);
}
}, "maybeRealpath");
var defaultReadPackage = /* @__PURE__ */ __name(function defaultReadPackage2(readFile17, pkgfile, cb2) {
readFile17(pkgfile, function(readFileErr, body) {
if (readFileErr) cb2(readFileErr);
else {
try {
var pkg = JSON.parse(body);
cb2(null, pkg);
} catch (jsonErr) {
cb2(null);
}
}
});
}, "defaultReadPackage");
var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x6, start, opts) {
var dirs = nodeModulesPaths(start, opts, x6);
for (var i5 = 0; i5 < dirs.length; i5++) {
dirs[i5] = path72.join(dirs[i5], x6);
}
return dirs;
}, "getPackageCandidates");
module3.exports = /* @__PURE__ */ __name(function resolve25(x6, options, callback) {
var cb2 = callback;
var opts = options;
if (typeof options === "function") {
cb2 = opts;
opts = {};
}
if (typeof x6 !== "string") {
var err = new TypeError("Path must be a string.");
return process.nextTick(function() {
cb2(err);
});
}
opts = normalizeOptions(x6, opts);
var isFile = opts.isFile || defaultIsFile;
var isDirectory2 = opts.isDirectory || defaultIsDir;
var readFile17 = opts.readFile || fs24.readFile;
var realpath2 = opts.realpath || defaultRealpath;
var readPackage = opts.readPackage || defaultReadPackage;
if (opts.readFile && opts.readPackage) {
var conflictErr = new TypeError("`readFile` and `readPackage` are mutually exclusive.");
return process.nextTick(function() {
cb2(conflictErr);
});
}
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || [".js"];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path72.dirname(caller());
var parent = opts.filename || basedir;
opts.paths = opts.paths || defaultPaths();
var absoluteStart = path72.resolve(basedir);
maybeRealpath(
realpath2,
absoluteStart,
opts,
function(err2, realStart) {
if (err2) cb2(err2);
else init3(realStart);
}
);
var res;
function init3(basedir2) {
if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x6)) {
res = path72.resolve(basedir2, x6);
if (x6 === "." || x6 === ".." || x6.slice(-1) === "/") res += "/";
if (/\/$/.test(x6) && res === basedir2) {
loadAsDirectory(res, opts.package, onfile);
} else loadAsFile(res, opts.package, onfile);
} else if (includeCoreModules && isCore(x6)) {
return cb2(null, x6);
} else loadNodeModules(x6, basedir2, function(err2, n6, pkg) {
if (err2) cb2(err2);
else if (n6) {
return maybeRealpath(realpath2, n6, opts, function(err3, realN) {
if (err3) {
cb2(err3);
} else {
cb2(null, realN, pkg);
}
});
} else {
var moduleError = new Error("Cannot find module '" + x6 + "' from '" + parent + "'");
moduleError.code = "MODULE_NOT_FOUND";
cb2(moduleError);
}
});
}
__name(init3, "init");
function onfile(err2, m6, pkg) {
if (err2) cb2(err2);
else if (m6) cb2(null, m6, pkg);
else loadAsDirectory(res, function(err3, d6, pkg2) {
if (err3) cb2(err3);
else if (d6) {
maybeRealpath(realpath2, d6, opts, function(err4, realD) {
if (err4) {
cb2(err4);
} else {
cb2(null, realD, pkg2);
}
});
} else {
var moduleError = new Error("Cannot find module '" + x6 + "' from '" + parent + "'");
moduleError.code = "MODULE_NOT_FOUND";
cb2(moduleError);
}
});
}
__name(onfile, "onfile");
function loadAsFile(x7, thePackage, callback2) {
var loadAsFilePackage = thePackage;
var cb3 = callback2;
if (typeof loadAsFilePackage === "function") {
cb3 = loadAsFilePackage;
loadAsFilePackage = void 0;
}
var exts = [""].concat(extensions);
load(exts, x7, loadAsFilePackage);
function load(exts2, x8, loadPackage) {
if (exts2.length === 0) return cb3(null, void 0, loadPackage);
var file = x8 + exts2[0];
var pkg = loadPackage;
if (pkg) onpkg(null, pkg);
else loadpkg(path72.dirname(file), onpkg);
function onpkg(err2, pkg_, dir) {
pkg = pkg_;
if (err2) return cb3(err2);
if (dir && pkg && opts.pathFilter) {
var rfile = path72.relative(dir, file);
var rel = rfile.slice(0, rfile.length - exts2[0].length);
var r7 = opts.pathFilter(pkg, x8, rel);
if (r7) return load(
[""].concat(extensions.slice()),
path72.resolve(dir, r7),
pkg
);
}
isFile(file, onex);
}
__name(onpkg, "onpkg");
function onex(err2, ex) {
if (err2) return cb3(err2);
if (ex) return cb3(null, file, pkg);
load(exts2.slice(1), x8, pkg);
}
__name(onex, "onex");
}
__name(load, "load");
}
__name(loadAsFile, "loadAsFile");
function loadpkg(dir, cb3) {
if (dir === "" || dir === "/") return cb3(null);
if (process.platform === "win32" && /^\w:[/\\]*$/.test(dir)) {
return cb3(null);
}
if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb3(null);
maybeRealpath(realpath2, dir, opts, function(unwrapErr, pkgdir) {
if (unwrapErr) return loadpkg(path72.dirname(dir), cb3);
var pkgfile = path72.join(pkgdir, "package.json");
isFile(pkgfile, function(err2, ex) {
if (!ex) return loadpkg(path72.dirname(dir), cb3);
readPackage(readFile17, pkgfile, function(err3, pkgParam) {
if (err3) cb3(err3);
var pkg = pkgParam;
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(pkg, pkgfile);
}
cb3(null, pkg, dir);
});
});
});
}
__name(loadpkg, "loadpkg");
function loadAsDirectory(x7, loadAsDirectoryPackage, callback2) {
var cb3 = callback2;
var fpkg = loadAsDirectoryPackage;
if (typeof fpkg === "function") {
cb3 = fpkg;
fpkg = opts.package;
}
maybeRealpath(realpath2, x7, opts, function(unwrapErr, pkgdir) {
if (unwrapErr) return cb3(unwrapErr);
var pkgfile = path72.join(pkgdir, "package.json");
isFile(pkgfile, function(err2, ex) {
if (err2) return cb3(err2);
if (!ex) return loadAsFile(path72.join(x7, "index"), fpkg, cb3);
readPackage(readFile17, pkgfile, function(err3, pkgParam) {
if (err3) return cb3(err3);
var pkg = pkgParam;
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(pkg, pkgfile);
}
if (pkg && pkg.main) {
if (typeof pkg.main !== "string") {
var mainError = new TypeError("package \u201C" + pkg.name + "\u201D `main` must be a string");
mainError.code = "INVALID_PACKAGE_MAIN";
return cb3(mainError);
}
if (pkg.main === "." || pkg.main === "./") {
pkg.main = "index";
}
loadAsFile(path72.resolve(x7, pkg.main), pkg, function(err4, m6, pkg2) {
if (err4) return cb3(err4);
if (m6) return cb3(null, m6, pkg2);
if (!pkg2) return loadAsFile(path72.join(x7, "index"), pkg2, cb3);
var dir = path72.resolve(x7, pkg2.main);
loadAsDirectory(dir, pkg2, function(err5, n6, pkg3) {
if (err5) return cb3(err5);
if (n6) return cb3(null, n6, pkg3);
loadAsFile(path72.join(x7, "index"), pkg3, cb3);
});
});
return;
}
loadAsFile(path72.join(x7, "/index"), pkg, cb3);
});
});
});
}
__name(loadAsDirectory, "loadAsDirectory");
function processDirs(cb3, dirs) {
if (dirs.length === 0) return cb3(null, void 0);
var dir = dirs[0];
isDirectory2(path72.dirname(dir), isdir);
function isdir(err2, isdir2) {
if (err2) return cb3(err2);
if (!isdir2) return processDirs(cb3, dirs.slice(1));
loadAsFile(dir, opts.package, onfile2);
}
__name(isdir, "isdir");
function onfile2(err2, m6, pkg) {
if (err2) return cb3(err2);
if (m6) return cb3(null, m6, pkg);
loadAsDirectory(dir, opts.package, ondir);
}
__name(onfile2, "onfile");
function ondir(err2, n6, pkg) {
if (err2) return cb3(err2);
if (n6) return cb3(null, n6, pkg);
processDirs(cb3, dirs.slice(1));
}
__name(ondir, "ondir");
}
__name(processDirs, "processDirs");
function loadNodeModules(x7, start, cb3) {
var thunk = /* @__PURE__ */ __name(function() {
return getPackageCandidates(x7, start, opts);
}, "thunk");
processDirs(
cb3,
packageIterator ? packageIterator(x7, start, thunk, opts) : thunk()
);
}
__name(loadNodeModules, "loadNodeModules");
}, "resolve");
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/core.json
var require_core2 = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/core.json"(exports2, module3) {
module3.exports = {
assert: true,
"node:assert": [">= 14.18 && < 15", ">= 16"],
"assert/strict": ">= 15",
"node:assert/strict": ">= 16",
async_hooks: ">= 8",
"node:async_hooks": [">= 14.18 && < 15", ">= 16"],
buffer_ieee754: ">= 0.5 && < 0.9.7",
buffer: true,
"node:buffer": [">= 14.18 && < 15", ">= 16"],
child_process: true,
"node:child_process": [">= 14.18 && < 15", ">= 16"],
cluster: ">= 0.5",
"node:cluster": [">= 14.18 && < 15", ">= 16"],
console: true,
"node:console": [">= 14.18 && < 15", ">= 16"],
constants: true,
"node:constants": [">= 14.18 && < 15", ">= 16"],
crypto: true,
"node:crypto": [">= 14.18 && < 15", ">= 16"],
_debug_agent: ">= 1 && < 8",
_debugger: "< 8",
dgram: true,
"node:dgram": [">= 14.18 && < 15", ">= 16"],
diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
"node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
dns: true,
"node:dns": [">= 14.18 && < 15", ">= 16"],
"dns/promises": ">= 15",
"node:dns/promises": ">= 16",
domain: ">= 0.7.12",
"node:domain": [">= 14.18 && < 15", ">= 16"],
events: true,
"node:events": [">= 14.18 && < 15", ">= 16"],
freelist: "< 6",
fs: true,
"node:fs": [">= 14.18 && < 15", ">= 16"],
"fs/promises": [">= 10 && < 10.1", ">= 14"],
"node:fs/promises": [">= 14.18 && < 15", ">= 16"],
_http_agent: ">= 0.11.1",
"node:_http_agent": [">= 14.18 && < 15", ">= 16"],
_http_client: ">= 0.11.1",
"node:_http_client": [">= 14.18 && < 15", ">= 16"],
_http_common: ">= 0.11.1",
"node:_http_common": [">= 14.18 && < 15", ">= 16"],
_http_incoming: ">= 0.11.1",
"node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
_http_outgoing: ">= 0.11.1",
"node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
_http_server: ">= 0.11.1",
"node:_http_server": [">= 14.18 && < 15", ">= 16"],
http: true,
"node:http": [">= 14.18 && < 15", ">= 16"],
http2: ">= 8.8",
"node:http2": [">= 14.18 && < 15", ">= 16"],
https: true,
"node:https": [">= 14.18 && < 15", ">= 16"],
inspector: ">= 8",
"node:inspector": [">= 14.18 && < 15", ">= 16"],
"inspector/promises": [">= 19"],
"node:inspector/promises": [">= 19"],
_linklist: "< 8",
module: true,
"node:module": [">= 14.18 && < 15", ">= 16"],
net: true,
"node:net": [">= 14.18 && < 15", ">= 16"],
"node-inspect/lib/_inspect": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
"node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
os: true,
"node:os": [">= 14.18 && < 15", ">= 16"],
path: true,
"node:path": [">= 14.18 && < 15", ">= 16"],
"path/posix": ">= 15.3",
"node:path/posix": ">= 16",
"path/win32": ">= 15.3",
"node:path/win32": ">= 16",
perf_hooks: ">= 8.5",
"node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
process: ">= 1",
"node:process": [">= 14.18 && < 15", ">= 16"],
punycode: ">= 0.5",
"node:punycode": [">= 14.18 && < 15", ">= 16"],
querystring: true,
"node:querystring": [">= 14.18 && < 15", ">= 16"],
readline: true,
"node:readline": [">= 14.18 && < 15", ">= 16"],
"readline/promises": ">= 17",
"node:readline/promises": ">= 17",
repl: true,
"node:repl": [">= 14.18 && < 15", ">= 16"],
smalloc: ">= 0.11.5 && < 3",
_stream_duplex: ">= 0.9.4",
"node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
_stream_transform: ">= 0.9.4",
"node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
_stream_wrap: ">= 1.4.1",
"node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
_stream_passthrough: ">= 0.9.4",
"node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
_stream_readable: ">= 0.9.4",
"node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
_stream_writable: ">= 0.9.4",
"node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
stream: true,
"node:stream": [">= 14.18 && < 15", ">= 16"],
"stream/consumers": ">= 16.7",
"node:stream/consumers": ">= 16.7",
"stream/promises": ">= 15",
"node:stream/promises": ">= 16",
"stream/web": ">= 16.5",
"node:stream/web": ">= 16.5",
string_decoder: true,
"node:string_decoder": [">= 14.18 && < 15", ">= 16"],
sys: [">= 0.4 && < 0.7", ">= 0.8"],
"node:sys": [">= 14.18 && < 15", ">= 16"],
"test/reporters": ">= 19.9 && < 20.2",
"node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
"node:test": [">= 16.17 && < 17", ">= 18"],
timers: true,
"node:timers": [">= 14.18 && < 15", ">= 16"],
"timers/promises": ">= 15",
"node:timers/promises": ">= 16",
_tls_common: ">= 0.11.13",
"node:_tls_common": [">= 14.18 && < 15", ">= 16"],
_tls_legacy: ">= 0.11.3 && < 10",
_tls_wrap: ">= 0.11.3",
"node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
tls: true,
"node:tls": [">= 14.18 && < 15", ">= 16"],
trace_events: ">= 10",
"node:trace_events": [">= 14.18 && < 15", ">= 16"],
tty: true,
"node:tty": [">= 14.18 && < 15", ">= 16"],
url: true,
"node:url": [">= 14.18 && < 15", ">= 16"],
util: true,
"node:util": [">= 14.18 && < 15", ">= 16"],
"util/types": ">= 15.3",
"node:util/types": ">= 16",
"v8/tools/arguments": ">= 10 && < 12",
"v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
"v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
v8: ">= 1",
"node:v8": [">= 14.18 && < 15", ">= 16"],
vm: true,
"node:vm": [">= 14.18 && < 15", ">= 16"],
wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
"node:wasi": [">= 18.17 && < 19", ">= 20"],
worker_threads: ">= 11.7",
"node:worker_threads": [">= 14.18 && < 15", ">= 16"],
zlib: ">= 0.5",
"node:zlib": [">= 14.18 && < 15", ">= 16"]
};
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/core.js
var require_core3 = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/core.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var isCoreModule = require_is_core_module();
var data = require_core2();
var core = {};
for (mod in data) {
if (Object.prototype.hasOwnProperty.call(data, mod)) {
core[mod] = isCoreModule(mod);
}
}
var mod;
module3.exports = core;
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/is-core.js
var require_is_core = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/is-core.js"(exports2, module3) {
init_import_meta_url();
var isCoreModule = require_is_core_module();
module3.exports = /* @__PURE__ */ __name(function isCore(x6) {
return isCoreModule(x6);
}, "isCore");
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/sync.js
var require_sync = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/lib/sync.js"(exports2, module3) {
init_import_meta_url();
var isCore = require_is_core_module();
var fs24 = require("fs");
var path72 = require("path");
var getHomedir = require_homedir();
var caller = require_caller();
var nodeModulesPaths = require_node_modules_paths();
var normalizeOptions = require_normalize_options();
var realpathFS = process.platform !== "win32" && fs24.realpathSync && typeof fs24.realpathSync.native === "function" ? fs24.realpathSync.native : fs24.realpathSync;
var homedir3 = getHomedir();
var defaultPaths = /* @__PURE__ */ __name(function() {
return [
path72.join(homedir3, ".node_modules"),
path72.join(homedir3, ".node_libraries")
];
}, "defaultPaths");
var defaultIsFile = /* @__PURE__ */ __name(function isFile(file) {
try {
var stat8 = fs24.statSync(file, { throwIfNoEntry: false });
} catch (e7) {
if (e7 && (e7.code === "ENOENT" || e7.code === "ENOTDIR")) return false;
throw e7;
}
return !!stat8 && (stat8.isFile() || stat8.isFIFO());
}, "isFile");
var defaultIsDir = /* @__PURE__ */ __name(function isDirectory2(dir) {
try {
var stat8 = fs24.statSync(dir, { throwIfNoEntry: false });
} catch (e7) {
if (e7 && (e7.code === "ENOENT" || e7.code === "ENOTDIR")) return false;
throw e7;
}
return !!stat8 && stat8.isDirectory();
}, "isDirectory");
var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync4(x6) {
try {
return realpathFS(x6);
} catch (realpathErr) {
if (realpathErr.code !== "ENOENT") {
throw realpathErr;
}
}
return x6;
}, "realpathSync");
var maybeRealpathSync = /* @__PURE__ */ __name(function maybeRealpathSync2(realpathSync4, x6, opts) {
if (opts && opts.preserveSymlinks === false) {
return realpathSync4(x6);
}
return x6;
}, "maybeRealpathSync");
var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync30, pkgfile) {
var body = readFileSync30(pkgfile);
try {
var pkg = JSON.parse(body);
return pkg;
} catch (jsonErr) {
}
}, "defaultReadPackageSync");
var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x6, start, opts) {
var dirs = nodeModulesPaths(start, opts, x6);
for (var i5 = 0; i5 < dirs.length; i5++) {
dirs[i5] = path72.join(dirs[i5], x6);
}
return dirs;
}, "getPackageCandidates");
module3.exports = /* @__PURE__ */ __name(function resolveSync2(x6, options) {
if (typeof x6 !== "string") {
throw new TypeError("Path must be a string.");
}
var opts = normalizeOptions(x6, options);
var isFile = opts.isFile || defaultIsFile;
var readFileSync30 = opts.readFileSync || fs24.readFileSync;
var isDirectory2 = opts.isDirectory || defaultIsDir;
var realpathSync4 = opts.realpathSync || defaultRealpathSync;
var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
if (opts.readFileSync && opts.readPackageSync) {
throw new TypeError("`readFileSync` and `readPackageSync` are mutually exclusive.");
}
var packageIterator = opts.packageIterator;
var extensions = opts.extensions || [".js"];
var includeCoreModules = opts.includeCoreModules !== false;
var basedir = opts.basedir || path72.dirname(caller());
var parent = opts.filename || basedir;
opts.paths = opts.paths || defaultPaths();
var absoluteStart = maybeRealpathSync(realpathSync4, path72.resolve(basedir), opts);
if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x6)) {
var res = path72.resolve(absoluteStart, x6);
if (x6 === "." || x6 === ".." || x6.slice(-1) === "/") res += "/";
var m6 = loadAsFileSync(res) || loadAsDirectorySync(res);
if (m6) return maybeRealpathSync(realpathSync4, m6, opts);
} else if (includeCoreModules && isCore(x6)) {
return x6;
} else {
var n6 = loadNodeModulesSync(x6, absoluteStart);
if (n6) return maybeRealpathSync(realpathSync4, n6, opts);
}
var err = new Error("Cannot find module '" + x6 + "' from '" + parent + "'");
err.code = "MODULE_NOT_FOUND";
throw err;
function loadAsFileSync(x7) {
var pkg = loadpkg(path72.dirname(x7));
if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
var rfile = path72.relative(pkg.dir, x7);
var r7 = opts.pathFilter(pkg.pkg, x7, rfile);
if (r7) {
x7 = path72.resolve(pkg.dir, r7);
}
}
if (isFile(x7)) {
return x7;
}
for (var i5 = 0; i5 < extensions.length; i5++) {
var file = x7 + extensions[i5];
if (isFile(file)) {
return file;
}
}
}
__name(loadAsFileSync, "loadAsFileSync");
function loadpkg(dir) {
if (dir === "" || dir === "/") return;
if (process.platform === "win32" && /^\w:[/\\]*$/.test(dir)) {
return;
}
if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
var pkgfile = path72.join(maybeRealpathSync(realpathSync4, dir, opts), "package.json");
if (!isFile(pkgfile)) {
return loadpkg(path72.dirname(dir));
}
var pkg = readPackageSync(readFileSync30, pkgfile);
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(
pkg,
/*pkgfile,*/
dir
);
}
return { pkg, dir };
}
__name(loadpkg, "loadpkg");
function loadAsDirectorySync(x7) {
var pkgfile = path72.join(maybeRealpathSync(realpathSync4, x7, opts), "/package.json");
if (isFile(pkgfile)) {
try {
var pkg = readPackageSync(readFileSync30, pkgfile);
} catch (e7) {
}
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(
pkg,
/*pkgfile,*/
x7
);
}
if (pkg && pkg.main) {
if (typeof pkg.main !== "string") {
var mainError = new TypeError("package \u201C" + pkg.name + "\u201D `main` must be a string");
mainError.code = "INVALID_PACKAGE_MAIN";
throw mainError;
}
if (pkg.main === "." || pkg.main === "./") {
pkg.main = "index";
}
try {
var m7 = loadAsFileSync(path72.resolve(x7, pkg.main));
if (m7) return m7;
var n7 = loadAsDirectorySync(path72.resolve(x7, pkg.main));
if (n7) return n7;
} catch (e7) {
}
}
}
return loadAsFileSync(path72.join(x7, "/index"));
}
__name(loadAsDirectorySync, "loadAsDirectorySync");
function loadNodeModulesSync(x7, start) {
var thunk = /* @__PURE__ */ __name(function() {
return getPackageCandidates(x7, start, opts);
}, "thunk");
var dirs = packageIterator ? packageIterator(x7, start, thunk, opts) : thunk();
for (var i5 = 0; i5 < dirs.length; i5++) {
var dir = dirs[i5];
if (isDirectory2(path72.dirname(dir))) {
var m7 = loadAsFileSync(dir);
if (m7) return m7;
var n7 = loadAsDirectorySync(dir);
if (n7) return n7;
}
}
}
__name(loadNodeModulesSync, "loadNodeModulesSync");
}, "resolveSync");
}
});
// ../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/index.js
var require_resolve = __commonJS({
"../../node_modules/.pnpm/resolve@1.22.8/node_modules/resolve/index.js"(exports2, module3) {
init_import_meta_url();
var async = require_async();
async.core = require_core3();
async.isCore = require_is_core();
async.sync = require_sync();
module3.exports = async;
}
});
// src/paths.ts
function toUrlPath(filePath) {
(0, import_node_console.assert)(
!/^[a-z]:/i.test(filePath),
"Tried to convert a Windows file path with a drive to a URL path."
);
return filePath.replace(/\\/g, "/");
}
function readableRelative(to) {
const relativePath = import_node_path11.default.relative(process.cwd(), to);
if (
// No directory nesting, return as-is
import_node_path11.default.basename(relativePath) === relativePath || // Outside current directory
relativePath.startsWith(".")
) {
return relativePath;
} else {
return "./" + relativePath;
}
}
function getBasePath() {
return import_node_path11.default.resolve(__dirname, "..");
}
function getWranglerHiddenDirPath(projectRoot) {
projectRoot ??= process.cwd();
return import_node_path11.default.join(projectRoot, ".wrangler");
}
function getWranglerTmpDir(projectRoot, prefix, cleanup = true) {
const tmpRoot = import_node_path11.default.join(getWranglerHiddenDirPath(projectRoot), "tmp");
import_node_fs6.default.mkdirSync(tmpRoot, { recursive: true });
const tmpPrefix = import_node_path11.default.join(tmpRoot, `${prefix}-`);
const tmpDir = import_node_fs6.default.realpathSync(import_node_fs6.default.mkdtempSync(tmpPrefix));
const removeDir = /* @__PURE__ */ __name(() => {
if (cleanup) {
try {
return import_node_fs6.default.rmSync(tmpDir, { recursive: true, force: true });
} catch {
}
}
}, "removeDir");
const removeExitListener = (0, import_signal_exit3.default)(removeDir);
return {
path: tmpDir,
remove() {
removeExitListener();
removeDir();
}
};
}
var import_node_console, import_node_fs6, import_node_path11, import_signal_exit3;
var init_paths = __esm({
"src/paths.ts"() {
init_import_meta_url();
import_node_console = require("console");
import_node_fs6 = __toESM(require("fs"));
import_node_path11 = __toESM(require("path"));
import_signal_exit3 = __toESM(require_signal_exit());
__name(toUrlPath, "toUrlPath");
__name(readableRelative, "readableRelative");
__name(getBasePath, "getBasePath");
__name(getWranglerHiddenDirPath, "getWranglerHiddenDirPath");
__name(getWranglerTmpDir, "getWranglerTmpDir");
}
});
// src/deployment-bundle/bundle-type.ts
function getBundleType(format9, file) {
if (file && file.endsWith(".py")) {
return "python";
}
return format9 === "modules" ? "esm" : "commonjs";
}
var init_bundle_type = __esm({
"src/deployment-bundle/bundle-type.ts"() {
init_import_meta_url();
__name(getBundleType, "getBundleType");
}
});
// src/deployment-bundle/rules.ts
function isJavaScriptModuleRule(rule) {
return rule.type === "ESModule" || rule.type === "CommonJS";
}
function parseRules(userRules = []) {
const rules = [...userRules, ...DEFAULT_MODULE_RULES];
const completedRuleLocations = {};
const redundantRules = {};
let index = 0;
const rulesToRemove = [];
for (const rule of rules) {
if (rule.type in completedRuleLocations) {
if (rules[completedRuleLocations[rule.type]].fallthrough !== false) {
if (rule.type in redundantRules) {
redundantRules[rule.type].push({
index,
default: index >= userRules.length
});
} else {
redundantRules[rule.type] = [
{ index, default: index >= userRules.length }
];
}
}
rulesToRemove.push(rule);
}
if (!(rule.type in completedRuleLocations) && rule.fallthrough !== true) {
completedRuleLocations[rule.type] = index;
}
index++;
}
for (const completedRuleType in completedRuleLocations) {
const r7 = redundantRules[completedRuleType];
if (r7) {
const completedRuleIndex = completedRuleLocations[completedRuleType];
let warning = `The ${completedRuleIndex >= userRules.length ? "default " : ""}module rule ${JSON.stringify(
rules[completedRuleIndex]
)} does not have a fallback, the following rules will be ignored:`;
for (const rule of r7) {
warning += `
${JSON.stringify(rules[rule.index])}${rule.default ? " (DEFAULT)" : ""}`;
}
warning += `
Add \`fallthrough = true\` to rule to allow next rule to be used or \`fallthrough = false\` to silence this warning`;
logger.warn(warning);
}
}
rulesToRemove.forEach((rule) => rules.splice(rules.indexOf(rule), 1));
return { rules, removedRules: rulesToRemove };
}
var DEFAULT_MODULE_RULES;
var init_rules = __esm({
"src/deployment-bundle/rules.ts"() {
init_import_meta_url();
init_logger();
__name(isJavaScriptModuleRule, "isJavaScriptModuleRule");
DEFAULT_MODULE_RULES = [
{ type: "Text", globs: ["**/*.txt", "**/*.html"] },
{ type: "Data", globs: ["**/*.bin"] },
{ type: "CompiledWasm", globs: ["**/*.wasm", "**/*.wasm?module"] }
];
__name(parseRules, "parseRules");
}
});
// src/deployment-bundle/source-maps.ts
function loadSourceMaps(main2, modules, bundle) {
const { sourceMapPath, sourceMapMetadata } = bundle;
if (sourceMapPath && sourceMapMetadata) {
return loadSourceMap(main2, sourceMapPath, sourceMapMetadata);
} else {
return scanSourceMaps([main2, ...modules]);
}
}
function loadSourceMap({ name: name2, filePath }, sourceMapPath, { entryDirectory }) {
if (filePath === void 0) {
return [];
}
const map2 = JSON.parse(
import_node_fs7.default.readFileSync(import_node_path12.default.join(entryDirectory, sourceMapPath), "utf8")
);
map2.file = name2;
if (map2.sourceRoot) {
const sourceRootPath = import_node_path12.default.dirname(
import_node_path12.default.join(entryDirectory, sourceMapPath)
);
map2.sourceRoot = import_node_path12.default.relative(sourceRootPath, map2.sourceRoot);
}
map2.sources = map2.sources.map((source) => {
const originalPath = import_node_path12.default.join(import_node_path12.default.dirname(filePath), source);
return import_node_path12.default.relative(entryDirectory, originalPath);
});
return [
{
name: name2 + ".map",
content: JSON.stringify(map2)
}
];
}
function scanSourceMaps(modules) {
const maps = [];
for (const module3 of modules) {
const maybeSourcemap = sourceMapForModule(module3);
if (maybeSourcemap) {
maps.push(maybeSourcemap);
}
}
return maps;
}
function tryAttachSourcemapToModule(module3) {
if (module3.type !== "esm" && module3.type !== "commonjs") {
return;
}
const sourceMap = sourceMapForModule(module3);
if (sourceMap) {
module3.sourceMap = sourceMap;
}
}
function getSourceMappingUrl(module3) {
const content = typeof module3.content === "string" ? module3.content : new TextDecoder().decode(module3.content);
const trimmed = content.trimEnd();
const lines = trimmed.split("\n");
while (lines.at(-1)?.trim().length === 0) {
lines.pop();
}
const commentPrefix = "//# sourceMappingURL=";
const lastLine = lines.pop();
if (lastLine === void 0 || !lastLine.startsWith(commentPrefix)) {
return void 0;
}
const commentPath = stripPrefix(commentPrefix, lastLine).trim();
if (commentPath.startsWith("data:")) {
throw new Error(
`Unsupported source map path in ${module3.filePath}: expected file path but found data URL.`
);
}
return commentPath;
}
function sourceMapForModule(module3) {
if (module3.filePath === void 0) {
return void 0;
}
const sourceMapUrl = getSourceMappingUrl(module3);
if (sourceMapUrl === void 0) {
return;
}
const sourcemapPath = import_node_path12.default.join(import_node_path12.default.dirname(module3.filePath), sourceMapUrl);
if (!import_node_fs7.default.existsSync(sourcemapPath)) {
throw new Error(
`Invalid source map path in ${module3.filePath}: ${sourcemapPath} does not exist.`
);
}
const map2 = JSON.parse(
import_node_fs7.default.readFileSync(sourcemapPath, "utf8")
);
map2.file = module3.name;
if (map2.sourceRoot) {
map2.sourceRoot = cleanPathPrefix(map2.sourceRoot);
}
map2.sources = map2.sources.map(cleanPathPrefix);
return {
name: module3.name + ".map",
content: JSON.stringify(map2)
};
}
function cleanPathPrefix(filePath) {
return stripPrefix(
"..\\",
stripPrefix("../", stripPrefix(".\\", stripPrefix("./", filePath)))
);
}
function stripPrefix(prefix, input) {
let stripped = input;
while (stripped.startsWith(prefix)) {
stripped = stripped.slice(prefix.length);
}
return stripped;
}
var import_node_fs7, import_node_path12;
var init_source_maps = __esm({
"src/deployment-bundle/source-maps.ts"() {
init_import_meta_url();
import_node_fs7 = __toESM(require("fs"));
import_node_path12 = __toESM(require("path"));
__name(loadSourceMaps, "loadSourceMaps");
__name(loadSourceMap, "loadSourceMap");
__name(scanSourceMaps, "scanSourceMaps");
__name(tryAttachSourcemapToModule, "tryAttachSourcemapToModule");
__name(getSourceMappingUrl, "getSourceMappingUrl");
__name(sourceMapForModule, "sourceMapForModule");
__name(cleanPathPrefix, "cleanPathPrefix");
__name(stripPrefix, "stripPrefix");
}
});
// src/deployment-bundle/find-additional-modules.ts
async function* getFiles(configPath, moduleRoot, relativeTo, projectRoot) {
const wranglerHiddenDirPath = getWranglerHiddenDirPath(projectRoot);
for (const file of await (0, import_promises3.readdir)(moduleRoot, { withFileTypes: true })) {
const absPath = import_node_path13.default.join(moduleRoot, file.name);
if (file.isDirectory()) {
if (absPath !== wranglerHiddenDirPath) {
yield* getFiles(configPath, absPath, relativeTo, projectRoot);
}
} else {
if (absPath !== configPath) {
yield import_node_path13.default.relative(relativeTo, absPath).replaceAll("\\", "/");
}
}
}
}
function isValidPythonPackageName(name2) {
const regex2 = /^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$/i;
return regex2.test(name2);
}
function filterPythonVendorModules(isPythonEntrypoint, modules) {
if (!isPythonEntrypoint) {
return modules;
}
return modules.filter((m6) => !m6.name.startsWith("python_modules" + import_node_path13.default.sep));
}
function getPythonVendorModulesSize(modules) {
const vendorModules = modules.filter(
(m6) => m6.name.startsWith("python_modules" + import_node_path13.default.sep)
);
return vendorModules.reduce((total, m6) => total + m6.content.length, 0);
}
async function findAdditionalModules(entry, rules, attachSourcemaps = false) {
const files = getFiles(
entry.configPath,
entry.moduleRoot,
entry.moduleRoot,
entry.projectRoot
);
const relativeEntryPoint = import_node_path13.default.relative(entry.moduleRoot, entry.file).replaceAll("\\", "/");
if (Array.isArray(rules)) {
rules = parseRules(rules);
}
const modules = (await matchFiles(files, entry.moduleRoot, rules)).filter((m6) => m6.name !== relativeEntryPoint).map((m6) => ({
...m6,
name: m6.name
}));
const isPythonEntrypoint = getBundleType(entry.format, entry.file) === "python";
if (isPythonEntrypoint) {
let pythonRequirements = "";
try {
pythonRequirements = await (0, import_promises3.readFile)(
import_node_path13.default.resolve(entry.projectRoot, "cf-requirements.txt"),
"utf-8"
);
} catch {
logger.debug(
"Python entrypoint detected, but no cf-requirements.txt file found."
);
}
if ((0, import_node_fs8.existsSync)(import_node_path13.default.resolve(entry.projectRoot, "requirements.txt"))) {
logger.warn(
"Found a `requirements.txt` file. Python requirements should now be in a `cf-requirements.txt` file."
);
}
for (const requirement of pythonRequirements.split("\n")) {
if (requirement === "") {
continue;
}
if (!isValidPythonPackageName(requirement)) {
throw new UserError(
`Invalid Python package name "${requirement}" found in cf-requirements.txt. Note that cf-requirements.txt should contain package names only, not version specifiers.`
);
}
modules.push({
type: "python-requirement",
name: requirement,
content: "",
filePath: void 0
});
}
const pythonModulesDir = import_node_path13.default.resolve(entry.projectRoot, "python_modules");
const pythonModulesDirInModuleRoot = import_node_path13.default.resolve(
entry.moduleRoot,
"python_modules"
);
const pythonModulesExistsInModuleRoot = (0, import_node_fs8.existsSync)(
pythonModulesDirInModuleRoot
);
if (pythonModulesExistsInModuleRoot && entry.projectRoot !== entry.moduleRoot) {
throw new UserError(
"The 'python_modules' directory cannot exist in your module root. Delete it to continue."
);
}
const pythonModulesExists = (0, import_node_fs8.existsSync)(pythonModulesDir);
if (pythonModulesExists) {
const pythonModulesFiles = getFiles(
entry.file,
pythonModulesDir,
pythonModulesDir,
entry.projectRoot
);
const vendoredRules = [
{ type: "Data", globs: ["**/*.so", "**/*.py"] }
];
const vendoredModules = (await matchFiles(
pythonModulesFiles,
pythonModulesDir,
parseRules(vendoredRules)
)).map((m6) => {
const prefixedPath = import_node_path13.default.join("python_modules", m6.name);
return {
...m6,
name: prefixedPath
};
});
modules.push(...vendoredModules);
} else {
logger.debug(
"Python entrypoint detected, but no python_modules directory found."
);
}
}
if (attachSourcemaps) {
modules.forEach((module3) => tryAttachSourcemapToModule(module3));
}
if (modules.length > 0) {
logger.info(`Attaching additional modules:`);
const filteredModules = filterPythonVendorModules(
isPythonEntrypoint,
modules
);
const vendorModulesSize = getPythonVendorModulesSize(modules);
const totalSize = modules.reduce(
(previous, { content }) => previous + content.length,
0
);
const tableEntries = [
...filteredModules.map(({ name: name2, type, content }) => {
return {
Name: name2,
Type: type ?? "",
Size: type === "python-requirement" ? "" : `${(content.length / 1024).toFixed(2)} KiB`
};
})
];
if (isPythonEntrypoint && vendorModulesSize > 0) {
tableEntries.push({
Name: "Vendored Modules",
Type: "",
Size: `${(vendorModulesSize / 1024).toFixed(2)} KiB`
});
}
tableEntries.push({
Name: `Total (${modules.length} module${modules.length > 1 ? "s" : ""})`,
Type: "",
Size: `${(totalSize / 1024).toFixed(2)} KiB`
});
logger.table(tableEntries);
}
return modules;
}
async function matchFiles(files, relativeTo, { rules, removedRules }) {
const modules = [];
const moduleNames = /* @__PURE__ */ new Set();
for await (const filePath of files) {
for (const rule of rules) {
for (const glob of rule.globs) {
const regexp = (0, import_glob_to_regexp.default)(glob, {
globstar: true
});
if (!regexp.test(filePath)) {
continue;
}
const absoluteFilePath = import_node_path13.default.join(relativeTo, filePath);
const fileContent = await (0, import_promises3.readFile)(
absoluteFilePath
);
const module3 = {
name: filePath,
content: fileContent,
filePath: absoluteFilePath,
type: RuleTypeToModuleType[rule.type]
};
if (!moduleNames.has(module3.name)) {
moduleNames.add(module3.name);
modules.push(module3);
} else {
logger.warn(
`Ignoring duplicate module: ${source_default.blue(
module3.name
)} (${source_default.green(module3.type ?? "")})`
);
}
}
}
for (const rule of removedRules) {
for (const glob of rule.globs) {
const regexp = (0, import_glob_to_regexp.default)(glob);
if (regexp.test(filePath)) {
throw new UserError(
`The file ${filePath} matched a module rule in your configuration (${JSON.stringify(
rule
)}), but was ignored because a previous rule with the same type was not marked as \`fallthrough = true\`.`
);
}
}
}
}
return modules;
}
async function* findAdditionalModuleWatchDirs(root) {
yield root;
for (const entry of await (0, import_promises3.readdir)(root, { withFileTypes: true })) {
if (entry.isDirectory()) {
if (entry.name === "node_modules" || entry.name === ".git") {
continue;
}
yield* findAdditionalModuleWatchDirs(import_node_path13.default.join(root, entry.name));
}
}
}
async function writeAdditionalModules(modules, destination) {
for (const module3 of modules) {
const modulePath = import_node_path13.default.resolve(destination, module3.name);
logger.debug("Writing additional module to output", modulePath);
await (0, import_promises3.mkdir)(import_node_path13.default.dirname(modulePath), { recursive: true });
await (0, import_promises3.writeFile)(modulePath, module3.content);
if (module3.sourceMap) {
const sourcemapPath = import_node_path13.default.resolve(destination, module3.sourceMap.name);
await (0, import_promises3.writeFile)(sourcemapPath, module3.sourceMap.content);
}
}
}
var import_node_fs8, import_promises3, import_node_path13, import_glob_to_regexp;
var init_find_additional_modules = __esm({
"src/deployment-bundle/find-additional-modules.ts"() {
init_import_meta_url();
import_node_fs8 = require("fs");
import_promises3 = require("fs/promises");
import_node_path13 = __toESM(require("path"));
init_source();
import_glob_to_regexp = __toESM(require_glob_to_regexp());
init_errors();
init_logger();
init_paths();
init_bundle_type();
init_module_collection();
init_rules();
init_source_maps();
__name(getFiles, "getFiles");
__name(isValidPythonPackageName, "isValidPythonPackageName");
__name(filterPythonVendorModules, "filterPythonVendorModules");
__name(getPythonVendorModulesSize, "getPythonVendorModulesSize");
__name(findAdditionalModules, "findAdditionalModules");
__name(matchFiles, "matchFiles");
__name(findAdditionalModuleWatchDirs, "findAdditionalModuleWatchDirs");
__name(writeAdditionalModules, "writeAdditionalModules");
}
});
// src/deployment-bundle/module-collection.ts
function flipObject(obj) {
return Object.fromEntries(
Object.entries(obj).filter(([_4, v7]) => !!v7).map(([k6, v7]) => [v7, k6])
);
}
function createModuleCollector(props) {
const parsedRules = parseRules(props.rules);
const modules = [];
return {
modules,
plugin: {
name: "wrangler-module-collector",
setup(build5) {
let foundModulePaths = [];
build5.onStart(async () => {
modules.splice(0);
if (props.findAdditionalModules) {
if (props.entry.format !== "modules") {
const error2 = "`find_additional_modules` can only be used with an ES module entrypoint.\nRemove `find_additional_modules = true` from your configuration, or migrate to the ES module Worker format: https://developers.cloudflare.com/workers/learning/migrate-to-module-workers/";
return { errors: [{ text: error2 }] };
}
const found = await findAdditionalModules(props.entry, parsedRules);
foundModulePaths = found.map(
({ name: name2 }) => import_node_path14.default.resolve(props.entry.moduleRoot, name2)
);
modules.push(...found);
}
});
build5.onResolve({ filter: modulesWatchRegexp }, (args) => {
return { namespace: modulesWatchNamespace, path: args.path };
});
build5.onLoad(
{ namespace: modulesWatchNamespace, filter: modulesWatchRegexp },
async () => {
let watchFiles = [];
const watchDirs = [];
if (props.findAdditionalModules) {
watchFiles = foundModulePaths;
const root = import_node_path14.default.resolve(props.entry.moduleRoot);
for await (const dir of findAdditionalModuleWatchDirs(root)) {
watchDirs.push(dir);
}
}
return { contents: "", loader: "js", watchFiles, watchDirs };
}
);
const rulesMatchers = parsedRules.rules.flatMap((rule) => {
return rule.globs.map((glob) => {
const regex2 = (0, import_glob_to_regexp2.default)(glob);
return {
regex: regex2,
rule
};
});
});
if (props.wrangler1xLegacyModuleReferences && props.wrangler1xLegacyModuleReferences.fileNames.size > 0) {
build5.onResolve(
{
filter: new RegExp(
"^(" + [...props.wrangler1xLegacyModuleReferences.fileNames].map((name2) => name2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|") + ")$"
)
},
async (args) => {
if (args.kind !== "import-statement" && args.kind !== "require-call") {
return;
}
logger.warn(
`Deprecation: detected a legacy module import in "./${import_node_path14.default.relative(
process.cwd(),
args.importer
)}". This will stop working in the future. Replace references to "${args.path}" with "./${args.path}";`
);
const filePath = import_node_path14.default.join(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
props.wrangler1xLegacyModuleReferences.rootDirectory,
args.path
);
const fileContent = await (0, import_promises4.readFile)(
filePath
);
const fileHash = import_node_crypto3.default.createHash("sha1").update(fileContent).digest("hex");
const fileName = props.preserveFileNames ? args.path : `./${fileHash}-${import_node_path14.default.basename(args.path)}`;
const { rule } = rulesMatchers.find(({ regex: regex2 }) => regex2.test(fileName)) || {};
if (rule) {
modules.push({
name: fileName,
filePath,
content: fileContent,
type: RuleTypeToModuleType[rule.type]
});
return {
path: fileName,
// change the reference to the changed module
external: props.entry.format === "modules",
// mark it as external in the bundle
namespace: `wrangler-module-${rule.type}`,
// just a tag, this isn't strictly necessary
watchFiles: [filePath]
// we also add the file to esbuild's watch list
};
}
}
);
}
parsedRules.rules?.forEach((rule) => {
if (!props.findAdditionalModules && isJavaScriptModuleRule(rule)) {
return;
}
rule.globs.forEach((glob) => {
build5.onResolve(
{ filter: (0, import_glob_to_regexp2.default)(glob) },
async (args) => {
if (args.pluginData?.skip) {
return;
}
let filePath = import_node_path14.default.join(args.resolveDir, args.path);
if (foundModulePaths.includes(filePath)) {
return { path: args.path, external: true };
}
if (isJavaScriptModuleRule(rule)) {
return;
}
try {
const resolved = await build5.resolve(args.path, {
kind: "import-statement",
resolveDir: args.resolveDir,
pluginData: {
skip: true
}
});
if (resolved.path) {
filePath = resolved.path;
}
} catch {
}
try {
const resolved = (0, import_resolve.sync)(args.path, {
basedir: args.resolveDir
});
filePath = resolved;
} catch {
}
const fileContent = await (0, import_promises4.readFile)(
filePath
);
const fileHash = import_node_crypto3.default.createHash("sha1").update(fileContent).digest("hex");
const fileName = props.preserveFileNames ? args.path : `./${fileHash}-${import_node_path14.default.basename(args.path)}`;
modules.push({
name: fileName,
filePath,
content: fileContent,
type: RuleTypeToModuleType[rule.type]
});
return {
path: fileName,
// change the reference to the changed module
external: props.entry.format === "modules",
// mark it as external in the bundle
namespace: `wrangler-module-${rule.type}`,
// just a tag, this isn't strictly necessary
watchFiles: [filePath]
// we also add the file to esbuild's watch list
};
}
);
if (props.entry.format === "service-worker") {
build5.onLoad(
{ filter: (0, import_glob_to_regexp2.default)(glob) },
async (args) => {
return {
// We replace the the module with an identifier
// that we'll separately add to the form upload
// as part of [wasm_modules]/[text_blobs]/[data_blobs]. This identifier has to be a valid
// JS identifier, so we replace all non alphanumeric characters
// with an underscore.
contents: `export default ${args.path.replace(
/[^a-zA-Z0-9_$]/g,
"_"
)};`
};
}
);
}
});
});
parsedRules.removedRules.forEach((rule) => {
rule.globs.forEach((glob) => {
build5.onResolve(
{ filter: (0, import_glob_to_regexp2.default)(glob) },
async (args) => {
throw new UserError(
`The file ${args.path} matched a module rule in your configuration (${JSON.stringify(
rule
)}), but was ignored because a previous rule with the same type was not marked as \`fallthrough = true\`.`
);
}
);
});
});
}
}
};
}
function getWrangler1xLegacyModuleReferences(rootDirectory, entryPath) {
return {
rootDirectory,
fileNames: new Set(
(0, import_node_fs9.readdirSync)(rootDirectory, { withFileTypes: true }).filter(
(dirEntry) => dirEntry.isFile() && dirEntry.name !== import_node_path14.default.basename(entryPath)
).map((dirEnt) => dirEnt.name)
)
};
}
var import_node_crypto3, import_node_fs9, import_promises4, import_node_path14, import_glob_to_regexp2, import_resolve, RuleTypeToModuleType, ModuleTypeToRuleType, modulesWatchRegexp, modulesWatchNamespace, noopModuleCollector;
var init_module_collection = __esm({
"src/deployment-bundle/module-collection.ts"() {
init_import_meta_url();
import_node_crypto3 = __toESM(require("crypto"));
import_node_fs9 = require("fs");
import_promises4 = require("fs/promises");
import_node_path14 = __toESM(require("path"));
import_glob_to_regexp2 = __toESM(require_glob_to_regexp());
import_resolve = __toESM(require_resolve());
init_errors();
init_logger();
init_find_additional_modules();
init_rules();
__name(flipObject, "flipObject");
RuleTypeToModuleType = {
ESModule: "esm",
CommonJS: "commonjs",
CompiledWasm: "compiled-wasm",
Data: "buffer",
Text: "text",
PythonModule: "python",
PythonRequirement: "python-requirement"
};
ModuleTypeToRuleType = flipObject(RuleTypeToModuleType);
modulesWatchRegexp = /^wrangler:modules-watch$/;
modulesWatchNamespace = "wrangler-modules-watch";
noopModuleCollector = {
modules: [],
plugin: {
name: "wrangler-module-collector",
setup: /* @__PURE__ */ __name((build5) => {
build5.onResolve({ filter: modulesWatchRegexp }, (args) => {
return { namespace: modulesWatchNamespace, path: args.path };
});
build5.onLoad(
{ namespace: modulesWatchNamespace, filter: modulesWatchRegexp },
() => ({ contents: "", loader: "js" })
);
}, "setup")
}
};
__name(createModuleCollector, "createModuleCollector");
__name(getWrangler1xLegacyModuleReferences, "getWrangler1xLegacyModuleReferences");
}
});
// src/deployment-bundle/source-url.ts
function withSourceURL(source, sourcePath) {
return `${source}
//# sourceURL=${(0, import_url2.pathToFileURL)(sourcePath)}`;
}
function withSourceURLs(entrypointPath, entrypointSource, modules) {
if (!entrypointPath.endsWith(".py")) {
entrypointSource = withSourceURL(entrypointSource, entrypointPath);
}
modules = modules.map((module3) => {
if (module3.filePath !== void 0 && (module3.type === "esm" || module3.type === "commonjs")) {
let newContent = module3.content.toString();
newContent = withSourceURL(newContent, module3.filePath);
return { ...module3, content: newContent };
} else {
return module3;
}
});
return { entrypointSource, modules };
}
var import_url2;
var init_source_url = __esm({
"src/deployment-bundle/source-url.ts"() {
init_import_meta_url();
import_url2 = require("url");
__name(withSourceURL, "withSourceURL");
__name(withSourceURLs, "withSourceURLs");
}
});
// src/images/fetcher.ts
function getImagesRemoteFetcher(complianceConfig) {
return /* @__PURE__ */ __name(async function imagesRemoteFetcher(request4) {
const accountId = await getAccountId(complianceConfig);
const url4 = `/accounts/${accountId}/images_edge/v2/binding/preview${new URL(request4.url).pathname}`;
const res = await performApiFetch(complianceConfig, url4, {
method: request4.method,
body: request4.body,
duplex: "half",
headers: {
"content-type": request4.headers.get("content-type") || ""
}
});
return new import_miniflare5.Response(res.body, { headers: res.headers });
}, "imagesRemoteFetcher");
}
var import_miniflare5, EXTERNAL_IMAGES_WORKER_NAME, EXTERNAL_IMAGES_WORKER_SCRIPT;
var init_fetcher2 = __esm({
"src/images/fetcher.ts"() {
init_import_meta_url();
import_miniflare5 = require("miniflare");
init_internal();
init_user2();
EXTERNAL_IMAGES_WORKER_NAME = "__WRANGLER_EXTERNAL_IMAGES_WORKER";
EXTERNAL_IMAGES_WORKER_SCRIPT = `
import makeBinding from 'cloudflare-internal:images-api'
export default function (env) {
return makeBinding({
fetcher: env.FETCHER,
});
}
`;
__name(getImagesRemoteFetcher, "getImagesRemoteFetcher");
}
});
// ../../node_modules/.pnpm/ini@1.3.8/node_modules/ini/ini.js
var require_ini = __commonJS({
"../../node_modules/.pnpm/ini@1.3.8/node_modules/ini/ini.js"(exports2) {
init_import_meta_url();
exports2.parse = exports2.decode = decode;
exports2.stringify = exports2.encode = encode;
exports2.safe = safe;
exports2.unsafe = unsafe;
var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
function encode(obj, opt) {
var children = [];
var out = "";
if (typeof opt === "string") {
opt = {
section: opt,
whitespace: false
};
} else {
opt = opt || {};
opt.whitespace = opt.whitespace === true;
}
var separator = opt.whitespace ? " = " : "=";
Object.keys(obj).forEach(function(k6, _4, __) {
var val2 = obj[k6];
if (val2 && Array.isArray(val2)) {
val2.forEach(function(item) {
out += safe(k6 + "[]") + separator + safe(item) + "\n";
});
} else if (val2 && typeof val2 === "object")
children.push(k6);
else
out += safe(k6) + separator + safe(val2) + eol;
});
if (opt.section && out.length)
out = "[" + safe(opt.section) + "]" + eol + out;
children.forEach(function(k6, _4, __) {
var nk = dotSplit(k6).join("\\.");
var section = (opt.section ? opt.section + "." : "") + nk;
var child = encode(obj[k6], {
section,
whitespace: opt.whitespace
});
if (out.length && child.length)
out += eol;
out += child;
});
return out;
}
__name(encode, "encode");
function dotSplit(str) {
return str.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) {
return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, "");
});
}
__name(dotSplit, "dotSplit");
function decode(str) {
var out = {};
var p6 = out;
var section = null;
var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
var lines = str.split(/[\r\n]+/g);
lines.forEach(function(line, _4, __) {
if (!line || line.match(/^\s*[;#]/))
return;
var match2 = line.match(re);
if (!match2)
return;
if (match2[1] !== void 0) {
section = unsafe(match2[1]);
if (section === "__proto__") {
p6 = {};
return;
}
p6 = out[section] = out[section] || {};
return;
}
var key = unsafe(match2[2]);
if (key === "__proto__")
return;
var value = match2[3] ? unsafe(match2[4]) : true;
switch (value) {
case "true":
case "false":
case "null":
value = JSON.parse(value);
}
if (key.length > 2 && key.slice(-2) === "[]") {
key = key.substring(0, key.length - 2);
if (key === "__proto__")
return;
if (!p6[key])
p6[key] = [];
else if (!Array.isArray(p6[key]))
p6[key] = [p6[key]];
}
if (Array.isArray(p6[key]))
p6[key].push(value);
else
p6[key] = value;
});
Object.keys(out).filter(function(k6, _4, __) {
if (!out[k6] || typeof out[k6] !== "object" || Array.isArray(out[k6]))
return false;
var parts = dotSplit(k6);
var p7 = out;
var l6 = parts.pop();
var nl = l6.replace(/\\\./g, ".");
parts.forEach(function(part, _5, __2) {
if (part === "__proto__")
return;
if (!p7[part] || typeof p7[part] !== "object")
p7[part] = {};
p7 = p7[part];
});
if (p7 === out && nl === l6)
return false;
p7[nl] = out[k6];
return true;
}).forEach(function(del, _4, __) {
delete out[del];
});
return out;
}
__name(decode, "decode");
function isQuoted(val2) {
return val2.charAt(0) === '"' && val2.slice(-1) === '"' || val2.charAt(0) === "'" && val2.slice(-1) === "'";
}
__name(isQuoted, "isQuoted");
function safe(val2) {
return typeof val2 !== "string" || val2.match(/[=\r\n]/) || val2.match(/^\[/) || val2.length > 1 && isQuoted(val2) || val2 !== val2.trim() ? JSON.stringify(val2) : val2.replace(/;/g, "\\;").replace(/#/g, "\\#");
}
__name(safe, "safe");
function unsafe(val2, doUnesc) {
val2 = (val2 || "").trim();
if (isQuoted(val2)) {
if (val2.charAt(0) === "'")
val2 = val2.substr(1, val2.length - 2);
try {
val2 = JSON.parse(val2);
} catch (_4) {
}
} else {
var esc = false;
var unesc = "";
for (var i5 = 0, l6 = val2.length; i5 < l6; i5++) {
var c6 = val2.charAt(i5);
if (esc) {
if ("\\;#".indexOf(c6) !== -1)
unesc += c6;
else
unesc += "\\" + c6;
esc = false;
} else if (";#".indexOf(c6) !== -1)
break;
else if (c6 === "\\")
esc = true;
else
unesc += c6;
}
if (esc)
unesc += "\\";
return unesc.trim();
}
return val2;
}
__name(unsafe, "unsafe");
}
});
// ../../node_modules/.pnpm/strip-json-comments@2.0.1/node_modules/strip-json-comments/index.js
var require_strip_json_comments = __commonJS({
"../../node_modules/.pnpm/strip-json-comments@2.0.1/node_modules/strip-json-comments/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var singleComment = 1;
var multiComment = 2;
function stripWithoutWhitespace() {
return "";
}
__name(stripWithoutWhitespace, "stripWithoutWhitespace");
function stripWithWhitespace(str, start, end) {
return str.slice(start, end).replace(/\S/g, " ");
}
__name(stripWithWhitespace, "stripWithWhitespace");
module3.exports = function(str, opts) {
opts = opts || {};
var currentChar;
var nextChar;
var insideString = false;
var insideComment = false;
var offset = 0;
var ret = "";
var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
for (var i5 = 0; i5 < str.length; i5++) {
currentChar = str[i5];
nextChar = str[i5 + 1];
if (!insideComment && currentChar === '"') {
var escaped = str[i5 - 1] === "\\" && str[i5 - 2] !== "\\";
if (!escaped) {
insideString = !insideString;
}
}
if (insideString) {
continue;
}
if (!insideComment && currentChar + nextChar === "//") {
ret += str.slice(offset, i5);
offset = i5;
insideComment = singleComment;
i5++;
} else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
i5++;
insideComment = false;
ret += strip(str, offset, i5);
offset = i5;
continue;
} else if (insideComment === singleComment && currentChar === "\n") {
insideComment = false;
ret += strip(str, offset, i5);
offset = i5;
} else if (!insideComment && currentChar + nextChar === "/*") {
ret += str.slice(offset, i5);
offset = i5;
insideComment = multiComment;
i5++;
continue;
} else if (insideComment === multiComment && currentChar + nextChar === "*/") {
i5++;
insideComment = false;
ret += strip(str, offset, i5 + 1);
offset = i5 + 1;
continue;
}
}
return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
};
}
});
// ../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/lib/utils.js
var require_utils3 = __commonJS({
"../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/lib/utils.js"(exports2) {
"use strict";
init_import_meta_url();
var fs24 = require("fs");
var ini = require_ini();
var path72 = require("path");
var stripJsonComments = require_strip_json_comments();
var parse7 = exports2.parse = function(content) {
if (/^\s*{/.test(content))
return JSON.parse(stripJsonComments(content));
return ini.parse(content);
};
var file = exports2.file = function() {
var args = [].slice.call(arguments).filter(function(arg) {
return arg != null;
});
for (var i5 in args)
if ("string" !== typeof args[i5])
return;
var file2 = path72.join.apply(null, args);
var content;
try {
return fs24.readFileSync(file2, "utf-8");
} catch (err) {
return;
}
};
var json = exports2.json = function() {
var content = file.apply(null, arguments);
return content ? parse7(content) : null;
};
var env6 = exports2.env = function(prefix, env7) {
env7 = env7 || process.env;
var obj = {};
var l6 = prefix.length;
for (var k6 in env7) {
if (k6.toLowerCase().indexOf(prefix.toLowerCase()) === 0) {
var keypath = k6.substring(l6).split("__");
var _emptyStringIndex;
while ((_emptyStringIndex = keypath.indexOf("")) > -1) {
keypath.splice(_emptyStringIndex, 1);
}
var cursor = obj;
keypath.forEach(/* @__PURE__ */ __name(function _buildSubObj(_subkey, i5) {
if (!_subkey || typeof cursor !== "object")
return;
if (i5 === keypath.length - 1)
cursor[_subkey] = env7[k6];
if (cursor[_subkey] === void 0)
cursor[_subkey] = {};
cursor = cursor[_subkey];
}, "_buildSubObj"));
}
}
return obj;
};
var find = exports2.find = function() {
var rel = path72.join.apply(null, [].slice.call(arguments));
function find2(start, rel2) {
var file2 = path72.join(start, rel2);
try {
fs24.statSync(file2);
return file2;
} catch (err) {
if (path72.dirname(start) !== start)
return find2(path72.dirname(start), rel2);
}
}
__name(find2, "find");
return find2(process.cwd(), rel);
};
}
});
// ../../node_modules/.pnpm/deep-extend@0.6.0/node_modules/deep-extend/lib/deep-extend.js
var require_deep_extend = __commonJS({
"../../node_modules/.pnpm/deep-extend@0.6.0/node_modules/deep-extend/lib/deep-extend.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function isSpecificValue(val2) {
return val2 instanceof Buffer || val2 instanceof Date || val2 instanceof RegExp ? true : false;
}
__name(isSpecificValue, "isSpecificValue");
function cloneSpecificValue(val2) {
if (val2 instanceof Buffer) {
var x6 = Buffer.alloc ? Buffer.alloc(val2.length) : new Buffer(val2.length);
val2.copy(x6);
return x6;
} else if (val2 instanceof Date) {
return new Date(val2.getTime());
} else if (val2 instanceof RegExp) {
return new RegExp(val2);
} else {
throw new Error("Unexpected situation");
}
}
__name(cloneSpecificValue, "cloneSpecificValue");
function deepCloneArray(arr) {
var clone = [];
arr.forEach(function(item, index) {
if (typeof item === "object" && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
__name(deepCloneArray, "deepCloneArray");
function safeGetProperty(object, property) {
return property === "__proto__" ? void 0 : object[property];
}
__name(safeGetProperty, "safeGetProperty");
var deepExtend = module3.exports = function() {
if (arguments.length < 1 || typeof arguments[0] !== "object") {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
var target = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var val2, src, clone;
args.forEach(function(obj) {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function(key) {
src = safeGetProperty(target, key);
val2 = safeGetProperty(obj, key);
if (val2 === target) {
return;
} else if (typeof val2 !== "object" || val2 === null) {
target[key] = val2;
return;
} else if (Array.isArray(val2)) {
target[key] = deepCloneArray(val2);
return;
} else if (isSpecificValue(val2)) {
target[key] = cloneSpecificValue(val2);
return;
} else if (typeof src !== "object" || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val2);
return;
} else {
target[key] = deepExtend(src, val2);
return;
}
});
});
return target;
};
}
});
// ../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js
var require_minimist = __commonJS({
"../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js"(exports2, module3) {
init_import_meta_url();
module3.exports = function(args, opts) {
if (!opts) opts = {};
var flags2 = { bools: {}, strings: {}, unknownFn: null };
if (typeof opts["unknown"] === "function") {
flags2.unknownFn = opts["unknown"];
}
if (typeof opts["boolean"] === "boolean" && opts["boolean"]) {
flags2.allBools = true;
} else {
[].concat(opts["boolean"]).filter(Boolean).forEach(function(key2) {
flags2.bools[key2] = true;
});
}
var aliases2 = {};
Object.keys(opts.alias || {}).forEach(function(key2) {
aliases2[key2] = [].concat(opts.alias[key2]);
aliases2[key2].forEach(function(x6) {
aliases2[x6] = [key2].concat(aliases2[key2].filter(function(y4) {
return x6 !== y4;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function(key2) {
flags2.strings[key2] = true;
if (aliases2[key2]) {
flags2.strings[aliases2[key2]] = true;
}
});
var defaults = opts["default"] || {};
var argv = { _: [] };
Object.keys(flags2.bools).forEach(function(key2) {
setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
});
var notFlags = [];
if (args.indexOf("--") !== -1) {
notFlags = args.slice(args.indexOf("--") + 1);
args = args.slice(0, args.indexOf("--"));
}
function argDefined(key2, arg2) {
return flags2.allBools && /^--[^=]+$/.test(arg2) || flags2.strings[key2] || flags2.bools[key2] || aliases2[key2];
}
__name(argDefined, "argDefined");
function setArg(key2, val2, arg2) {
if (arg2 && flags2.unknownFn && !argDefined(key2, arg2)) {
if (flags2.unknownFn(arg2) === false) return;
}
var value2 = !flags2.strings[key2] && isNumber(val2) ? Number(val2) : val2;
setKey(argv, key2.split("."), value2);
(aliases2[key2] || []).forEach(function(x6) {
setKey(argv, x6.split("."), value2);
});
}
__name(setArg, "setArg");
function setKey(obj, keys, value2) {
var o5 = obj;
for (var i6 = 0; i6 < keys.length - 1; i6++) {
var key2 = keys[i6];
if (isConstructorOrProto(o5, key2)) return;
if (o5[key2] === void 0) o5[key2] = {};
if (o5[key2] === Object.prototype || o5[key2] === Number.prototype || o5[key2] === String.prototype) o5[key2] = {};
if (o5[key2] === Array.prototype) o5[key2] = [];
o5 = o5[key2];
}
var key2 = keys[keys.length - 1];
if (isConstructorOrProto(o5, key2)) return;
if (o5 === Object.prototype || o5 === Number.prototype || o5 === String.prototype) o5 = {};
if (o5 === Array.prototype) o5 = [];
if (o5[key2] === void 0 || flags2.bools[key2] || typeof o5[key2] === "boolean") {
o5[key2] = value2;
} else if (Array.isArray(o5[key2])) {
o5[key2].push(value2);
} else {
o5[key2] = [o5[key2], value2];
}
}
__name(setKey, "setKey");
function aliasIsBoolean(key2) {
return aliases2[key2].some(function(x6) {
return flags2.bools[x6];
});
}
__name(aliasIsBoolean, "aliasIsBoolean");
for (var i5 = 0; i5 < args.length; i5++) {
var arg = args[i5];
if (/^--.+=/.test(arg)) {
var m6 = arg.match(/^--([^=]+)=([\s\S]*)$/);
var key = m6[1];
var value = m6[2];
if (flags2.bools[key]) {
value = value !== "false";
}
setArg(key, value, arg);
} else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
} else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i5 + 1];
if (next !== void 0 && !/^-/.test(next) && !flags2.bools[key] && !flags2.allBools && (aliases2[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i5++;
} else if (/^(true|false)$/.test(next)) {
setArg(key, next === "true", arg);
i5++;
} else {
setArg(key, flags2.strings[key] ? "" : true, arg);
}
} else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1, -1).split("");
var broken = false;
for (var j6 = 0; j6 < letters.length; j6++) {
var next = arg.slice(j6 + 2);
if (next === "-") {
setArg(letters[j6], next, arg);
continue;
}
if (/[A-Za-z]/.test(letters[j6]) && /=/.test(next)) {
setArg(letters[j6], next.split("=")[1], arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j6]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j6], next, arg);
broken = true;
break;
}
if (letters[j6 + 1] && letters[j6 + 1].match(/\W/)) {
setArg(letters[j6], arg.slice(j6 + 2), arg);
broken = true;
break;
} else {
setArg(letters[j6], flags2.strings[letters[j6]] ? "" : true, arg);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== "-") {
if (args[i5 + 1] && !/^(-|--)[^-]/.test(args[i5 + 1]) && !flags2.bools[key] && (aliases2[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i5 + 1], arg);
i5++;
} else if (args[i5 + 1] && /^(true|false)$/.test(args[i5 + 1])) {
setArg(key, args[i5 + 1] === "true", arg);
i5++;
} else {
setArg(key, flags2.strings[key] ? "" : true, arg);
}
}
} else {
if (!flags2.unknownFn || flags2.unknownFn(arg) !== false) {
argv._.push(
flags2.strings["_"] || !isNumber(arg) ? arg : Number(arg)
);
}
if (opts.stopEarly) {
argv._.push.apply(argv._, args.slice(i5 + 1));
break;
}
}
}
Object.keys(defaults).forEach(function(key2) {
if (!hasKey2(argv, key2.split("."))) {
setKey(argv, key2.split("."), defaults[key2]);
(aliases2[key2] || []).forEach(function(x6) {
setKey(argv, x6.split("."), defaults[key2]);
});
}
});
if (opts["--"]) {
argv["--"] = new Array();
notFlags.forEach(function(key2) {
argv["--"].push(key2);
});
} else {
notFlags.forEach(function(key2) {
argv._.push(key2);
});
}
return argv;
};
function hasKey2(obj, keys) {
var o5 = obj;
keys.slice(0, -1).forEach(function(key2) {
o5 = o5[key2] || {};
});
var key = keys[keys.length - 1];
return key in o5;
}
__name(hasKey2, "hasKey");
function isNumber(x6) {
if (typeof x6 === "number") return true;
if (/^0x[0-9a-f]+$/i.test(x6)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x6);
}
__name(isNumber, "isNumber");
function isConstructorOrProto(obj, key) {
return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
}
__name(isConstructorOrProto, "isConstructorOrProto");
}
});
// ../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js
var require_rc = __commonJS({
"../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js"(exports2, module3) {
init_import_meta_url();
var cc2 = require_utils3();
var join24 = require("path").join;
var deepExtend = require_deep_extend();
var etc = "/etc";
var win = process.platform === "win32";
var home = win ? process.env.USERPROFILE : process.env.HOME;
module3.exports = function(name2, defaults, argv, parse7) {
if ("string" !== typeof name2)
throw new Error("rc(name): name *must* be string");
if (!argv)
argv = require_minimist()(process.argv.slice(2));
defaults = ("string" === typeof defaults ? cc2.json(defaults) : defaults) || {};
parse7 = parse7 || cc2.parse;
var env6 = cc2.env(name2 + "_");
var configs = [defaults];
var configFiles = [];
function addConfigFile(file) {
if (configFiles.indexOf(file) >= 0) return;
var fileConfig = cc2.file(file);
if (fileConfig) {
configs.push(parse7(fileConfig));
configFiles.push(file);
}
}
__name(addConfigFile, "addConfigFile");
if (!win)
[
join24(etc, name2, "config"),
join24(etc, name2 + "rc")
].forEach(addConfigFile);
if (home)
[
join24(home, ".config", name2, "config"),
join24(home, ".config", name2),
join24(home, "." + name2, "config"),
join24(home, "." + name2 + "rc")
].forEach(addConfigFile);
addConfigFile(cc2.find("." + name2 + "rc"));
if (env6.config) addConfigFile(env6.config);
if (argv.config) addConfigFile(argv.config);
return deepExtend.apply(null, configs.concat([
env6,
argv,
configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : void 0
]));
};
}
});
// ../../node_modules/.pnpm/registry-url@3.1.0/node_modules/registry-url/index.js
var require_registry_url = __commonJS({
"../../node_modules/.pnpm/registry-url@3.1.0/node_modules/registry-url/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = function(scope) {
var rc = require_rc()("npm", { registry: "https://registry.npmjs.org/" });
var url4 = rc[scope + ":registry"] || rc.registry;
return url4.slice(-1) === "/" ? url4 : url4 + "/";
};
}
});
// ../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js
var require_safe_buffer = __commonJS({
"../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports2, module3) {
init_import_meta_url();
var buffer = require("buffer");
var Buffer7 = buffer.Buffer;
function copyProps(src, dst) {
for (var key in src) {
dst[key] = src[key];
}
}
__name(copyProps, "copyProps");
if (Buffer7.from && Buffer7.alloc && Buffer7.allocUnsafe && Buffer7.allocUnsafeSlow) {
module3.exports = buffer;
} else {
copyProps(buffer, exports2);
exports2.Buffer = SafeBuffer;
}
function SafeBuffer(arg, encodingOrOffset, length) {
return Buffer7(arg, encodingOrOffset, length);
}
__name(SafeBuffer, "SafeBuffer");
SafeBuffer.prototype = Object.create(Buffer7.prototype);
copyProps(Buffer7, SafeBuffer);
SafeBuffer.from = function(arg, encodingOrOffset, length) {
if (typeof arg === "number") {
throw new TypeError("Argument must not be a number");
}
return Buffer7(arg, encodingOrOffset, length);
};
SafeBuffer.alloc = function(size, fill2, encoding) {
if (typeof size !== "number") {
throw new TypeError("Argument must be a number");
}
var buf = Buffer7(size);
if (fill2 !== void 0) {
if (typeof encoding === "string") {
buf.fill(fill2, encoding);
} else {
buf.fill(fill2);
}
} else {
buf.fill(0);
}
return buf;
};
SafeBuffer.allocUnsafe = function(size) {
if (typeof size !== "number") {
throw new TypeError("Argument must be a number");
}
return Buffer7(size);
};
SafeBuffer.allocUnsafeSlow = function(size) {
if (typeof size !== "number") {
throw new TypeError("Argument must be a number");
}
return buffer.SlowBuffer(size);
};
}
});
// ../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/base64.js
var require_base64 = __commonJS({
"../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/base64.js"(exports2, module3) {
init_import_meta_url();
var safeBuffer = require_safe_buffer().Buffer;
function decodeBase64(base642) {
return safeBuffer.from(base642, "base64").toString("utf8");
}
__name(decodeBase64, "decodeBase64");
function encodeBase64(string) {
return safeBuffer.from(string, "utf8").toString("base64");
}
__name(encodeBase64, "encodeBase64");
module3.exports = {
decodeBase64,
encodeBase64
};
}
});
// ../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/index.js
var require_registry_auth_token = __commonJS({
"../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/index.js"(exports2, module3) {
init_import_meta_url();
var url4 = require("url");
var base642 = require_base64();
var decodeBase64 = base642.decodeBase64;
var encodeBase64 = base642.encodeBase64;
var tokenKey = ":_authToken";
var userKey = ":username";
var passwordKey = ":_password";
module3.exports = function() {
var checkUrl2;
var options;
if (arguments.length >= 2) {
checkUrl2 = arguments[0];
options = arguments[1];
} else if (typeof arguments[0] === "string") {
checkUrl2 = arguments[0];
} else {
options = arguments[0];
}
options = options || {};
options.npmrc = options.npmrc || require_rc()("npm", { registry: "https://registry.npmjs.org/" });
checkUrl2 = checkUrl2 || options.npmrc.registry;
return getRegistryAuthInfo(checkUrl2, options) || getLegacyAuthInfo(options.npmrc);
};
function getRegistryAuthInfo(checkUrl2, options) {
var parsed = url4.parse(checkUrl2, false, true);
var pathname;
while (pathname !== "/" && parsed.pathname !== pathname) {
pathname = parsed.pathname || "/";
var regUrl = "//" + parsed.host + pathname.replace(/\/$/, "");
var authInfo = getAuthInfoForUrl(regUrl, options.npmrc);
if (authInfo) {
return authInfo;
}
if (!options.recursive) {
return /\/$/.test(checkUrl2) ? void 0 : getRegistryAuthInfo(url4.resolve(checkUrl2, "."), options);
}
parsed.pathname = url4.resolve(normalizePath2(pathname), "..") || "/";
}
return void 0;
}
__name(getRegistryAuthInfo, "getRegistryAuthInfo");
function getLegacyAuthInfo(npmrc) {
if (npmrc._auth) {
return { token: npmrc._auth, type: "Basic" };
}
return void 0;
}
__name(getLegacyAuthInfo, "getLegacyAuthInfo");
function normalizePath2(path72) {
return path72[path72.length - 1] === "/" ? path72 : path72 + "/";
}
__name(normalizePath2, "normalizePath");
function getAuthInfoForUrl(regUrl, npmrc) {
var bearerAuth = getBearerToken(npmrc[regUrl + tokenKey] || npmrc[regUrl + "/" + tokenKey]);
if (bearerAuth) {
return bearerAuth;
}
var username = npmrc[regUrl + userKey] || npmrc[regUrl + "/" + userKey];
var password = npmrc[regUrl + passwordKey] || npmrc[regUrl + "/" + passwordKey];
var basicAuth = getTokenForUsernameAndPassword(username, password);
if (basicAuth) {
return basicAuth;
}
return void 0;
}
__name(getAuthInfoForUrl, "getAuthInfoForUrl");
function getBearerToken(tok) {
if (!tok) {
return void 0;
}
var token = tok.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
return process.env[envVar];
});
return { token, type: "Bearer" };
}
__name(getBearerToken, "getBearerToken");
function getTokenForUsernameAndPassword(username, password) {
if (!username || !password) {
return void 0;
}
var pass2 = decodeBase64(password.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
return process.env[envVar];
}));
var token = encodeBase64(username + ":" + pass2);
return {
token,
type: "Basic",
password: pass2,
username
};
}
__name(getTokenForUsernameAndPassword, "getTokenForUsernameAndPassword");
}
});
// ../../node_modules/.pnpm/update-check@1.5.4/node_modules/update-check/index.js
var require_update_check = __commonJS({
"../../node_modules/.pnpm/update-check@1.5.4/node_modules/update-check/index.js"(exports2, module3) {
init_import_meta_url();
var { URL: URL7 } = require("url");
var { join: join24 } = require("path");
var fs24 = require("fs");
var { promisify: promisify3 } = require("util");
var { tmpdir } = require("os");
var registryUrl = require_registry_url();
var writeFile10 = promisify3(fs24.writeFile);
var mkdir5 = promisify3(fs24.mkdir);
var readFile17 = promisify3(fs24.readFile);
var compareVersions = /* @__PURE__ */ __name((a5, b6) => a5.localeCompare(b6, "en-US", { numeric: true }), "compareVersions");
var encode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/^%40/, "@"), "encode");
var getFile = /* @__PURE__ */ __name(async (details, distTag) => {
const rootDir = tmpdir();
const subDir = join24(rootDir, "update-check");
if (!fs24.existsSync(subDir)) {
await mkdir5(subDir);
}
let name2 = `${details.name}-${distTag}.json`;
if (details.scope) {
name2 = `${details.scope}-${name2}`;
}
return join24(subDir, name2);
}, "getFile");
var evaluateCache = /* @__PURE__ */ __name(async (file, time, interval) => {
if (fs24.existsSync(file)) {
const content = await readFile17(file, "utf8");
const { lastUpdate, latest } = JSON.parse(content);
const nextCheck = lastUpdate + interval;
if (nextCheck > time) {
return {
shouldCheck: false,
latest
};
}
}
return {
shouldCheck: true,
latest: null
};
}, "evaluateCache");
var updateCache = /* @__PURE__ */ __name(async (file, latest, lastUpdate) => {
const content = JSON.stringify({
latest,
lastUpdate
});
await writeFile10(file, content, "utf8");
}, "updateCache");
var loadPackage = /* @__PURE__ */ __name((url4, authInfo) => new Promise((resolve25, reject) => {
const options = {
host: url4.hostname,
path: url4.pathname,
port: url4.port,
headers: {
accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"
},
timeout: 2e3
};
if (authInfo) {
options.headers.authorization = `${authInfo.type} ${authInfo.token}`;
}
const { get: get2 } = url4.protocol === "https:" ? require("https") : require("http");
get2(options, (response) => {
const { statusCode } = response;
if (statusCode !== 200) {
const error2 = new Error(`Request failed with code ${statusCode}`);
error2.code = statusCode;
reject(error2);
response.resume();
return;
}
let rawData = "";
response.setEncoding("utf8");
response.on("data", (chunk) => {
rawData += chunk;
});
response.on("end", () => {
try {
const parsedData = JSON.parse(rawData);
resolve25(parsedData);
} catch (e7) {
reject(e7);
}
});
}).on("error", reject).on("timeout", reject);
}), "loadPackage");
var getMostRecent = /* @__PURE__ */ __name(async ({ full, scope }, distTag) => {
const regURL = registryUrl(scope);
const url4 = new URL7(full, regURL);
let spec = null;
try {
spec = await loadPackage(url4);
} catch (err) {
if (err.code && String(err.code).startsWith(4)) {
const registryAuthToken = require_registry_auth_token();
const authInfo = registryAuthToken(regURL, { recursive: true });
spec = await loadPackage(url4, authInfo);
} else {
throw err;
}
}
const version5 = spec["dist-tags"][distTag];
if (!version5) {
throw new Error(`Distribution tag ${distTag} is not available`);
}
return version5;
}, "getMostRecent");
var defaultConfig = {
interval: 36e5,
distTag: "latest"
};
var getDetails = /* @__PURE__ */ __name((name2) => {
const spec = {
full: encode(name2)
};
if (name2.includes("/")) {
const parts = name2.split("/");
spec.scope = parts[0];
spec.name = parts[1];
} else {
spec.scope = null;
spec.name = name2;
}
return spec;
}, "getDetails");
module3.exports = async (pkg, config) => {
if (typeof pkg !== "object") {
throw new Error("The first parameter should be your package.json file content");
}
const details = getDetails(pkg.name);
const time = Date.now();
const { distTag, interval } = Object.assign({}, defaultConfig, config);
const file = await getFile(details, distTag);
let latest = null;
let shouldCheck = true;
({ shouldCheck, latest } = await evaluateCache(file, time, interval));
if (shouldCheck) {
latest = await getMostRecent(details, distTag);
await updateCache(file, latest, time);
}
const comparision = compareVersions(pkg.version, latest);
if (comparision === -1) {
return {
latest,
fromCache: !shouldCheck
};
}
return null;
};
}
});
// src/update-check.ts
async function doUpdateCheck() {
let update = null;
const pkg = { name, version };
try {
update = await (0, import_update_check.default)(pkg, {
distTag: pkg.version.startsWith("0.0.0") ? "beta" : "latest"
});
} catch {
}
return update?.latest;
}
function updateCheck() {
return updateCheckPromise ??= doUpdateCheck();
}
var import_update_check, updateCheckPromise;
var init_update_check = __esm({
"src/update-check.ts"() {
init_import_meta_url();
import_update_check = __toESM(require_update_check());
init_package();
__name(doUpdateCheck, "doUpdateCheck");
__name(updateCheck, "updateCheck");
}
});
// src/vectorize/fetcher.ts
function MakeVectorizeFetcher(complianceConfig, indexId) {
return async function(request4) {
const accountId = await getAccountId(complianceConfig);
request4.headers.delete("Host");
request4.headers.delete("Content-Length");
let op = request4.url.split("/").pop() || "";
op = URL_SUBSTITUTIONS.get(op) || op;
const base = `/accounts/${accountId}/vectorize/v2/indexes/${indexId}/`;
const url4 = base + op;
const res = await performApiFetch(complianceConfig, url4, {
method: request4.method,
headers: Object.fromEntries(request4.headers.entries()),
body: request4.body,
duplex: "half"
});
const respHeaders = new import_miniflare6.Headers(res.headers);
respHeaders.delete("Host");
respHeaders.delete("Content-Length");
const apiResponse = await res.json();
const newResponse = apiResponse.success ? apiResponse.result : {
error: apiResponse.errors[0].message,
code: apiResponse.errors[0].code
};
return new import_miniflare6.Response(JSON.stringify(newResponse), {
status: res.status,
headers: respHeaders
});
};
}
var import_miniflare6, EXTERNAL_VECTORIZE_WORKER_NAME, EXTERNAL_VECTORIZE_WORKER_SCRIPT, URL_SUBSTITUTIONS;
var init_fetcher3 = __esm({
"src/vectorize/fetcher.ts"() {
init_import_meta_url();
import_miniflare6 = require("miniflare");
init_internal();
init_user2();
EXTERNAL_VECTORIZE_WORKER_NAME = "__WRANGLER_EXTERNAL_VECTORIZE_WORKER";
EXTERNAL_VECTORIZE_WORKER_SCRIPT = `
import makeBinding from 'cloudflare-internal:vectorize-api'
export default function (env) {
return makeBinding({
fetcher: env.FETCHER,
indexId: env.INDEX_ID,
indexVersion: env.INDEX_VERSION,
useNdJson: true,
});
}
`;
URL_SUBSTITUTIONS = /* @__PURE__ */ new Map([
["getByIds", "get_by_ids"],
["deleteByIds", "delete_by_ids"]
]);
__name(MakeVectorizeFetcher, "MakeVectorizeFetcher");
}
});
// src/dev/class-names-sqlite.ts
function getClassNamesWhichUseSQLite(migrations) {
const classNamesWhichUseSQLite = /* @__PURE__ */ new Map();
(migrations || []).forEach((migration) => {
migration.deleted_classes?.forEach((deleted_class) => {
if (!classNamesWhichUseSQLite.delete(deleted_class)) {
throw new UserError(
`Cannot apply deleted_classes migration to non-existent class ${deleted_class}`
);
}
});
migration.renamed_classes?.forEach(({ from, to }) => {
const useSQLite = classNamesWhichUseSQLite.get(from);
if (useSQLite === void 0) {
throw new UserError(
`Cannot apply renamed_classes migration to non-existent class ${from}`
);
} else {
classNamesWhichUseSQLite.delete(from);
classNamesWhichUseSQLite.set(to, useSQLite);
}
});
migration.new_classes?.forEach((new_class) => {
if (classNamesWhichUseSQLite.has(new_class)) {
throw new UserError(
`Cannot apply new_classes migration to existing class ${new_class}`
);
} else {
classNamesWhichUseSQLite.set(new_class, false);
}
});
migration.new_sqlite_classes?.forEach((new_class) => {
if (classNamesWhichUseSQLite.has(new_class)) {
throw new UserError(
`Cannot apply new_sqlite_classes migration to existing class ${new_class}`
);
} else {
classNamesWhichUseSQLite.set(new_class, true);
}
});
});
return classNamesWhichUseSQLite;
}
var init_class_names_sqlite = __esm({
"src/dev/class-names-sqlite.ts"() {
init_import_meta_url();
init_errors();
__name(getClassNamesWhichUseSQLite, "getClassNamesWhichUseSQLite");
}
});
// ../workers-shared/utils/constants.ts
var PATH_HASH_SIZE, CONTENT_HASH_SIZE, TAIL_SIZE, ENTRY_SIZE, MAX_ASSET_COUNT2, MAX_ASSET_SIZE2, CF_ASSETS_IGNORE_FILENAME, REDIRECTS_FILENAME, HEADERS_FILENAME;
var init_constants2 = __esm({
"../workers-shared/utils/constants.ts"() {
init_import_meta_url();
PATH_HASH_SIZE = 16;
CONTENT_HASH_SIZE = 16;
TAIL_SIZE = 8;
ENTRY_SIZE = PATH_HASH_SIZE + CONTENT_HASH_SIZE + TAIL_SIZE;
MAX_ASSET_COUNT2 = 2e4;
MAX_ASSET_SIZE2 = 25 * 1024 * 1024;
CF_ASSETS_IGNORE_FILENAME = ".assetsignore";
REDIRECTS_FILENAME = "_redirects";
HEADERS_FILENAME = "_headers";
}
});
// ../../node_modules/.pnpm/zod@3.22.3/node_modules/zod/lib/index.mjs
function setErrorMap(map2) {
overrideErrorMap = map2;
}
function getErrorMap() {
return overrideErrorMap;
}
function addIssueToContext(ctx, issueData) {
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
// then global default map
].filter((x6) => !!x6)
});
ctx.common.issues.push(issue);
}
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 = /* @__PURE__ */ __name((iss, ctx) => {
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
if (typeof ctx.data === "undefined") {
return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
}
return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
}, "customMap");
return { errorMap: customMap, description };
}
function isValidIP(ip, version5) {
if ((version5 === "v4" || !version5) && ipv4Regex.test(ip)) {
return true;
}
if ((version5 === "v6" || !version5) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function floatSafeRemainder(val2, step) {
const valDecCount = (val2.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = parseInt(val2.toFixed(decCount).replace(".", ""));
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / Math.pow(10, decCount);
}
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: /* @__PURE__ */ __name(() => newShape, "shape")
});
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
function mergeValues(a5, b6) {
const aType = getParsedType(a5);
const bType = getParsedType(b6);
if (a5 === b6) {
return { valid: true, data: a5 };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b6);
const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a5, ...b6 };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a5[key], b6[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a5.length !== b6.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0; index < a5.length; index++) {
const itemA = a5[index];
const itemB = b6[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b6) {
return { valid: true, data: a5 };
} else {
return { valid: false };
}
}
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, emailRegex, emojiRegex2, ipv4Regex, ipv6Regex, datetimeRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, custom, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER, z2;
var init_lib4 = __esm({
"../../node_modules/.pnpm/zod@3.22.3/node_modules/zod/lib/index.mjs"() {
init_import_meta_url();
(function(util3) {
util3.assertEqual = (val2) => val2;
function assertIs(_arg) {
}
__name(assertIs, "assertIs");
util3.assertIs = assertIs;
function assertNever2(_x2) {
throw new Error();
}
__name(assertNever2, "assertNever");
util3.assertNever = assertNever2;
util3.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util3.getValidEnumValues = (obj) => {
const validKeys = util3.objectKeys(obj).filter((k6) => typeof obj[obj[k6]] !== "number");
const filtered = {};
for (const k6 of validKeys) {
filtered[k6] = obj[k6];
}
return util3.objectValues(filtered);
};
util3.objectValues = (obj) => {
return util3.objectKeys(obj).map(function(e7) {
return obj[e7];
});
};
util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util3.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return void 0;
};
util3.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && isFinite(val2) && Math.floor(val2) === val2;
function joinValues(array, separator = " | ") {
return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
}
__name(joinValues, "joinValues");
util3.joinValues = joinValues;
util3.jsonStringifyReplacer = (_4, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
// second overwrites first
};
};
})(objectUtil || (objectUtil = {}));
ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
getParsedType = /* @__PURE__ */ __name((data) => {
const t7 = typeof data;
switch (t7) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
}, "getParsedType");
ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
quotelessJson = /* @__PURE__ */ __name((obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
}, "quotelessJson");
ZodError = class extends Error {
static {
__name(this, "ZodError");
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
get errors() {
return this.issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = /* @__PURE__ */ __name((error2) => {
for (const issue of error2.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i5 = 0;
while (i5 < issue.path.length) {
const el = issue.path[i5];
const terminal = i5 === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i5++;
}
}
}
}, "processError");
processError(this);
return fieldErrors;
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error2 = new ZodError(issues);
return error2;
};
errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
}, "errorMap");
overrideErrorMap = errorMap;
__name(setErrorMap, "setErrorMap");
__name(getErrorMap, "getErrorMap");
makeIssue = /* @__PURE__ */ __name((params) => {
const { data, path: path72, errorMaps, issueData } = params;
const fullPath = [...path72, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
let errorMessage = "";
const maps = errorMaps.filter((m6) => !!m6).slice().reverse();
for (const map2 of maps) {
errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: issueData.message || errorMessage
};
}, "makeIssue");
EMPTY_PATH = [];
__name(addIssueToContext, "addIssueToContext");
ParseStatus = class _ParseStatus {
static {
__name(this, "ParseStatus");
}
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status2, results) {
const arrayValue = [];
for (const s5 of results) {
if (s5.status === "aborted")
return INVALID;
if (s5.status === "dirty")
status2.dirty();
arrayValue.push(s5.value);
}
return { status: status2.value, value: arrayValue };
}
static async mergeObjectAsync(status2, pairs) {
const syncPairs = [];
for (const pair of pairs) {
syncPairs.push({
key: await pair.key,
value: await pair.value
});
}
return _ParseStatus.mergeObjectSync(status2, syncPairs);
}
static mergeObjectSync(status2, 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")
status2.dirty();
if (value.status === "dirty")
status2.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status2.value, value: finalObject };
}
};
INVALID = Object.freeze({
status: "aborted"
});
DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
isAborted = /* @__PURE__ */ __name((x6) => x6.status === "aborted", "isAborted");
isDirty = /* @__PURE__ */ __name((x6) => x6.status === "dirty", "isDirty");
isValid = /* @__PURE__ */ __name((x6) => x6.status === "valid", "isValid");
isAsync = /* @__PURE__ */ __name((x6) => typeof Promise !== "undefined" && x6 instanceof Promise, "isAsync");
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
ParseInputLazyPath = class {
static {
__name(this, "ParseInputLazyPath");
}
constructor(parent, value, path72, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path72;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (this._key instanceof Array) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
};
handleResult = /* @__PURE__ */ __name((ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error2 = new ZodError(ctx.common.issues);
this._error = error2;
return this._error;
}
};
}
}, "handleResult");
__name(processCreateParams, "processCreateParams");
ZodType = class {
static {
__name(this, "ZodType");
}
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
var _a4;
const ctx = {
common: {
issues: [],
async: (_a4 = params === null || params === void 0 ? void 0 : params.async) !== null && _a4 !== void 0 ? _a4 : false,
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
async: true
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult2 = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult2) ? maybeAsyncResult2 : Promise.resolve(maybeAsyncResult2));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = /* @__PURE__ */ __name((val2) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val2);
} else {
return message;
}
}, "getIssueProperties");
return this._refinement((val2, ctx) => {
const result = check(val2);
const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val2)
}), "setError");
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val2, ctx) => {
if (!check(val2)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
cuidRegex = /^c[^\s-]{8,}$/i;
cuid2Regex = /^[a-z][a-z0-9]*$/;
ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
emojiRegex2 = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
ipv4Regex = /^(((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}))$/;
ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
datetimeRegex = /* @__PURE__ */ __name((args) => {
if (args.precision) {
if (args.offset) {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
} else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
}
} else if (args.precision === 0) {
if (args.offset) {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
} else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
}
} else {
if (args.offset) {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
} else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
}
}
}, "datetimeRegex");
__name(isValidIP, "isValidIP");
ZodString = class _ZodString extends ZodType {
static {
__name(this, "ZodString");
}
constructor() {
super(...arguments);
this._regex = (regex2, validation2, message) => this.refinement((data) => regex2.test(data), {
validation: validation2,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
this.trim = () => new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
this.toLowerCase = () => new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
this.toUpperCase = () => new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(
ctx2,
{
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
}
//
);
return INVALID;
}
const status2 = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status2.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex2.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch (_a4) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status2.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status2.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status2.dirty();
}
} else if (check.kind === "datetime") {
const regex2 = datetimeRegex(check);
if (!regex2.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status2.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status2.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status2.value, value: input.data };
}
_addCheck(check) {
return new _ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
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) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a4;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
offset: (_a4 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a4 !== void 0 ? _a4 : false,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
regex(regex2, message) {
return this._addCheck({
kind: "regex",
regex: regex2,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options === null || options === void 0 ? void 0 : options.position,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
get isDatetime() {
return !!this._def.checks.find((ch2) => ch2.kind === "datetime");
}
get isEmail() {
return !!this._def.checks.find((ch2) => ch2.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch2) => ch2.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch2) => ch2.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch2) => ch2.kind === "uuid");
}
get isCUID() {
return !!this._def.checks.find((ch2) => ch2.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch2) => ch2.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch2) => ch2.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch2) => ch2.kind === "ip");
}
get minLength() {
let min = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "min") {
if (min === null || ch2.value > min)
min = ch2.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "max") {
if (max === null || ch2.value < max)
max = ch2.value;
}
}
return max;
}
};
ZodString.create = (params) => {
var _a4;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a4 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a4 !== void 0 ? _a4 : false,
...processCreateParams(params)
});
};
__name(floatSafeRemainder, "floatSafeRemainder");
ZodNumber = class _ZodNumber extends ZodType {
static {
__name(this, "ZodNumber");
}
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status2 = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status2.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status2.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status2.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new _ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "min") {
if (min === null || ch2.value > min)
min = ch2.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "max") {
if (max === null || ch2.value < max)
max = ch2.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch2) => ch2.kind === "int" || ch2.kind === "multipleOf" && util.isInteger(ch2.value));
}
get isFinite() {
let max = null, min = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "finite" || ch2.kind === "int" || ch2.kind === "multipleOf") {
return true;
} else if (ch2.kind === "min") {
if (min === null || ch2.value > min)
min = ch2.value;
} else if (ch2.kind === "max") {
if (max === null || ch2.value < max)
max = ch2.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
ZodBigInt = class _ZodBigInt extends ZodType {
static {
__name(this, "ZodBigInt");
}
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
input.data = BigInt(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status2 = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status2.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status2.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status2.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new _ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "min") {
if (min === null || ch2.value > min)
min = ch2.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "max") {
if (max === null || ch2.value < max)
max = ch2.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _a4;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a4 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a4 !== void 0 ? _a4 : false,
...processCreateParams(params)
});
};
ZodBoolean = class extends ZodType {
static {
__name(this, "ZodBoolean");
}
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
ZodDate = class _ZodDate extends ZodType {
static {
__name(this, "ZodDate");
}
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status2 = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status2.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status2.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status2.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new _ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "min") {
if (min === null || ch2.value > min)
min = ch2.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch2 of this._def.checks) {
if (ch2.kind === "max") {
if (max === null || ch2.value < max)
max = ch2.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
ZodSymbol = class extends ZodType {
static {
__name(this, "ZodSymbol");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
ZodUndefined = class extends ZodType {
static {
__name(this, "ZodUndefined");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
ZodNull = class extends ZodType {
static {
__name(this, "ZodNull");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
ZodAny = class extends ZodType {
static {
__name(this, "ZodAny");
}
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
ZodUnknown = class extends ZodType {
static {
__name(this, "ZodUnknown");
}
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
ZodNever = class extends ZodType {
static {
__name(this, "ZodNever");
}
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
ZodVoid = class extends ZodType {
static {
__name(this, "ZodVoid");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
ZodArray = class _ZodArray extends ZodType {
static {
__name(this, "ZodArray");
}
_parse(input) {
const { ctx, status: status2 } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status2.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status2.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status2.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i5) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i5));
})).then((result2) => {
return ParseStatus.mergeArray(status2, result2);
});
}
const result = [...ctx.data].map((item, i5) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i5));
});
return ParseStatus.mergeArray(status2, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new _ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new _ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new _ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
__name(deepPartialify, "deepPartialify");
ZodObject = class _ZodObject extends ZodType {
static {
__name(this, "ZodObject");
}
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
return this._cached = { shape, keys };
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status: status2, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status2.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;
syncPairs.push({
key,
value: await pair.value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status2, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status2, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? {
errorMap: /* @__PURE__ */ __name((issue, ctx) => {
var _a4, _b2, _c3, _d2;
const defaultError = (_c3 = (_b2 = (_a4 = this._def).errorMap) === null || _b2 === void 0 ? void 0 : _b2.call(_a4, issue, ctx).message) !== null && _c3 !== void 0 ? _c3 : ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: (_d2 = errorUtil.errToObj(message).message) !== null && _d2 !== void 0 ? _d2 : defaultError
};
return {
message: defaultError
};
}, "errorMap")
} : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new _ZodObject({
...this._def,
shape: /* @__PURE__ */ __name(() => ({
...this._def.shape(),
...augmentation
}), "shape")
});
}
/**
* 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: /* @__PURE__ */ __name(() => ({
...this._def.shape(),
...merging._def.shape()
}), "shape"),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new _ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
util.objectKeys(mask).forEach((key) => {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
});
return new _ZodObject({
...this._def,
shape: /* @__PURE__ */ __name(() => shape, "shape")
});
}
omit(mask) {
const shape = {};
util.objectKeys(this.shape).forEach((key) => {
if (!mask[key]) {
shape[key] = this.shape[key];
}
});
return new _ZodObject({
...this._def,
shape: /* @__PURE__ */ __name(() => shape, "shape")
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
});
return new _ZodObject({
...this._def,
shape: /* @__PURE__ */ __name(() => newShape, "shape")
});
}
required(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
});
return new _ZodObject({
...this._def,
shape: /* @__PURE__ */ __name(() => newShape, "shape")
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: /* @__PURE__ */ __name(() => shape, "shape"),
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: /* @__PURE__ */ __name(() => shape, "shape"),
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodUnion = class extends ZodType {
static {
__name(this, "ZodUnion");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
__name(handleResults, "handleResults");
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types3, params) => {
return new ZodUnion({
options: types3,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
getDiscriminator = /* @__PURE__ */ __name((type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return Object.keys(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [void 0];
} else if (type instanceof ZodNull) {
return [null];
} else {
return null;
}
}, "getDiscriminator");
ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
static {
__name(this, "ZodDiscriminatedUnion");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new _ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
__name(mergeValues, "mergeValues");
ZodIntersection = class extends ZodType {
static {
__name(this, "ZodIntersection");
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status2.dirty();
}
return { status: status2.value, value: merged.data };
}, "handleParsed");
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(([left2, right2]) => handleParsed(left2, right2));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
};
ZodIntersection.create = (left2, right2, params) => {
return new ZodIntersection({
left: left2,
right: right2,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
ZodTuple = class _ZodTuple extends ZodType {
static {
__name(this, "ZodTuple");
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status2.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((x6) => !!x6);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status2, results);
});
} else {
return ParseStatus.mergeArray(status2, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new _ZodTuple({
...this._def,
rest
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
ZodRecord = class _ZodRecord extends ZodType {
static {
__name(this, "ZodRecord");
}
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status2, pairs);
} else {
return ParseStatus.mergeObjectSync(status2, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new _ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
ZodMap = class extends ZodType {
static {
__name(this, "ZodMap");
}
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], 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") {
status2.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status2.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") {
status2.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status2.value, value: finalMap };
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
ZodSet = class _ZodSet extends ZodType {
static {
__name(this, "ZodSet");
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status2.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status2.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")
status2.dirty();
parsedSet.add(element.value);
}
return { status: status2.value, value: parsedSet };
}
__name(finalizeSet, "finalizeSet");
const elements = [...ctx.data.values()].map((item, i5) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i5)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new _ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new _ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
ZodFunction = class _ZodFunction extends ZodType {
static {
__name(this, "ZodFunction");
}
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error2) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x6) => !!x6),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error2
}
});
}
__name(makeArgsIssue, "makeArgsIssue");
function makeReturnsIssue(returns, error2) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x6) => !!x6),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error2
}
});
}
__name(makeReturnsIssue, "makeReturnsIssue");
const params = { errorMap: ctx.common.contextualErrorMap };
const fn2 = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error2 = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e7) => {
error2.addIssue(makeArgsIssue(args, e7));
throw error2;
});
const result = await Reflect.apply(fn2, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e7) => {
error2.addIssue(makeReturnsIssue(result, e7));
throw error2;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn2, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new _ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new _ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new _ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
};
ZodLazy = class extends ZodType {
static {
__name(this, "ZodLazy");
}
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
ZodLiteral = class extends ZodType {
static {
__name(this, "ZodLiteral");
}
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
__name(createZodEnum, "createZodEnum");
ZodEnum = class _ZodEnum extends ZodType {
static {
__name(this, "ZodEnum");
}
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (this._def.values.indexOf(input.data) === -1) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val2 of this._def.values) {
enumValues[val2] = val2;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val2 of this._def.values) {
enumValues[val2] = val2;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val2 of this._def.values) {
enumValues[val2] = val2;
}
return enumValues;
}
extract(values) {
return _ZodEnum.create(values);
}
exclude(values) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
}
};
ZodEnum.create = createZodEnum;
ZodNativeEnum = class extends ZodType {
static {
__name(this, "ZodNativeEnum");
}
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (nativeEnumValues.indexOf(input.data) === -1) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
ZodPromise = class extends ZodType {
static {
__name(this, "ZodPromise");
}
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
ZodEffects = class extends ZodType {
static {
__name(this, "ZodEffects");
}
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: /* @__PURE__ */ __name((arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status2.abort();
} else {
status2.dirty();
}
}, "addIssue"),
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.issues.length) {
return {
status: "dirty",
value: ctx.data
};
}
if (ctx.common.async) {
return Promise.resolve(processed).then((processed2) => {
return this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
});
} else {
return this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
}
}
if (effect.type === "refinement") {
const executeRefinement = /* @__PURE__ */ __name((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;
}, "executeRefinement");
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")
status2.dirty();
executeRefinement(inner.value);
return { status: status2.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")
status2.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status2.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return base;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status2.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return base;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status2.value, value: result }));
});
}
}
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
ZodOptional = class extends ZodType {
static {
__name(this, "ZodOptional");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
ZodNullable = class extends ZodType {
static {
__name(this, "ZodNullable");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
ZodDefault = class extends ZodType {
static {
__name(this, "ZodDefault");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
ZodCatch = class extends ZodType {
static {
__name(this, "ZodCatch");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
ZodNaN = class extends ZodType {
static {
__name(this, "ZodNaN");
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
BRAND = Symbol("zod_brand");
ZodBranded = class extends ZodType {
static {
__name(this, "ZodBranded");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
ZodPipeline = class _ZodPipeline extends ZodType {
static {
__name(this, "ZodPipeline");
}
_parse(input) {
const { status: status2, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = /* @__PURE__ */ __name(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") {
status2.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}, "handleAsync");
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") {
status2.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a5, b6) {
return new _ZodPipeline({
in: a5,
out: b6,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
ZodReadonly = class extends ZodType {
static {
__name(this, "ZodReadonly");
}
_parse(input) {
const result = this._def.innerType._parse(input);
if (isValid(result)) {
result.value = Object.freeze(result.value);
}
return result;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
custom = /* @__PURE__ */ __name((check, params = {}, fatal) => {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a4, _b2;
if (!check(data)) {
const p6 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const _fatal = (_b2 = (_a4 = p6.fatal) !== null && _a4 !== void 0 ? _a4 : fatal) !== null && _b2 !== void 0 ? _b2 : true;
const p22 = typeof p6 === "string" ? { message: p6 } : p6;
ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
}
});
return ZodAny.create();
}, "custom");
late = {
object: ZodObject.lazycreate
};
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
instanceOfType = /* @__PURE__ */ __name((cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params), "instanceOfType");
stringType = ZodString.create;
numberType = ZodNumber.create;
nanType = ZodNaN.create;
bigIntType = ZodBigInt.create;
booleanType = ZodBoolean.create;
dateType = ZodDate.create;
symbolType = ZodSymbol.create;
undefinedType = ZodUndefined.create;
nullType = ZodNull.create;
anyType = ZodAny.create;
unknownType = ZodUnknown.create;
neverType = ZodNever.create;
voidType = ZodVoid.create;
arrayType = ZodArray.create;
objectType = ZodObject.create;
strictObjectType = ZodObject.strictCreate;
unionType = ZodUnion.create;
discriminatedUnionType = ZodDiscriminatedUnion.create;
intersectionType = ZodIntersection.create;
tupleType = ZodTuple.create;
recordType = ZodRecord.create;
mapType = ZodMap.create;
setType = ZodSet.create;
functionType = ZodFunction.create;
lazyType = ZodLazy.create;
literalType = ZodLiteral.create;
enumType = ZodEnum.create;
nativeEnumType = ZodNativeEnum.create;
promiseType = ZodPromise.create;
effectsType = ZodEffects.create;
optionalType = ZodOptional.create;
nullableType = ZodNullable.create;
preprocessType = ZodEffects.createWithPreprocess;
pipelineType = ZodPipeline.create;
ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
coerce = {
string: /* @__PURE__ */ __name((arg) => ZodString.create({ ...arg, coerce: true }), "string"),
number: /* @__PURE__ */ __name((arg) => ZodNumber.create({ ...arg, coerce: true }), "number"),
boolean: /* @__PURE__ */ __name((arg) => ZodBoolean.create({
...arg,
coerce: true
}), "boolean"),
bigint: /* @__PURE__ */ __name((arg) => ZodBigInt.create({ ...arg, coerce: true }), "bigint"),
date: /* @__PURE__ */ __name((arg) => ZodDate.create({ ...arg, coerce: true }), "date")
};
NEVER = INVALID;
z2 = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
"enum": enumType,
"function": functionType,
"instanceof": instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
"null": nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
"undefined": undefinedType,
union: unionType,
unknown: unknownType,
"void": voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError
});
}
});
// ../workers-shared/utils/types.ts
var InternalConfigSchema, StaticRoutingSchema, RouterConfigSchema, EyeballRouterConfigSchema, MetadataStaticRedirectEntry, MetadataRedirectEntry, MetadataStaticRedirects, MetadataRedirects, MetadataHeaderEntry, MetadataHeaders, RedirectsSchema, HeadersSchema, AssetConfigSchema;
var init_types2 = __esm({
"../workers-shared/utils/types.ts"() {
init_import_meta_url();
init_lib4();
InternalConfigSchema = z2.object({
account_id: z2.number().optional(),
script_id: z2.number().optional(),
debug: z2.boolean().optional()
});
StaticRoutingSchema = z2.object({
user_worker: z2.array(z2.string()),
asset_worker: z2.array(z2.string()).optional()
});
RouterConfigSchema = z2.object({
invoke_user_worker_ahead_of_assets: z2.boolean().optional(),
static_routing: StaticRoutingSchema.optional(),
has_user_worker: z2.boolean().optional(),
...InternalConfigSchema.shape
});
EyeballRouterConfigSchema = z2.union([
z2.object({
limitedAssetsOnly: z2.boolean().optional()
}),
z2.null()
]);
MetadataStaticRedirectEntry = z2.object({
status: z2.number(),
to: z2.string(),
lineNumber: z2.number()
});
MetadataRedirectEntry = z2.object({
status: z2.number(),
to: z2.string()
});
MetadataStaticRedirects = z2.record(MetadataStaticRedirectEntry);
MetadataRedirects = z2.record(MetadataRedirectEntry);
MetadataHeaderEntry = z2.object({
set: z2.record(z2.string()).optional(),
unset: z2.array(z2.string()).optional()
});
MetadataHeaders = z2.record(MetadataHeaderEntry);
RedirectsSchema = z2.object({
version: z2.literal(1),
staticRules: MetadataStaticRedirects,
rules: MetadataRedirects
}).optional();
HeadersSchema = z2.object({
version: z2.literal(2),
rules: MetadataHeaders
}).optional();
AssetConfigSchema = z2.object({
compatibility_date: z2.string().optional(),
compatibility_flags: z2.array(z2.string()).optional(),
html_handling: z2.enum([
"auto-trailing-slash",
"force-trailing-slash",
"drop-trailing-slash",
"none"
]).optional(),
not_found_handling: z2.enum(["single-page-application", "404-page", "none"]).optional(),
redirects: RedirectsSchema,
headers: HeadersSchema,
has_static_routing: z2.boolean().optional(),
...InternalConfigSchema.shape
});
}
});
// ../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js
var require_ignore = __commonJS({
"../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js"(exports2, module3) {
init_import_meta_url();
function makeArray(subject) {
return Array.isArray(subject) ? subject : [subject];
}
__name(makeArray, "makeArray");
var EMPTY = "";
var SPACE2 = " ";
var ESCAPE = "\\";
var REGEX_TEST_BLANK_LINE = /^\s+$/;
var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
var REGEX_SPLITALL_CRLF = /\r?\n/g;
var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
var SLASH2 = "/";
var TMP_KEY_IGNORE = "node-ignore";
if (typeof Symbol !== "undefined") {
TMP_KEY_IGNORE = Symbol.for("node-ignore");
}
var KEY_IGNORE = TMP_KEY_IGNORE;
var define = /* @__PURE__ */ __name((object, key, value) => Object.defineProperty(object, key, { value }), "define");
var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
var RETURN_FALSE = /* @__PURE__ */ __name(() => false, "RETURN_FALSE");
var sanitizeRange = /* @__PURE__ */ __name((range) => range.replace(
REGEX_REGEXP_RANGE,
(match2, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match2 : EMPTY
), "sanitizeRange");
var cleanRangeBackSlash = /* @__PURE__ */ __name((slashes) => {
const { length } = slashes;
return slashes.slice(0, length - length % 2);
}, "cleanRangeBackSlash");
var REPLACERS = [
[
// remove BOM
// TODO:
// Other similar zero-width characters?
/^\uFEFF/,
() => EMPTY
],
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[
// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/,
(match2) => match2.indexOf("\\") === 0 ? SPACE2 : EMPTY
],
// replace (\ ) with ' '
[
/\\\s/g,
() => SPACE2
],
// Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[
/[\\$.|*+(){^]/g,
(match2) => `\\${match2}`
],
[
// > a question mark (?) matches a single character
/(?!\\)\?/g,
() => "[^/]"
],
// leading slash
[
// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//,
() => "^"
],
// replace special metacharacter slash after the leading slash
[
/\//g,
() => "\\/"
],
[
// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
// > under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//,
// '**/foo' <-> 'foo'
() => "^(?:.*\\/)?"
],
// starting
[
// there will be no leading '/'
// (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^^])/,
/* @__PURE__ */ __name(function startingReplacer() {
return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
}, "startingReplacer")
],
// two globstars
[
// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g,
// Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
(_4, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
],
// normal intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule,
// coz trailing single wildcard will be handed by [trailing wildcard]
/(^|[^\\]+)(\\\*)+(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
(_4, p1, p22) => {
const unescaped = p22.replace(/\\\*/g, "[^\\/]*");
return p1 + unescaped;
}
],
[
// unescape, revert step 3 except for back slash
// For example, if a user escape a '\\*',
// after step 3, the result will be '\\\\\\*'
/\\\\\\(?=[$.|*+(){^])/g,
() => ESCAPE
],
[
// '\\\\' -> '\\'
/\\\\/g,
() => ESCAPE
],
[
// > The range notation, e.g. [a-zA-Z],
// > can be used to match one of the characters in a range.
// `\` is escaped by step 3
/(\\)?\[([^\]/]*?)(\\*)($|\])/g,
(match2, leadEscape, range, endEscape, close2) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close2}` : close2 === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
],
// ending
[
// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*])$/,
// WTF!
// https://git-scm.com/docs/gitignore
// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
// which re-fixes #24, #38
// > If there is a separator at the end of the pattern then the pattern
// > will only match directories, otherwise the pattern can match both
// > files and directories.
// 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
(match2) => /\/$/.test(match2) ? `${match2}$` : `${match2}(?=$|\\/$)`
],
// trailing wildcard
[
/(\^|\\\/)?\\\*$/,
(_4, p1) => {
const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
return `${prefix}(?=$|\\/$)`;
}
]
];
var regexCache = /* @__PURE__ */ Object.create(null);
var makeRegex = /* @__PURE__ */ __name((pattern, ignoreCase) => {
let source = regexCache[pattern];
if (!source) {
source = REPLACERS.reduce(
(prev, current) => prev.replace(current[0], current[1].bind(pattern)),
pattern
);
regexCache[pattern] = source;
}
return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
}, "makeRegex");
var isString4 = /* @__PURE__ */ __name((subject) => typeof subject === "string", "isString");
var checkPattern = /* @__PURE__ */ __name((pattern) => pattern && isString4(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0, "checkPattern");
var splitPattern = /* @__PURE__ */ __name((pattern) => pattern.split(REGEX_SPLITALL_CRLF), "splitPattern");
var IgnoreRule = class {
static {
__name(this, "IgnoreRule");
}
constructor(origin, pattern, negative, regex2) {
this.origin = origin;
this.pattern = pattern;
this.negative = negative;
this.regex = regex2;
}
};
var createRule = /* @__PURE__ */ __name((pattern, ignoreCase) => {
const origin = pattern;
let negative = false;
if (pattern.indexOf("!") === 0) {
negative = true;
pattern = pattern.substr(1);
}
pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
const regex2 = makeRegex(pattern, ignoreCase);
return new IgnoreRule(
origin,
pattern,
negative,
regex2
);
}, "createRule");
var throwError = /* @__PURE__ */ __name((message, Ctor) => {
throw new Ctor(message);
}, "throwError");
var checkPath2 = /* @__PURE__ */ __name((path72, originalPath, doThrow) => {
if (!isString4(path72)) {
return doThrow(
`path must be a string, but got \`${originalPath}\``,
TypeError
);
}
if (!path72) {
return doThrow(`path must not be empty`, TypeError);
}
if (checkPath2.isNotRelative(path72)) {
const r7 = "`path.relative()`d";
return doThrow(
`path should be a ${r7} string, but got "${originalPath}"`,
RangeError
);
}
return true;
}, "checkPath");
var isNotRelative = /* @__PURE__ */ __name((path72) => REGEX_TEST_INVALID_PATH.test(path72), "isNotRelative");
checkPath2.isNotRelative = isNotRelative;
checkPath2.convert = (p6) => p6;
var Ignore = class {
static {
__name(this, "Ignore");
}
constructor({
ignorecase = true,
ignoreCase = ignorecase,
allowRelativePaths = false
} = {}) {
define(this, KEY_IGNORE, true);
this._rules = [];
this._ignoreCase = ignoreCase;
this._allowRelativePaths = allowRelativePaths;
this._initCache();
}
_initCache() {
this._ignoreCache = /* @__PURE__ */ Object.create(null);
this._testCache = /* @__PURE__ */ Object.create(null);
}
_addPattern(pattern) {
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules);
this._added = true;
return;
}
if (checkPattern(pattern)) {
const rule = createRule(pattern, this._ignoreCase);
this._added = true;
this._rules.push(rule);
}
}
// @param {Array<string> | string | Ignore} pattern
add(pattern) {
this._added = false;
makeArray(
isString4(pattern) ? splitPattern(pattern) : pattern
).forEach(this._addPattern, this);
if (this._added) {
this._initCache();
}
return this;
}
// legacy
addPattern(pattern) {
return this.add(pattern);
}
// | ignored : unignored
// negative | 0:0 | 0:1 | 1:0 | 1:1
// -------- | ------- | ------- | ------- | --------
// 0 | TEST | TEST | SKIP | X
// 1 | TESTIF | SKIP | TEST | X
// - SKIP: always skip
// - TEST: always test
// - TESTIF: only test if checkUnignored
// - X: that never happen
// @param {boolean} whether should check if the path is unignored,
// setting `checkUnignored` to `false` could reduce additional
// path matching.
// @returns {TestResult} true if a file is ignored
_testOne(path72, checkUnignored) {
let ignored = false;
let unignored = false;
this._rules.forEach((rule) => {
const { negative } = rule;
if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
return;
}
const matched = rule.regex.test(path72);
if (matched) {
ignored = !negative;
unignored = negative;
}
});
return {
ignored,
unignored
};
}
// @returns {TestResult}
_test(originalPath, cache6, checkUnignored, slices) {
const path72 = originalPath && checkPath2.convert(originalPath);
checkPath2(
path72,
originalPath,
this._allowRelativePaths ? RETURN_FALSE : throwError
);
return this._t(path72, cache6, checkUnignored, slices);
}
_t(path72, cache6, checkUnignored, slices) {
if (path72 in cache6) {
return cache6[path72];
}
if (!slices) {
slices = path72.split(SLASH2);
}
slices.pop();
if (!slices.length) {
return cache6[path72] = this._testOne(path72, checkUnignored);
}
const parent = this._t(
slices.join(SLASH2) + SLASH2,
cache6,
checkUnignored,
slices
);
return cache6[path72] = parent.ignored ? parent : this._testOne(path72, checkUnignored);
}
ignores(path72) {
return this._test(path72, this._ignoreCache, false).ignored;
}
createFilter() {
return (path72) => !this.ignores(path72);
}
filter(paths) {
return makeArray(paths).filter(this.createFilter());
}
// @returns {TestResult}
test(path72) {
return this._test(path72, this._testCache, true);
}
};
var factory = /* @__PURE__ */ __name((options) => new Ignore(options), "factory");
var isPathValid = /* @__PURE__ */ __name((path72) => checkPath2(path72 && checkPath2.convert(path72), path72, RETURN_FALSE), "isPathValid");
factory.isPathValid = isPathValid;
factory.default = factory;
module3.exports = factory;
if (
// Detect `process` so that it can run in browsers.
typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")
) {
const makePosix = /* @__PURE__ */ __name((str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/"), "makePosix");
checkPath2.convert = makePosix;
const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
checkPath2.isNotRelative = (path72) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path72) || isNotRelative(path72);
}
}
});
// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/other.js
var types, other_default;
var init_other = __esm({
"../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/other.js"() {
init_import_meta_url();
types = {
"application/prs.cww": ["cww"],
"application/prs.xsf+xml": ["xsf"],
"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.age": ["age"],
"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.autodesk.fbx": ["fbx"],
"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.dcmp+xml": ["dcmp"],
"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.slides": ["ggs"],
"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.drawing": ["gdraw"],
"application/vnd.google-apps.form": ["gform"],
"application/vnd.google-apps.jam": ["gjam"],
"application/vnd.google-apps.map": ["gmap"],
"application/vnd.google-apps.presentation": ["gslides"],
"application/vnd.google-apps.script": ["gscript"],
"application/vnd.google-apps.site": ["gsite"],
"application/vnd.google-apps.spreadsheet": ["gsheet"],
"application/vnd.google-earth.kml+xml": ["kml"],
"application/vnd.google-earth.kmz": ["kmz"],
"application/vnd.gov.sk.xmldatacontainer+xml": ["xdcf"],
"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-visio.viewer": ["vdx"],
"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.nato.bindingdataobject+xml": ["bdo"],
"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.procrate.brushset": ["brushset"],
"application/vnd.procreate.brush": ["brush"],
"application/vnd.procreate.dream": ["drm"],
"application/vnd.proteus.magazine": ["mgz"],
"application/vnd.publishare-delta-tree": ["qps"],
"application/vnd.pvi.ptid1": ["ptid"],
"application/vnd.pwg-xhtml-print+xml": ["xhtm"],
"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", "uo"],
"application/vnd.vcx": ["vcx"],
"application/vnd.visio": ["vsd", "vst", "vss", "vsw", "vsdx", "vtx"],
"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-blender": ["blend"],
"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-compressed": ["*rar"],
"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-ipynb+json": ["ipynb"],
"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-zip-compressed": ["*zip"],
"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", "btf"],
"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-adobe-dng": ["dng"],
"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.bary": ["bary"],
"model/vnd.cld": ["cld"],
"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.pytha.pyox": ["pyo", "pyox"],
"model/vnd.sap.vds": ["vds"],
"model/vnd.usda": ["usda"],
"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.familysearch.gedcom": ["ged"],
"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"]
};
Object.freeze(types);
other_default = types;
}
});
// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/standard.js
var types2, standard_default;
var init_standard = __esm({
"../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/standard.js"() {
init_import_meta_url();
types2 = {
"application/andrew-inset": ["ez"],
"application/appinstaller": ["appinstaller"],
"application/applixware": ["aw"],
"application/appx": ["appx"],
"application/appxbundle": ["appxbundle"],
"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/automationml-aml+xml": ["aml"],
"application/automationml-amlx+zip": ["amlx"],
"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/cpl+xml": ["cpl"],
"application/cu-seeme": ["cu"],
"application/cwl": ["cwl"],
"application/dash+xml": ["mpd"],
"application/dash-patch+xml": ["mpp"],
"application/davmount+xml": ["davmount"],
"application/dicom": ["dcm"],
"application/docbook+xml": ["dbk"],
"application/dssc+der": ["dssc"],
"application/dssc+xml": ["xdssc"],
"application/ecmascript": ["ecma"],
"application/emma+xml": ["emma"],
"application/emotionml+xml": ["emotionml"],
"application/epub+zip": ["epub"],
"application/exi": ["exi"],
"application/express": ["exp"],
"application/fdf": ["fdf"],
"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"],
"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/media-policy-dataset+xml": ["mpf"],
"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": ["*mp4", "*mpg4", "mp4s", "m4p"],
"application/msix": ["msix"],
"application/msixbundle": ["msixbundle"],
"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",
"one",
"onea"
],
"application/oxps": ["oxps"],
"application/p2p-overlay+xml": ["relo"],
"application/patch-ops-error+xml": ["xer"],
"application/pdf": ["pdf"],
"application/pgp-encrypted": ["pgp"],
"application/pgp-keys": ["asc"],
"application/pgp-signature": ["sig", "*asc"],
"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/sql": ["sql"],
"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/watcherinfo+xml": ["wif"],
"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/xfdf": ["xfdf"],
"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"],
"application/zip+dotlottie": ["lottie"],
"audio/3gpp": ["*3gpp"],
"audio/aac": ["adts", "aac"],
"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", "m4b"],
"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/avci": ["avci"],
"image/avcs": ["avcs"],
"image/avif": ["avif"],
"image/bmp": ["bmp", "dib"],
"image/cgm": ["cgm"],
"image/dicom-rle": ["drle"],
"image/dpx": ["dpx"],
"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/ief": ["ief"],
"image/jaii": ["jaii"],
"image/jais": ["jais"],
"image/jls": ["jls"],
"image/jp2": ["jp2", "jpg2"],
"image/jpeg": ["jpg", "jpeg", "jpe"],
"image/jph": ["jph"],
"image/jphc": ["jhc"],
"image/jpm": ["jpm", "jpgm"],
"image/jpx": ["jpx", "jpf"],
"image/jxl": ["jxl"],
"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/pjpeg": ["jfif"],
"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", "mht", "mhtml"],
"model/3mf": ["3mf"],
"model/gltf+json": ["gltf"],
"model/gltf-binary": ["glb"],
"model/iges": ["igs", "iges"],
"model/jt": ["jt"],
"model/mesh": ["msh", "mesh", "silo"],
"model/mtl": ["mtl"],
"model/obj": ["obj"],
"model/prc": ["prc"],
"model/step": ["step", "stp", "stpnc", "p21", "210"],
"model/step+xml": ["stpx"],
"model/step+zip": ["stpz"],
"model/step-xml+zip": ["stpxz"],
"model/stl": ["stl"],
"model/u3d": ["u3d"],
"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/javascript": ["js", "mjs"],
"text/jsx": ["jsx"],
"text/less": ["less"],
"text/markdown": ["md", "markdown"],
"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/wgsl": ["wgsl"],
"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", "m2t", "m2ts", "mts"],
"video/mp4": ["mp4", "mp4v", "mpg4"],
"video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"],
"video/ogg": ["ogv"],
"video/quicktime": ["qt", "mov"],
"video/webm": ["webm"]
};
Object.freeze(types2);
standard_default = types2;
}
});
// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet, _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions, Mime, Mime_default;
var init_Mime = __esm({
"../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/Mime.js"() {
init_import_meta_url();
__classPrivateFieldGet = function(receiver, state2, kind, f6) {
if (kind === "a" && !f6) throw new TypeError("Private accessor was defined without a getter");
if (typeof state2 === "function" ? receiver !== state2 || !f6 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f6 : kind === "a" ? f6.call(receiver) : f6 ? f6.value : state2.get(receiver);
};
Mime = class {
static {
__name(this, "Mime");
}
constructor(...args) {
_Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
_Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
_Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
for (const arg of args) {
this.define(arg);
}
}
define(typeMap, force = false) {
for (let [type, extensions] of Object.entries(typeMap)) {
type = type.toLowerCase();
extensions = extensions.map((ext) => ext.toLowerCase());
if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
}
const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
let first = true;
for (let extension of extensions) {
const starred = extension.startsWith("*");
extension = starred ? extension.slice(1) : extension;
allExtensions?.add(extension);
if (first) {
__classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
}
first = false;
if (starred)
continue;
const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
if (currentType && currentType != type && !force) {
throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
}
__classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
}
}
return this;
}
getType(path72) {
if (typeof path72 !== "string")
return null;
const last = path72.replace(/^.*[/\\]/s, "").toLowerCase();
const ext = last.replace(/^.*\./s, "").toLowerCase();
const hasPath = last.length < path72.length;
const hasDot = ext.length < last.length - 1;
if (!hasDot && hasPath)
return null;
return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
}
getExtension(type) {
if (typeof type !== "string")
return null;
type = type?.split?.(";")[0];
return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
}
getAllExtensions(type) {
if (typeof type !== "string")
return null;
return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
}
_freeze() {
this.define = () => {
throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
};
Object.freeze(this);
for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
Object.freeze(extensions);
}
return this;
}
_getTestState() {
return {
types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
};
}
};
_Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
Mime_default = Mime;
}
});
// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/index.js
var src_default;
var init_src = __esm({
"../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/index.js"() {
init_import_meta_url();
init_other();
init_standard();
init_Mime();
init_Mime();
src_default = new Mime_default(standard_default, other_default)._freeze();
}
});
// ../workers-shared/utils/helpers.ts
function createPatternMatcher(patterns, exclude2) {
if (patterns.length === 0) {
return (_filePath) => !exclude2;
} else {
const ignorer = (0, import_ignore.default)().add(patterns);
return (filePath) => ignorer.test(filePath).ignored;
}
}
function thrownIsDoesNotExistError(thrown) {
return thrown instanceof Error && "code" in thrown && thrown.code === "ENOENT";
}
function maybeGetFile(filePath) {
try {
return (0, import_node_fs10.readFileSync)(filePath, "utf8");
} catch (e7) {
if (!thrownIsDoesNotExistError(e7)) {
throw e7;
}
}
}
async function createAssetsIgnoreFunction(dir) {
const cfAssetIgnorePath = (0, import_node_path15.resolve)(dir, CF_ASSETS_IGNORE_FILENAME);
const ignorePatterns = [
// Ignore the `.assetsignore` file and other metafiles by default.
// The ignore lib expects unix-style paths for its patterns
`/${CF_ASSETS_IGNORE_FILENAME}`,
`/${REDIRECTS_FILENAME}`,
`/${HEADERS_FILENAME}`
];
let assetsIgnoreFilePresent = false;
const assetsIgnore = maybeGetFile(cfAssetIgnorePath);
if (assetsIgnore !== void 0) {
assetsIgnoreFilePresent = true;
ignorePatterns.push(...assetsIgnore.split("\n"));
}
return {
assetsIgnoreFunction: createPatternMatcher(ignorePatterns, true),
assetsIgnoreFilePresent
};
}
var import_node_fs10, import_node_path15, import_ignore, normalizeFilePath, getContentType;
var init_helpers2 = __esm({
"../workers-shared/utils/helpers.ts"() {
init_import_meta_url();
import_node_fs10 = require("fs");
import_node_path15 = require("path");
import_ignore = __toESM(require_ignore());
init_src();
init_constants2();
normalizeFilePath = /* @__PURE__ */ __name((relativeFilepath) => {
if ((0, import_node_path15.isAbsolute)(relativeFilepath)) {
throw new Error(`Expected relative path`);
}
return "/" + relativeFilepath.split(import_node_path15.sep).join("/");
}, "normalizeFilePath");
getContentType = /* @__PURE__ */ __name((absFilePath) => {
let contentType = src_default.getType(absFilePath);
if (contentType && contentType.startsWith("text/") && !contentType.includes("charset")) {
contentType = `${contentType}; charset=utf-8`;
}
return contentType;
}, "getContentType");
__name(createPatternMatcher, "createPatternMatcher");
__name(thrownIsDoesNotExistError, "thrownIsDoesNotExistError");
__name(maybeGetFile, "maybeGetFile");
__name(createAssetsIgnoreFunction, "createAssetsIgnoreFunction");
}
});
// ../workers-shared/utils/configuration/constants.ts
var REDIRECTS_VERSION, HEADERS_VERSION, PERMITTED_STATUS_CODES, HEADER_SEPARATOR, MAX_LINE_LENGTH, MAX_HEADER_RULES, MAX_DYNAMIC_REDIRECT_RULES, MAX_STATIC_REDIRECT_RULES, UNSET_OPERATOR, SPLAT_REGEX, PLACEHOLDER_REGEX, MAX_ROUTES_RULES, MAX_ROUTES_RULE_LENGTH;
var init_constants3 = __esm({
"../workers-shared/utils/configuration/constants.ts"() {
init_import_meta_url();
REDIRECTS_VERSION = 1;
HEADERS_VERSION = 2;
PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([200, 301, 302, 303, 307, 308]);
HEADER_SEPARATOR = ":";
MAX_LINE_LENGTH = 2e3;
MAX_HEADER_RULES = 100;
MAX_DYNAMIC_REDIRECT_RULES = 100;
MAX_STATIC_REDIRECT_RULES = 2e3;
UNSET_OPERATOR = "! ";
SPLAT_REGEX = /\*/g;
PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
MAX_ROUTES_RULES = 100;
MAX_ROUTES_RULE_LENGTH = 100;
}
});
// ../workers-shared/utils/configuration/validateURL.ts
function urlHasHost(token) {
const host = URL_REGEX.exec(token);
return Boolean(host && host.groups && host.groups.host);
}
var extractPathname, URL_REGEX, HOST_WITH_PORT_REGEX, PATH_REGEX, validateUrl;
var init_validateURL = __esm({
"../workers-shared/utils/configuration/validateURL.ts"() {
init_import_meta_url();
extractPathname = /* @__PURE__ */ __name((path72 = "/", includeSearch, includeHash) => {
if (!path72.startsWith("/")) {
path72 = `/${path72}`;
}
const url4 = new URL(`//${path72}`, "relative://");
return `${url4.pathname}${includeSearch ? url4.search : ""}${includeHash ? url4.hash : ""}`;
}, "extractPathname");
URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
HOST_WITH_PORT_REGEX = /.*:\d+$/;
PATH_REGEX = /^\//;
validateUrl = /* @__PURE__ */ __name((token, onlyRelative = false, disallowPorts = false, includeSearch = false, includeHash = false) => {
const host = URL_REGEX.exec(token);
if (host && host.groups && host.groups.host) {
if (onlyRelative) {
return [
void 0,
`Only relative URLs are allowed. Skipping absolute URL ${token}.`
];
}
if (disallowPorts && host.groups.host.match(HOST_WITH_PORT_REGEX)) {
return [
void 0,
`Specifying ports is not supported. Skipping absolute URL ${token}.`
];
}
return [
`https://${host.groups.host}${extractPathname(
host.groups.path,
includeSearch,
includeHash
)}`,
void 0
];
} else {
if (!token.startsWith("/") && onlyRelative) {
token = `/${token}`;
}
const path72 = PATH_REGEX.exec(token);
if (path72) {
try {
return [extractPathname(token, includeSearch, includeHash), void 0];
} catch {
return [void 0, `Error parsing URL segment ${token}. Skipping.`];
}
}
}
return [
void 0,
onlyRelative ? "URLs should begin with a forward-slash." : 'URLs should either be relative (e.g. begin with a forward-slash), or use HTTPS (e.g. begin with "https://").'
];
}, "validateUrl");
__name(urlHasHost, "urlHasHost");
}
});
// ../workers-shared/utils/configuration/parseHeaders.ts
function parseHeaders(input, {
maxRules = MAX_HEADER_RULES,
maxLineLength = MAX_LINE_LENGTH
} = {}) {
const lines = input.split("\n");
const rules = [];
const invalid = [];
let rule = void 0;
for (let i5 = 0; i5 < lines.length; i5++) {
const line = (lines[i5] || "").trim();
if (line.length === 0 || line.startsWith("#")) {
continue;
}
if (line.length > maxLineLength) {
invalid.push({
message: `Ignoring line ${i5 + 1} as it exceeds the maximum allowed length of ${maxLineLength}.`
});
continue;
}
if (LINE_IS_PROBABLY_A_PATH.test(line)) {
if (rules.length >= maxRules) {
invalid.push({
message: `Maximum number of rules supported is ${maxRules}. Skipping remaining ${lines.length - i5} lines of file.`
});
break;
}
if (rule) {
if (isValidRule(rule)) {
rules.push({
path: rule.path,
headers: rule.headers,
unsetHeaders: rule.unsetHeaders
});
} else {
invalid.push({
line: rule.line,
lineNumber: i5 + 1,
message: "No headers specified"
});
}
}
const [path72, pathError] = validateUrl(line, false, true);
if (pathError) {
invalid.push({
line,
lineNumber: i5 + 1,
message: pathError
});
rule = void 0;
continue;
}
rule = {
path: path72,
line,
headers: {},
unsetHeaders: []
};
continue;
}
if (!line.includes(HEADER_SEPARATOR)) {
if (!rule) {
invalid.push({
line,
lineNumber: i5 + 1,
message: "Expected a path beginning with at least one forward-slash"
});
} else {
if (line.trim().startsWith(UNSET_OPERATOR)) {
rule.unsetHeaders.push(line.trim().replace(UNSET_OPERATOR, ""));
} else {
invalid.push({
line,
lineNumber: i5 + 1,
message: "Expected a colon-separated header pair (e.g. name: value)"
});
}
}
continue;
}
const [rawName, ...rawValue] = line.split(HEADER_SEPARATOR);
const name2 = (rawName || "").trim().toLowerCase();
if (name2.includes(" ")) {
invalid.push({
line,
lineNumber: i5 + 1,
message: "Header name cannot include spaces"
});
continue;
}
const value = rawValue.join(HEADER_SEPARATOR).trim();
if (name2 === "") {
invalid.push({
line,
lineNumber: i5 + 1,
message: "No header name specified"
});
continue;
}
if (value === "") {
invalid.push({
line,
lineNumber: i5 + 1,
message: "No header value specified"
});
continue;
}
if (!rule) {
invalid.push({
line,
lineNumber: i5 + 1,
message: `Path should come before header (${name2}: ${value})`
});
continue;
}
const existingValues = rule.headers[name2];
rule.headers[name2] = existingValues ? `${existingValues}, ${value}` : value;
}
if (rule) {
if (isValidRule(rule)) {
rules.push({
path: rule.path,
headers: rule.headers,
unsetHeaders: rule.unsetHeaders
});
} else {
invalid.push({ line: rule.line, message: "No headers specified" });
}
}
return {
rules,
invalid
};
}
function isValidRule(rule) {
return Object.keys(rule.headers).length > 0 || rule.unsetHeaders.length > 0;
}
var LINE_IS_PROBABLY_A_PATH;
var init_parseHeaders = __esm({
"../workers-shared/utils/configuration/parseHeaders.ts"() {
init_import_meta_url();
init_constants3();
init_validateURL();
LINE_IS_PROBABLY_A_PATH = new RegExp(/^([^\s]+:\/\/|^\/)/);
__name(parseHeaders, "parseHeaders");
__name(isValidRule, "isValidRule");
}
});
// ../workers-shared/utils/configuration/parseRedirects.ts
function parseRedirects(input, {
maxStaticRules = MAX_STATIC_REDIRECT_RULES,
maxDynamicRules = MAX_DYNAMIC_REDIRECT_RULES,
maxLineLength = MAX_LINE_LENGTH
} = {}) {
const lines = input.split("\n");
const rules = [];
const seen_paths = /* @__PURE__ */ new Set();
const invalid = [];
let staticRules = 0;
let dynamicRules = 0;
let canCreateStaticRule = true;
for (let i5 = 0; i5 < lines.length; i5++) {
const line = (lines[i5] || "").trim();
if (line.length === 0 || line.startsWith("#")) {
continue;
}
if (line.length > maxLineLength) {
invalid.push({
message: `Ignoring line ${i5 + 1} as it exceeds the maximum allowed length of ${maxLineLength}.`
});
continue;
}
const tokens = line.split(/\s+/);
if (tokens.length < 2 || tokens.length > 3) {
invalid.push({
line,
lineNumber: i5 + 1,
message: `Expected exactly 2 or 3 whitespace-separated tokens. Got ${tokens.length}.`
});
continue;
}
const [str_from, str_to, str_status = "302"] = tokens;
const fromResult = validateUrl(str_from, true, true, false, false);
if (fromResult[0] === void 0) {
invalid.push({
line,
lineNumber: i5 + 1,
message: fromResult[1]
});
continue;
}
const from = fromResult[0];
if (canCreateStaticRule && !from.match(SPLAT_REGEX) && !from.match(PLACEHOLDER_REGEX)) {
staticRules += 1;
if (staticRules > maxStaticRules) {
invalid.push({
message: `Maximum number of static rules supported is ${maxStaticRules}. Skipping line.`
});
continue;
}
} else {
dynamicRules += 1;
canCreateStaticRule = false;
if (dynamicRules > maxDynamicRules) {
invalid.push({
message: `Maximum number of dynamic rules supported is ${maxDynamicRules}. Skipping remaining ${lines.length - i5} lines of file.`
});
break;
}
}
const toResult = validateUrl(str_to, false, false, true, true);
if (toResult[0] === void 0) {
invalid.push({
line,
lineNumber: i5 + 1,
message: toResult[1]
});
continue;
}
const to = toResult[0];
const status2 = Number(str_status);
if (isNaN(status2) || !PERMITTED_STATUS_CODES.has(status2)) {
invalid.push({
line,
lineNumber: i5 + 1,
message: `Valid status codes are 200, 301, 302 (default), 303, 307, or 308. Got ${str_status}.`
});
continue;
}
if (/\/\*?$/.test(from) && /\/index(.html)?$/.test(to) && !urlHasHost(to)) {
invalid.push({
line,
lineNumber: i5 + 1,
message: "Infinite loop detected in this rule and has been ignored. This will cause a redirect to strip `.html` or `/index` and end up triggering this rule again. Please fix or remove this rule to silence this warning."
});
continue;
}
if (seen_paths.has(from)) {
invalid.push({
line,
lineNumber: i5 + 1,
message: `Ignoring duplicate rule for path ${from}.`
});
continue;
}
seen_paths.add(from);
if (status2 === 200) {
if (urlHasHost(to)) {
invalid.push({
line,
lineNumber: i5 + 1,
message: `Proxy (200) redirects can only point to relative paths. Got ${to}`
});
continue;
}
}
rules.push({ from, to, status: status2, lineNumber: i5 + 1 });
}
return {
rules,
invalid
};
}
var init_parseRedirects = __esm({
"../workers-shared/utils/configuration/parseRedirects.ts"() {
init_import_meta_url();
init_constants3();
init_validateURL();
__name(parseRedirects, "parseRedirects");
}
});
// ../workers-shared/utils/configuration/types.ts
var init_types3 = __esm({
"../workers-shared/utils/configuration/types.ts"() {
init_import_meta_url();
}
});
// ../workers-shared/index.ts
var init_workers_shared = __esm({
"../workers-shared/index.ts"() {
init_import_meta_url();
init_constants2();
init_types2();
init_helpers2();
init_parseHeaders();
init_parseRedirects();
init_types3();
}
});
// src/sourcemap.ts
function maybeRetrieveFileSourceMap(filePath) {
if (filePath === void 0) {
return null;
}
const contents = maybeGetFile(filePath);
if (contents === void 0) {
return null;
}
const mapRegexp = /# sourceMappingURL=(.+)/g;
const matches = [...contents.matchAll(mapRegexp)];
if (matches.length === 0) {
return null;
}
const mapMatch = matches[matches.length - 1];
const fileUrl = import_node_url6.default.pathToFileURL(filePath);
const mapUrl = new URL(mapMatch[1], fileUrl);
if (mapUrl.protocol === "data:" && mapUrl.pathname.startsWith("application/json;base64,")) {
const base642 = mapUrl.href.substring(mapUrl.href.indexOf(",") + 1);
const map2 = Buffer.from(base642, "base64").toString();
return { map: map2, url: fileUrl.href };
} else {
const map2 = maybeGetFile(mapUrl);
if (map2 === void 0) {
return null;
}
return { map: map2, url: mapUrl.href };
}
}
function getSourceMappingPrepareStackTrace(retrieveSourceMap) {
retrieveSourceMapOverride = retrieveSourceMap;
if (sourceMappingPrepareStackTrace !== void 0) {
return sourceMappingPrepareStackTrace;
}
const support = (0, import_miniflare7.getFreshSourceMapSupport)();
const originalPrepareStackTrace = Error.prepareStackTrace;
support.install({
environment: "node",
// Don't add Node `uncaughtException` handler
handleUncaughtExceptions: false,
// Don't hook Node `require` function
hookRequire: false,
redirectConflictingLibrary: false,
// Make sure we're using fresh copies of files each time we source map
emptyCacheBetweenOperations: true,
// Allow retriever to be overridden at prepare stack trace time
retrieveSourceMap(path72) {
return retrieveSourceMapOverride?.(path72) ?? null;
}
});
sourceMappingPrepareStackTrace = Error.prepareStackTrace;
(0, import_node_assert4.default)(sourceMappingPrepareStackTrace !== void 0);
Error.prepareStackTrace = originalPrepareStackTrace;
return sourceMappingPrepareStackTrace;
}
function getSourceMappedStack(details) {
const description = details.exception?.description ?? "";
const callFrames = details.stackTrace?.callFrames;
if (callFrames === void 0) {
return description;
}
const nameMessage = details.exception?.description?.split("\n")[0] ?? "";
const colonIndex = nameMessage.indexOf(":");
const error2 = new Error(nameMessage.substring(colonIndex + 2));
error2.name = nameMessage.substring(0, colonIndex);
const callSites = callFrames.map(callFrameToCallSite);
return getSourceMappingPrepareStackTrace()(error2, callSites);
}
function callFrameToCallSite(frame) {
return new CallSite({
typeName: null,
functionName: frame.functionName,
methodName: null,
fileName: frame.url,
lineNumber: frame.lineNumber + 1,
columnNumber: frame.columnNumber + 1,
native: false
});
}
function getSourceMappedString(value, retrieveSourceMap) {
const callSiteLines = Array.from(value.matchAll(CALL_SITE_REGEXP));
const callSites = callSiteLines.map(lineMatchToCallSite);
const prepareStack = getSourceMappingPrepareStackTrace(retrieveSourceMap);
const sourceMappedStackTrace = prepareStack(
placeholderError,
callSites
);
const sourceMappedCallSiteLines = sourceMappedStackTrace.split("\n").slice(1);
for (let i5 = 0; i5 < callSiteLines.length; i5++) {
if (callSites[i5].getFileName() === void 0) {
continue;
}
const callSiteLine = callSiteLines[i5][0];
const callSiteAtIndex = callSiteLine.indexOf("at");
(0, import_node_assert4.default)(callSiteAtIndex !== -1);
const callSiteLineLeftPad = callSiteLine.substring(0, callSiteAtIndex);
value = value.replace(
callSiteLine,
callSiteLineLeftPad + sourceMappedCallSiteLines[i5].trimStart()
);
}
return value;
}
function lineMatchToCallSite(lineMatch) {
let object = null;
let method = null;
let functionName = null;
let typeName = null;
let methodName = null;
const isNative = lineMatch[5] === "native";
if (lineMatch[1]) {
functionName = lineMatch[1];
let methodStart = functionName.lastIndexOf(".");
if (functionName[methodStart - 1] == ".") {
methodStart--;
}
if (methodStart > 0) {
object = functionName.substring(0, methodStart);
method = functionName.substring(methodStart + 1);
const objectEnd = object.indexOf(".Module");
if (objectEnd > 0) {
functionName = functionName.substring(objectEnd + 1);
object = object.substring(0, objectEnd);
}
}
}
if (method) {
typeName = object;
methodName = method;
}
if (method === "<anonymous>") {
methodName = null;
functionName = null;
}
return new CallSite({
typeName,
functionName,
methodName,
fileName: lineMatch[2],
lineNumber: parseInt(lineMatch[3]) || null,
columnNumber: parseInt(lineMatch[4]) || null,
native: isNative
});
}
var import_node_assert4, import_node_url6, import_miniflare7, sourceMappingPrepareStackTrace, retrieveSourceMapOverride, placeholderError, CALL_SITE_REGEXP, CallSite;
var init_sourcemap = __esm({
"src/sourcemap.ts"() {
init_import_meta_url();
import_node_assert4 = __toESM(require("assert"));
import_node_url6 = __toESM(require("url"));
init_workers_shared();
import_miniflare7 = require("miniflare");
__name(maybeRetrieveFileSourceMap, "maybeRetrieveFileSourceMap");
__name(getSourceMappingPrepareStackTrace, "getSourceMappingPrepareStackTrace");
__name(getSourceMappedStack, "getSourceMappedStack");
__name(callFrameToCallSite, "callFrameToCallSite");
placeholderError = new Error();
__name(getSourceMappedString, "getSourceMappedString");
CALL_SITE_REGEXP = // Validation errors from `wrangler deploy` have a 2 space indent, whereas
// regular stack traces have a 4 space indent.
// eslint-disable-next-line no-control-regex
/^(?:\s+(?:\x1B\[\d+m)?'?)? {2,4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/gm;
__name(lineMatchToCallSite, "lineMatchToCallSite");
CallSite = class {
constructor(opts) {
this.opts = opts;
}
static {
__name(this, "CallSite");
}
getScriptHash() {
throw new Error("Method not implemented.");
}
getEnclosingColumnNumber() {
throw new Error("Method not implemented.");
}
getEnclosingLineNumber() {
throw new Error("Method not implemented.");
}
getPosition() {
throw new Error("Method not implemented.");
}
getThis() {
return null;
}
getTypeName() {
return this.opts.typeName;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
getFunction() {
return void 0;
}
getFunctionName() {
return this.opts.functionName;
}
getMethodName() {
return this.opts.methodName;
}
getFileName() {
return this.opts.fileName ?? null;
}
getScriptNameOrSourceURL() {
return this.opts.fileName;
}
getLineNumber() {
return this.opts.lineNumber;
}
getColumnNumber() {
return this.opts.columnNumber;
}
getEvalOrigin() {
return void 0;
}
isToplevel() {
return false;
}
isEval() {
return false;
}
isNative() {
return this.opts.native;
}
isConstructor() {
return false;
}
isAsync() {
return false;
}
isPromiseAll() {
return false;
}
isPromiseAny() {
return false;
}
getPromiseIndex() {
return null;
}
};
}
});
// src/dev/miniflare/stdio.ts
function handleRuntimeStdioWithStructuredLogs(stdout2, stderr2) {
stdout2.on("data", getProcessStreamDataListener("stdout"));
stderr2.on("data", getProcessStreamDataListener("stderr"));
}
function getProcessStreamDataListener(processStream) {
let streamAccumulator = "";
return (chunk) => {
const fullStreamOutput = `${streamAccumulator}${chunk}`;
let currentLogsStr = "";
const lastNewlineIdx = fullStreamOutput.lastIndexOf("\n");
if (lastNewlineIdx > 0) {
currentLogsStr = fullStreamOutput.slice(0, lastNewlineIdx);
streamAccumulator = fullStreamOutput.slice(lastNewlineIdx + 1);
} else {
streamAccumulator = fullStreamOutput;
}
const lines = currentLogsStr.split("\n");
for (const line of lines) {
const structuredLog = parseStructuredLog(line);
if (structuredLog) {
logStructuredLog(structuredLog, processStream);
} else {
const level = processStream === "stdout" ? "log" : "error";
logger[level](line);
}
}
};
}
function parseStructuredLog(str) {
try {
const maybeStructuredLog = JSON.parse(str);
if (typeof maybeStructuredLog !== "object" || maybeStructuredLog === null) {
return null;
}
const timestamp = parseInt(maybeStructuredLog.timestamp);
if (isNaN(timestamp) || typeof maybeStructuredLog.level !== "string" || typeof maybeStructuredLog.message !== "string") {
return null;
}
return {
timestamp,
level: maybeStructuredLog.level,
message: maybeStructuredLog.message
};
} catch {
return null;
}
}
function logStructuredLog({ level, message }, processStream) {
if (messageClassifiers.isBarf(message)) {
if (messageClassifiers.isAddressInUse(message)) {
const address = message.match(
/Address already in use; toString\(\) = (.+)\n/
)?.[1];
logger.error(
`Address already in use (${address}). Please check that you are not already running a server on this address or specify a different port with --port.`
);
return logger.debug(message);
}
if (messageClassifiers.isAccessViolation(message)) {
let error2 = "There was an access violation in the runtime.";
if (process.platform === "win32") {
error2 += "\nOn Windows, this may be caused by an outdated Microsoft Visual C++ Redistributable library.\nCheck that you have the latest version installed.\nSee https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist.";
}
logger.error(error2);
return logger.debug(message);
}
return logger.debug(message);
}
if ((level === "info" || level === "error") && messageClassifiers.isCodeMovedWarning(message)) {
return;
}
if (level === "warn") {
return logger.warn(message);
}
if (level === "info") {
return logger.info(message);
}
if (level === "debug") {
return logger.debug(message);
}
if (level === "error") {
return logger.error(getSourceMappedString(message));
}
if (processStream === "stderr") {
return logger.error(getSourceMappedString(message));
} else {
return logger.log(getSourceMappedString(message));
}
}
var messageClassifiers;
var init_stdio = __esm({
"src/dev/miniflare/stdio.ts"() {
init_import_meta_url();
init_logger();
init_sourcemap();
__name(handleRuntimeStdioWithStructuredLogs, "handleRuntimeStdioWithStructuredLogs");
__name(getProcessStreamDataListener, "getProcessStreamDataListener");
__name(parseStructuredLog, "parseStructuredLog");
__name(logStructuredLog, "logStructuredLog");
messageClassifiers = {
// Is this chunk a big chonky barf from workerd that we want to hijack to cleanup/ignore?
isBarf(chunk) {
const containsLlvmSymbolizerWarning = chunk.includes(
"Not symbolizing stack traces because $LLVM_SYMBOLIZER is not set"
);
const containsRecursiveIsolateLockWarning = chunk.includes(
"took recursive isolate lock"
);
const containsHexStack = /stack:( (0|[a-f\d]{4,})){3,}/.test(chunk);
return containsLlvmSymbolizerWarning || containsRecursiveIsolateLockWarning || containsHexStack;
},
// Is this chunk an Address In Use error?
isAddressInUse(chunk) {
return chunk.includes("Address already in use; toString() = ");
},
isCodeMovedWarning(chunk) {
return /CODE_MOVED for unknown code block/.test(chunk);
},
isAccessViolation(chunk) {
return chunk.includes("access violation;");
}
};
}
});
// src/dev/miniflare/index.ts
function getName(config) {
return config.name ?? DEFAULT_WORKER_NAME;
}
function getIdentifier(name2) {
return name2.replace(IDENTIFIER_UNSAFE_REGEXP, "_");
}
function castLogLevel(level) {
let key = level.toUpperCase();
if (key === "LOG") {
key = "INFO";
}
return import_miniflare8.LogLevel[key];
}
function buildLog() {
const level = castLogLevel(logger.loggerLevel);
return new WranglerLog(level, {
prefix: level === import_miniflare8.LogLevel.DEBUG ? "wrangler-UserWorker" : "wrangler"
});
}
async function buildSourceOptions(config) {
const scriptPath4 = config.bundle.path;
if (config.format === "modules") {
const isPython = config.bundle.type === "python";
const { entrypointSource, modules } = isPython ? {
entrypointSource: config.bundle.entrypointSource,
modules: config.bundle.modules
} : withSourceURLs(
scriptPath4,
config.bundle.entrypointSource,
config.bundle.modules
);
const entrypointNames = isPython ? [] : config.bundle.entry.exports;
const modulesRoot = import_node_path16.default.dirname(scriptPath4);
const sourceOptions = {
modulesRoot,
modules: [
// Entrypoint
{
type: ModuleTypeToRuleType[config.bundle.type],
path: scriptPath4,
contents: entrypointSource
},
// Misc (WebAssembly, etc, ...)
...modules.map((module3) => ({
type: ModuleTypeToRuleType[module3.type ?? "esm"],
path: import_node_path16.default.resolve(modulesRoot, module3.name),
contents: module3.content
}))
]
};
return { sourceOptions, entrypointNames };
} else {
return {
sourceOptions: { script: config.bundle.entrypointSource, scriptPath: scriptPath4 },
entrypointNames: []
};
}
}
function getRemoteId(id) {
return typeof id === "string" ? id : null;
}
function kvNamespaceEntry({ binding, id: originalId, experimental_remote }, remoteProxyConnectionString) {
const id = getRemoteId(originalId) ?? binding;
if (!remoteProxyConnectionString || !experimental_remote) {
return [binding, { id }];
}
return [binding, { id, remoteProxyConnectionString }];
}
function r2BucketEntry({ binding, bucket_name, experimental_remote }, remoteProxyConnectionString) {
const id = getRemoteId(bucket_name) ?? binding;
if (!remoteProxyConnectionString || !experimental_remote) {
return [binding, { id }];
}
return [binding, { id, remoteProxyConnectionString }];
}
function d1DatabaseEntry({
binding,
database_id,
preview_database_id,
experimental_remote
}, remoteProxyConnectionString) {
const id = getRemoteId(preview_database_id ?? database_id) ?? binding;
if (!remoteProxyConnectionString || !experimental_remote) {
return [binding, { id }];
}
return [binding, { id, remoteProxyConnectionString }];
}
function queueProducerEntry({
binding,
queue_name: queueName,
delivery_delay: deliveryDelay,
experimental_remote
}, remoteProxyConnectionString) {
if (!remoteProxyConnectionString || !experimental_remote) {
return [binding, { queueName, deliveryDelay }];
}
return [binding, { queueName, deliveryDelay, remoteProxyConnectionString }];
}
function pipelineEntry(pipeline, remoteProxyConnectionString) {
if (!remoteProxyConnectionString || !pipeline.experimental_remote) {
return [pipeline.binding, { pipeline: pipeline.pipeline }];
}
return [
pipeline.binding,
{ pipeline: pipeline.pipeline, remoteProxyConnectionString }
];
}
function hyperdriveEntry(hyperdrive) {
return [hyperdrive.binding, hyperdrive.localConnectionString ?? ""];
}
function workflowEntry({
binding,
name: name2,
class_name: className,
script_name: scriptName,
experimental_remote
}, remoteProxyConnectionString) {
if (!remoteProxyConnectionString || !experimental_remote) {
return [
binding,
{
name: name2,
className,
scriptName
}
];
}
return [
binding,
{
name: name2,
className,
scriptName,
remoteProxyConnectionString
}
];
}
function dispatchNamespaceEntry({ binding, namespace, experimental_remote }, remoteProxyConnectionString) {
if (!remoteProxyConnectionString || !experimental_remote) {
return [binding, { namespace }];
}
return [binding, { namespace, remoteProxyConnectionString }];
}
function ratelimitEntry(ratelimit) {
return [ratelimit.name, ratelimit];
}
function queueConsumerEntry(consumer) {
const options = {
maxBatchSize: consumer.max_batch_size,
maxBatchTimeout: consumer.max_batch_timeout,
maxRetries: consumer.max_retries,
deadLetterQueue: consumer.dead_letter_queue,
retryDelay: consumer.retry_delay
};
return [consumer.queue, options];
}
function buildMiniflareBindingOptions(config, remoteProxyConnectionString, remoteBindingsEnabled) {
const bindings = config.bindings;
const textBlobBindings = { ...bindings.text_blobs };
const dataBlobBindings = { ...bindings.data_blobs };
const wasmBindings = { ...bindings.wasm_modules };
if (config.format === "service-worker" && config.bundle) {
const scriptPath4 = config.bundle.path;
const modulesRoot = import_node_path16.default.dirname(scriptPath4);
for (const { type, name: name2 } of config.bundle.modules) {
if (type === "text") {
textBlobBindings[getIdentifier(name2)] = import_node_path16.default.resolve(modulesRoot, name2);
} else if (type === "buffer") {
dataBlobBindings[getIdentifier(name2)] = import_node_path16.default.resolve(modulesRoot, name2);
} else if (type === "compiled-wasm") {
wasmBindings[getIdentifier(name2)] = import_node_path16.default.resolve(modulesRoot, name2);
}
}
}
const serviceBindings = {
...config.serviceBindings
};
for (const service of config.services ?? []) {
if (remoteProxyConnectionString && service.experimental_remote) {
serviceBindings[service.binding] = {
name: service.service,
props: service.props,
entrypoint: service.entrypoint,
remoteProxyConnectionString
};
continue;
}
serviceBindings[service.binding] = {
name: service.service,
entrypoint: service.entrypoint,
props: service.props
};
}
const tails = [];
for (const tail of config.tails ?? []) {
tails.push({ name: tail.service });
}
const classNameToUseSQLite = getClassNamesWhichUseSQLite(config.migrations);
const durableObjects = bindings.durable_objects?.bindings ?? [];
const externalWorkers = [];
const wrappedBindings = {};
if (bindings.ai?.binding && !remoteBindingsEnabled) {
externalWorkers.push({
name: `${EXTERNAL_AI_WORKER_NAME}:${config.name}`,
modules: [
{
type: "ESModule",
path: "index.mjs",
contents: EXTERNAL_AI_WORKER_SCRIPT
}
],
serviceBindings: {
FETCHER: getAIFetcher({
compliance_region: config.complianceRegion
})
}
});
wrappedBindings[bindings.ai.binding] = {
scriptName: `${EXTERNAL_AI_WORKER_NAME}:${config.name}`
};
}
if (bindings.ai && remoteBindingsEnabled) {
warnOrError("ai", bindings.ai.experimental_remote, "always-remote");
}
if (bindings.browser && remoteBindingsEnabled) {
warnOrError("browser", bindings.browser.experimental_remote, "remote");
}
if (bindings.mtls_certificates && remoteBindingsEnabled) {
for (const mtls of bindings.mtls_certificates) {
warnOrError(
"mtls_certificates",
mtls.experimental_remote,
"always-remote"
);
}
}
if (bindings.images?.binding && !config.imagesLocalMode && !remoteBindingsEnabled) {
externalWorkers.push({
name: `${EXTERNAL_IMAGES_WORKER_NAME}:${config.name}`,
modules: [
{
type: "ESModule",
path: "index.mjs",
contents: EXTERNAL_IMAGES_WORKER_SCRIPT
}
],
serviceBindings: {
FETCHER: getImagesRemoteFetcher({
compliance_region: config.complianceRegion
})
}
});
wrappedBindings[bindings.images?.binding] = {
scriptName: `${EXTERNAL_IMAGES_WORKER_NAME}:${config.name}`
};
}
if (bindings.vectorize && !remoteBindingsEnabled) {
for (const vectorizeBinding of bindings.vectorize) {
const bindingName = vectorizeBinding.binding;
const indexName = vectorizeBinding.index_name;
const indexVersion = "v2";
externalWorkers.push({
name: `${EXTERNAL_VECTORIZE_WORKER_NAME}-${config.name}-${bindingName}`,
modules: [
{
type: "ESModule",
path: "index.mjs",
contents: EXTERNAL_VECTORIZE_WORKER_SCRIPT
}
],
serviceBindings: {
FETCHER: MakeVectorizeFetcher(
{ compliance_region: config.complianceRegion },
indexName
)
},
bindings: {
INDEX_ID: indexName,
INDEX_VERSION: indexVersion
}
});
wrappedBindings[bindingName] = {
scriptName: `${EXTERNAL_VECTORIZE_WORKER_NAME}-${config.name}-${bindingName}`
};
}
}
const bindingOptions = {
bindings: {
...bindings.vars,
// emulate version_metadata binding via a JSON var
...bindings.version_metadata ? { [bindings.version_metadata.binding]: { id: (0, import_node_crypto4.randomUUID)(), tag: "" } } : void 0
},
textBlobBindings,
dataBlobBindings,
wasmBindings,
ai: bindings.ai && remoteProxyConnectionString ? {
binding: bindings.ai.binding,
remoteProxyConnectionString
} : void 0,
kvNamespaces: Object.fromEntries(
bindings.kv_namespaces?.map(
(kv) => kvNamespaceEntry(kv, remoteProxyConnectionString)
) ?? []
),
r2Buckets: Object.fromEntries(
bindings.r2_buckets?.map(
(r22) => r2BucketEntry(r22, remoteProxyConnectionString)
) ?? []
),
d1Databases: Object.fromEntries(
bindings.d1_databases?.map(
(d1) => d1DatabaseEntry(d1, remoteProxyConnectionString)
) ?? []
),
queueProducers: Object.fromEntries(
bindings.queues?.map(
(queue) => queueProducerEntry(queue, remoteProxyConnectionString)
) ?? []
),
queueConsumers: Object.fromEntries(
config.queueConsumers?.map(queueConsumerEntry) ?? []
),
pipelines: Object.fromEntries(
bindings.pipelines?.map(
(pipeline) => pipelineEntry(pipeline, remoteProxyConnectionString)
) ?? []
),
hyperdrives: Object.fromEntries(
bindings.hyperdrive?.map(hyperdriveEntry) ?? []
),
analyticsEngineDatasets: Object.fromEntries(
bindings.analytics_engine_datasets?.map((binding) => [
binding.binding,
{ dataset: binding.dataset ?? "dataset" }
]) ?? []
),
workflows: Object.fromEntries(
bindings.workflows?.map(
(workflow) => workflowEntry(workflow, remoteProxyConnectionString)
) ?? []
),
secretsStoreSecrets: Object.fromEntries(
bindings.secrets_store_secrets?.map((binding) => [
binding.binding,
binding
]) ?? []
),
helloWorld: Object.fromEntries(
bindings.unsafe_hello_world?.map((binding) => [
binding.binding,
binding
]) ?? []
),
workerLoaders: Object.fromEntries(
bindings.unsafe?.bindings?.filter((b6) => b6.type == "worker-loader").map((binding) => [binding.name, {}]) ?? []
),
email: {
send_email: bindings.send_email?.map((b6) => ({
...b6,
remoteProxyConnectionString: b6.experimental_remote && remoteProxyConnectionString ? remoteProxyConnectionString : void 0
}))
},
images: bindings.images && (config.imagesLocalMode || remoteBindingsEnabled) ? {
binding: bindings.images.binding,
remoteProxyConnectionString: bindings.images.experimental_remote && remoteProxyConnectionString ? remoteProxyConnectionString : void 0
} : void 0,
browserRendering: bindings.browser?.binding ? {
binding: bindings.browser.binding,
remoteProxyConnectionString: remoteBindingsEnabled && remoteProxyConnectionString && bindings.browser?.experimental_remote ? remoteProxyConnectionString : void 0
} : void 0,
vectorize: remoteBindingsEnabled && remoteProxyConnectionString ? Object.fromEntries(
bindings.vectorize?.filter((v7) => {
warnOrError("vectorize", v7.experimental_remote, "remote");
return v7.experimental_remote;
}).map((vectorize) => {
return [
vectorize.binding,
{
index_name: vectorize.index_name,
remoteProxyConnectionString
}
];
}) ?? []
) : void 0,
dispatchNamespaces: remoteBindingsEnabled && remoteProxyConnectionString ? Object.fromEntries(
bindings.dispatch_namespaces?.filter((d6) => {
warnOrError(
"dispatch_namespaces",
d6.experimental_remote,
"remote"
);
return d6.experimental_remote;
}).map(
(dispatchNamespace) => dispatchNamespaceEntry(
dispatchNamespace,
remoteProxyConnectionString
)
) ?? []
) : void 0,
durableObjects: Object.fromEntries(
durableObjects.map(
({ name: name2, class_name: className, script_name: scriptName }) => {
return [
name2,
{
className,
scriptName,
useSQLite: classNameToUseSQLite.get(className),
container: config.containerDOClassNames?.size && config.enableContainers ? getImageNameFromDOClassName({
doClassName: className,
containerDOClassNames: config.containerDOClassNames,
containerBuildId: config.containerBuildId
}) : void 0
}
];
}
)
),
ratelimits: Object.fromEntries(
bindings.unsafe?.bindings?.filter((b6) => b6.type == "ratelimit").map(ratelimitEntry) ?? []
),
mtlsCertificates: remoteBindingsEnabled && remoteProxyConnectionString ? Object.fromEntries(
bindings.mtls_certificates?.filter((d6) => {
warnOrError(
"mtls_certificates",
d6.experimental_remote,
"remote"
);
return d6.experimental_remote;
}).map((mtlsCertificate) => [
mtlsCertificate.binding,
{
remoteProxyConnectionString,
certificate_id: mtlsCertificate.certificate_id
}
]) ?? []
) : void 0,
serviceBindings,
wrappedBindings,
tails
};
return {
bindingOptions,
externalWorkers
};
}
function getDefaultPersistRoot(localPersistencePath) {
if (localPersistencePath !== null) {
const v3Path = import_node_path16.default.join(localPersistencePath, "v3");
return v3Path;
}
}
function buildAssetOptions(config) {
if (config.assets) {
return {
assets: {
directory: config.assets.directory,
binding: config.assets.binding,
routerConfig: config.assets.routerConfig,
assetConfig: config.assets.assetConfig
}
};
}
}
function buildSitesOptions({
legacyAssetPaths
}) {
if (legacyAssetPaths !== void 0) {
const { baseDirectory, assetDirectory, includePatterns, excludePatterns } = legacyAssetPaths;
return {
sitePath: import_node_path16.default.join(baseDirectory, assetDirectory),
siteInclude: includePatterns.length > 0 ? includePatterns : void 0,
siteExclude: excludePatterns.length > 0 ? excludePatterns : void 0
};
}
}
async function buildMiniflareOptions(log2, config, proxyToUserWorkerAuthenticationSecret, remoteProxyConnectionString, remoteBindingsEnabled, onDevRegistryUpdate) {
if (config.crons?.length && !config.testScheduled) {
if (!didWarnMiniflareCronSupport) {
didWarnMiniflareCronSupport = true;
logger.warn(
"Miniflare does not currently trigger scheduled Workers automatically.\nRefer to https://developers.cloudflare.com/workers/configuration/cron-triggers/#test-cron-triggers for more details "
);
}
}
if (!remoteBindingsEnabled) {
if (config.bindings.ai) {
if (!didWarnAiAccountUsage) {
didWarnAiAccountUsage = true;
logger.warn(
"Using Workers AI always accesses your Cloudflare account in order to run AI models, and so will incur usage charges even in local development."
);
}
}
if (!config.bindVectorizeToProd && config.bindings.vectorize?.length) {
logger.warn(
"Vectorize local bindings are not supported yet. You may use the `--experimental-vectorize-bind-to-prod` flag to bind to your production index in local dev mode."
);
config.bindings.vectorize = [];
}
if (config.bindings.vectorize?.length) {
if (!didWarnMiniflareVectorizeSupport) {
didWarnMiniflareVectorizeSupport = true;
logger.warn(
"You are using Vectorize as a remote binding (through `--experimental-vectorize-bind-to-prod`). It may incur usage charges and modify your databases even in local development. "
);
}
}
}
const upstream = typeof config.localUpstream === "string" ? `${config.upstreamProtocol}://${config.localUpstream}` : void 0;
const { sourceOptions, entrypointNames } = await buildSourceOptions(config);
const { bindingOptions, externalWorkers } = buildMiniflareBindingOptions(
config,
remoteProxyConnectionString,
remoteBindingsEnabled
);
const sitesOptions = buildSitesOptions(config);
const defaultPersistRoot = getDefaultPersistRoot(config.localPersistencePath);
const assetOptions = buildAssetOptions(config);
const options = {
host: config.initialIp,
port: config.initialPort,
inspectorPort: config.inspect ? config.inspectorPort : void 0,
liveReload: config.liveReload,
upstream,
unsafeDevRegistryPath: config.devRegistry,
unsafeDevRegistryDurableObjectProxy: true,
unsafeHandleDevRegistryUpdate: onDevRegistryUpdate,
unsafeProxySharedSecret: proxyToUserWorkerAuthenticationSecret,
unsafeTriggerHandlers: true,
// The way we run Miniflare instances with wrangler dev is that there are two:
// - one holding the proxy worker,
// - and one holding the user worker.
// The issue with that setup is that end users would see two sets of request logs from Miniflare!
// Instead of hiding all logs from this Miniflare instance, we specifically hide the request logs,
// allowing other logs to be shown to the user (such as details about emails being triggered)
logRequests: false,
log: log2,
verbose: logger.loggerLevel === "debug",
handleRuntimeStdio: handleRuntimeStdioWithStructuredLogs,
structuredWorkerdLogs: true,
defaultPersistRoot,
workers: [
{
name: getName(config),
compatibilityDate: config.compatibilityDate,
compatibilityFlags: config.compatibilityFlags,
...sourceOptions,
...bindingOptions,
...sitesOptions,
...assetOptions,
// Allow each entrypoint to be accessed directly over `127.0.0.1:0`
unsafeDirectSockets: entrypointNames.map((name2) => ({
host: "127.0.0.1",
port: 0,
entrypoint: name2,
proxy: true
})),
containerEngine: config.containerEngine
},
...externalWorkers
]
};
return options;
}
function getImageNameFromDOClassName(options) {
(0, import_node_assert5.default)(
options.containerBuildId,
"Build ID should be set if containers are defined and enabled"
);
if (options.containerDOClassNames.has(options.doClassName)) {
return {
imageName: getDevContainerImageName(
options.doClassName,
options.containerBuildId
)
};
}
}
var import_node_assert5, import_node_crypto4, import_node_path16, import_miniflare8, EXTERNAL_SERVICE_WORKER_NAME, WranglerLog, DEFAULT_WORKER_NAME, IDENTIFIER_UNSAFE_REGEXP, didWarnMiniflareCronSupport, didWarnMiniflareVectorizeSupport, didWarnAiAccountUsage;
var init_miniflare = __esm({
"src/dev/miniflare/index.ts"() {
init_import_meta_url();
import_node_assert5 = __toESM(require("assert"));
import_node_crypto4 = require("crypto");
import_node_path16 = __toESM(require("path"));
init_containers_shared();
import_miniflare8 = require("miniflare");
init_fetcher();
init_module_collection();
init_source_url();
init_fetcher2();
init_logger();
init_update_check();
init_print_bindings();
init_fetcher3();
init_class_names_sqlite();
init_stdio();
EXTERNAL_SERVICE_WORKER_NAME = "__WRANGLER_EXTERNAL_DURABLE_OBJECTS_WORKER";
WranglerLog = class extends import_miniflare8.Log {
static {
__name(this, "WranglerLog");
}
#warnedCompatibilityDateFallback = false;
log(message) {
if (message.includes(EXTERNAL_SERVICE_WORKER_NAME)) {
return;
}
super.log(message);
}
warn(message) {
if (message.startsWith("The latest compatibility date supported by")) {
if (this.#warnedCompatibilityDateFallback) {
return;
}
this.#warnedCompatibilityDateFallback = true;
return void updateCheck().then((maybeNewVersion) => {
if (maybeNewVersion === void 0) {
return;
}
message += [
"",
"Features enabled by your requested compatibility date may not be available.",
`Upgrade to \`wrangler@${maybeNewVersion}\` to remove this warning.`
].join("\n");
super.warn(message);
});
}
super.warn(message);
}
};
DEFAULT_WORKER_NAME = "worker";
__name(getName, "getName");
IDENTIFIER_UNSAFE_REGEXP = /[^a-zA-Z0-9_$]/g;
__name(getIdentifier, "getIdentifier");
__name(castLogLevel, "castLogLevel");
__name(buildLog, "buildLog");
__name(buildSourceOptions, "buildSourceOptions");
__name(getRemoteId, "getRemoteId");
__name(kvNamespaceEntry, "kvNamespaceEntry");
__name(r2BucketEntry, "r2BucketEntry");
__name(d1DatabaseEntry, "d1DatabaseEntry");
__name(queueProducerEntry, "queueProducerEntry");
__name(pipelineEntry, "pipelineEntry");
__name(hyperdriveEntry, "hyperdriveEntry");
__name(workflowEntry, "workflowEntry");
__name(dispatchNamespaceEntry, "dispatchNamespaceEntry");
__name(ratelimitEntry, "ratelimitEntry");
__name(queueConsumerEntry, "queueConsumerEntry");
__name(buildMiniflareBindingOptions, "buildMiniflareBindingOptions");
__name(getDefaultPersistRoot, "getDefaultPersistRoot");
__name(buildAssetOptions, "buildAssetOptions");
__name(buildSitesOptions, "buildSitesOptions");
didWarnMiniflareCronSupport = false;
didWarnMiniflareVectorizeSupport = false;
didWarnAiAccountUsage = false;
__name(buildMiniflareOptions, "buildMiniflareOptions");
__name(getImageNameFromDOClassName, "getImageNameFromDOClassName");
}
});
// src/api/startDevWorker/devtools.ts
var init_devtools = __esm({
"src/api/startDevWorker/devtools.ts"() {
init_import_meta_url();
}
});
// src/api/startDevWorker/events.ts
function castErrorCause(cause) {
if (cause instanceof Error) {
return cause;
}
const error2 = new Error();
error2.cause = cause;
return error2;
}
var init_events = __esm({
"src/api/startDevWorker/events.ts"() {
init_import_meta_url();
init_devtools();
__name(castErrorCause, "castErrorCause");
}
});
// src/api/startDevWorker/BaseController.ts
var import_node_events, TypedEventEmitterImpl, Controller, RuntimeController;
var init_BaseController = __esm({
"src/api/startDevWorker/BaseController.ts"() {
init_import_meta_url();
import_node_events = require("events");
TypedEventEmitterImpl = import_node_events.EventEmitter;
Controller = class extends TypedEventEmitterImpl {
static {
__name(this, "Controller");
}
emitErrorEvent(data) {
this.emit("error", data);
}
};
RuntimeController = class extends Controller {
static {
__name(this, "RuntimeController");
}
};
}
});
// src/api/startDevWorker/utils.ts
function createDeferred(previousDeferred) {
let resolve25, reject;
const newPromise = new Promise((_resolve, _reject) => {
resolve25 = _resolve;
reject = _reject;
});
(0, import_node_assert6.default)(resolve25);
(0, import_node_assert6.default)(reject);
previousDeferred?.resolve(newPromise);
return {
promise: newPromise,
resolve: resolve25,
reject
};
}
function assertNever(_value) {
}
function unwrapHook(hook, ...args) {
return typeof hook === "function" ? hook(...args) : hook;
}
async function getBinaryFileContents(file) {
if ("contents" in file) {
if (file.contents instanceof Buffer) {
return file.contents;
}
return Buffer.from(file.contents);
}
return (0, import_promises5.readFile)(file.path);
}
function convertConfigBindingsToStartWorkerBindings(configBindings) {
const { queues, ...bindings } = configBindings;
return convertCfWorkerInitBindingsToBindings({
...bindings,
queues: queues.producers?.map((q6) => ({ ...q6, queue_name: q6.queue }))
});
}
function convertCfWorkerInitBindingsToBindings(inputBindings) {
const output = {};
const bindingsIterable = Object.entries(inputBindings);
for (const [type, info] of bindingsIterable) {
if (info === void 0) {
continue;
}
switch (type) {
case "vars": {
for (const [key, value] of Object.entries(info)) {
if (typeof value === "string") {
output[key] = { type: "plain_text", value };
} else {
output[key] = { type: "json", value };
}
}
break;
}
case "kv_namespaces": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "kv_namespace", ...x6 };
}
break;
}
case "send_email": {
for (const { name: name2, ...x6 } of info) {
output[name2] = { type: "send_email", ...x6 };
}
break;
}
case "wasm_modules": {
for (const [key, value] of Object.entries(info)) {
if (typeof value === "string") {
output[key] = { type: "wasm_module", source: { path: value } };
} else {
output[key] = { type: "wasm_module", source: { contents: value } };
}
}
break;
}
case "text_blobs": {
for (const [key, value] of Object.entries(info)) {
output[key] = { type: "text_blob", source: { path: value } };
}
break;
}
case "data_blobs": {
for (const [key, value] of Object.entries(info)) {
if (typeof value === "string") {
output[key] = { type: "data_blob", source: { path: value } };
} else {
output[key] = { type: "data_blob", source: { contents: value } };
}
}
break;
}
case "browser": {
const { binding, ...x6 } = info;
output[binding] = { type: "browser", ...x6 };
break;
}
case "durable_objects": {
for (const { name: name2, ...x6 } of info.bindings) {
output[name2] = { type: "durable_object_namespace", ...x6 };
}
break;
}
case "workflows": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "workflow", ...x6 };
}
break;
}
case "queues": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "queue", ...x6 };
}
break;
}
case "r2_buckets": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "r2_bucket", ...x6 };
}
break;
}
case "d1_databases": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "d1", ...x6 };
}
break;
}
case "services": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "service", ...x6 };
}
break;
}
case "analytics_engine_datasets": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "analytics_engine", ...x6 };
}
break;
}
case "dispatch_namespaces": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "dispatch_namespace", ...x6 };
}
break;
}
case "mtls_certificates": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "mtls_certificate", ...x6 };
}
break;
}
case "logfwdr": {
for (const { name: name2, ...x6 } of info.bindings) {
output[name2] = { type: "logfwdr", ...x6 };
}
break;
}
case "ai": {
const { binding, ...x6 } = info;
output[binding] = { type: "ai", ...x6 };
break;
}
case "images": {
const { binding, ...x6 } = info;
output[binding] = { type: "images", ...x6 };
break;
}
case "version_metadata": {
const { binding, ...x6 } = info;
output[binding] = { type: "version_metadata", ...x6 };
break;
}
case "hyperdrive": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "hyperdrive", ...x6 };
}
break;
}
case "vectorize": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "vectorize", ...x6 };
}
break;
}
case "unsafe": {
for (const { type: unsafeType, name: name2, ...data } of info.bindings ?? []) {
output[name2] = { type: `unsafe_${unsafeType}`, ...data };
}
break;
}
case "assets": {
output[info["binding"]] = { type: "assets" };
break;
}
case "pipelines": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "pipeline", ...x6 };
}
break;
}
case "secrets_store_secrets": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "secrets_store_secret", ...x6 };
}
break;
}
case "unsafe_hello_world": {
for (const { binding, ...x6 } of info) {
output[binding] = { type: "unsafe_hello_world", ...x6 };
}
break;
}
default: {
assertNever(type);
}
}
}
return output;
}
async function convertBindingsToCfWorkerInitBindings(inputBindings) {
const bindings = {
vars: void 0,
kv_namespaces: void 0,
send_email: void 0,
wasm_modules: void 0,
text_blobs: void 0,
browser: void 0,
ai: void 0,
images: void 0,
version_metadata: void 0,
data_blobs: void 0,
durable_objects: void 0,
queues: void 0,
r2_buckets: void 0,
workflows: void 0,
d1_databases: void 0,
vectorize: void 0,
hyperdrive: void 0,
secrets_store_secrets: void 0,
services: void 0,
analytics_engine_datasets: void 0,
dispatch_namespaces: void 0,
mtls_certificates: void 0,
logfwdr: void 0,
unsafe: void 0,
assets: void 0,
pipelines: void 0,
unsafe_hello_world: void 0
};
const fetchers = {};
for (const [name2, binding] of Object.entries(inputBindings ?? {})) {
if (binding.type === "plain_text") {
bindings.vars ??= {};
bindings.vars[name2] = binding.value;
} else if (binding.type === "json") {
bindings.vars ??= {};
bindings.vars[name2] = binding.value;
} else if (binding.type === "kv_namespace") {
bindings.kv_namespaces ??= [];
bindings.kv_namespaces.push({ ...binding, binding: name2 });
} else if (binding.type === "send_email") {
bindings.send_email ??= [];
bindings.send_email.push({ ...binding, name: name2 });
} else if (binding.type === "wasm_module") {
bindings.wasm_modules ??= {};
bindings.wasm_modules[name2] = await getBinaryFileContents(binding.source);
} else if (binding.type === "text_blob") {
bindings.text_blobs ??= {};
if (typeof binding.source.path === "string") {
bindings.text_blobs[name2] = binding.source.path;
} else if ("contents" in binding.source) {
throw new Error(
"Cannot provide text_blob contents directly in CfWorkerInitBindings"
);
}
} else if (binding.type === "data_blob") {
bindings.data_blobs ??= {};
bindings.data_blobs[name2] = await getBinaryFileContents(binding.source);
} else if (binding.type === "browser") {
bindings.browser = { ...binding, binding: name2 };
} else if (binding.type === "ai") {
bindings.ai = { ...binding, binding: name2 };
} else if (binding.type === "images") {
bindings.images = { ...binding, binding: name2 };
} else if (binding.type === "version_metadata") {
bindings.version_metadata = { binding: name2 };
} else if (binding.type === "durable_object_namespace") {
bindings.durable_objects ??= { bindings: [] };
bindings.durable_objects.bindings.push({ ...binding, name: name2 });
} else if (binding.type === "queue") {
bindings.queues ??= [];
bindings.queues.push({ ...binding, binding: name2 });
} else if (binding.type === "r2_bucket") {
bindings.r2_buckets ??= [];
bindings.r2_buckets.push({ ...binding, binding: name2 });
} else if (binding.type === "d1") {
bindings.d1_databases ??= [];
bindings.d1_databases.push({ ...binding, binding: name2 });
} else if (binding.type === "vectorize") {
bindings.vectorize ??= [];
bindings.vectorize.push({ ...binding, binding: name2 });
} else if (binding.type === "hyperdrive") {
bindings.hyperdrive ??= [];
bindings.hyperdrive.push({ ...binding, binding: name2 });
} else if (binding.type === "service") {
bindings.services ??= [];
bindings.services.push({ ...binding, binding: name2 });
} else if (binding.type === "fetcher") {
fetchers[name2] = binding.fetcher;
} else if (binding.type === "analytics_engine") {
bindings.analytics_engine_datasets ??= [];
bindings.analytics_engine_datasets.push({ ...binding, binding: name2 });
} else if (binding.type === "dispatch_namespace") {
bindings.dispatch_namespaces ??= [];
bindings.dispatch_namespaces.push({ ...binding, binding: name2 });
} else if (binding.type === "mtls_certificate") {
bindings.mtls_certificates ??= [];
bindings.mtls_certificates.push({ ...binding, binding: name2 });
} else if (binding.type === "pipeline") {
bindings.pipelines ??= [];
bindings.pipelines.push({ ...binding, binding: name2 });
} else if (binding.type === "logfwdr") {
bindings.logfwdr ??= { bindings: [] };
bindings.logfwdr.bindings.push({ ...binding, name: name2 });
} else if (binding.type === "workflow") {
bindings.workflows ??= [];
bindings.workflows.push({ ...binding, binding: name2 });
} else if (binding.type === "secrets_store_secret") {
bindings.secrets_store_secrets ??= [];
bindings.secrets_store_secrets.push({ ...binding, binding: name2 });
} else if (binding.type === "unsafe_hello_world") {
bindings.unsafe_hello_world ??= [];
bindings.unsafe_hello_world.push({ ...binding, binding: name2 });
} else if (isUnsafeBindingType(binding.type)) {
bindings.unsafe ??= {
bindings: [],
metadata: void 0,
capnp: void 0
};
const { type, ...data } = binding;
bindings.unsafe.bindings?.push({
type: type.slice("unsafe_".length),
name: name2,
...data
});
}
}
return { bindings, fetchers };
}
function isUnsafeBindingType(type) {
return type.startsWith("unsafe_");
}
function extractBindingsOfType(type, bindings) {
return Object.entries(bindings ?? {}).filter(
(binding) => binding[1].type === type
).map((binding) => ({
...binding[1],
binding: binding[0],
name: binding[0]
}));
}
var import_node_assert6, import_promises5;
var init_utils2 = __esm({
"src/api/startDevWorker/utils.ts"() {
init_import_meta_url();
import_node_assert6 = __toESM(require("assert"));
import_promises5 = require("fs/promises");
__name(createDeferred, "createDeferred");
__name(assertNever, "assertNever");
__name(unwrapHook, "unwrapHook");
__name(getBinaryFileContents, "getBinaryFileContents");
__name(convertConfigBindingsToStartWorkerBindings, "convertConfigBindingsToStartWorkerBindings");
__name(convertCfWorkerInitBindingsToBindings, "convertCfWorkerInitBindingsToBindings");
__name(convertBindingsToCfWorkerInitBindings, "convertBindingsToCfWorkerInitBindings");
__name(isUnsafeBindingType, "isUnsafeBindingType");
__name(extractBindingsOfType, "extractBindingsOfType");
}
});
// ../../node_modules/.pnpm/get-port@7.0.0/node_modules/get-port/index.js
async function getPorts(options) {
let ports;
let exclude2 = /* @__PURE__ */ new Set();
if (options) {
if (options.port) {
ports = typeof options.port === "number" ? [options.port] : options.port;
}
if (options.exclude) {
const excludeIterable = options.exclude;
if (typeof excludeIterable[Symbol.iterator] !== "function") {
throw new TypeError("The `exclude` option must be an iterable.");
}
for (const element of excludeIterable) {
if (typeof element !== "number") {
throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");
}
if (!Number.isSafeInteger(element)) {
throw new TypeError(`Number ${element} in the exclude option is not a safe integer and can't be used`);
}
}
exclude2 = new Set(excludeIterable);
}
}
if (timeout === void 0) {
timeout = setTimeout(() => {
timeout = void 0;
lockedPorts.old = lockedPorts.young;
lockedPorts.young = /* @__PURE__ */ new Set();
}, releaseOldLockedPortsIntervalMs);
if (timeout.unref) {
timeout.unref();
}
}
const hosts = getLocalHosts();
for (const port of portCheckSequence(ports)) {
try {
if (exclude2.has(port)) {
continue;
}
let availablePort = await getAvailablePort({ ...options, port }, hosts);
while (lockedPorts.old.has(availablePort) || lockedPorts.young.has(availablePort)) {
if (port !== 0) {
throw new Locked(port);
}
availablePort = await getAvailablePort({ ...options, port }, hosts);
}
lockedPorts.young.add(availablePort);
return availablePort;
} catch (error2) {
if (!["EADDRINUSE", "EACCES"].includes(error2.code) && !(error2 instanceof Locked)) {
throw error2;
}
}
}
throw new Error("No available ports found");
}
var import_node_net, import_node_os4, Locked, lockedPorts, releaseOldLockedPortsIntervalMs, timeout, getLocalHosts, checkAvailablePort, getAvailablePort, portCheckSequence;
var init_get_port = __esm({
"../../node_modules/.pnpm/get-port@7.0.0/node_modules/get-port/index.js"() {
init_import_meta_url();
import_node_net = __toESM(require("net"), 1);
import_node_os4 = __toESM(require("os"), 1);
Locked = class extends Error {
static {
__name(this, "Locked");
}
constructor(port) {
super(`${port} is locked`);
}
};
lockedPorts = {
old: /* @__PURE__ */ new Set(),
young: /* @__PURE__ */ new Set()
};
releaseOldLockedPortsIntervalMs = 1e3 * 15;
getLocalHosts = /* @__PURE__ */ __name(() => {
const interfaces = import_node_os4.default.networkInterfaces();
const results = /* @__PURE__ */ new Set([void 0, "0.0.0.0"]);
for (const _interface of Object.values(interfaces)) {
for (const config of _interface) {
results.add(config.address);
}
}
return results;
}, "getLocalHosts");
checkAvailablePort = /* @__PURE__ */ __name((options) => new Promise((resolve25, reject) => {
const server = import_node_net.default.createServer();
server.unref();
server.on("error", reject);
server.listen(options, () => {
const { port } = server.address();
server.close(() => {
resolve25(port);
});
});
}), "checkAvailablePort");
getAvailablePort = /* @__PURE__ */ __name(async (options, hosts) => {
if (options.host || options.port === 0) {
return checkAvailablePort(options);
}
for (const host of hosts) {
try {
await checkAvailablePort({ port: options.port, host });
} catch (error2) {
if (!["EADDRNOTAVAIL", "EINVAL"].includes(error2.code)) {
throw error2;
}
}
}
return options.port;
}, "getAvailablePort");
portCheckSequence = /* @__PURE__ */ __name(function* (ports) {
if (ports) {
yield* ports;
}
yield 0;
}, "portCheckSequence");
__name(getPorts, "getPorts");
}
});
// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/wrangler/templates/remoteBindings/ProxyServerWorker.ts
var import_node_path17, scriptPath, ProxyServerWorker_default;
var init_ProxyServerWorker = __esm({
"embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/wrangler/templates/remoteBindings/ProxyServerWorker.ts"() {
init_import_meta_url();
import_node_path17 = __toESM(require("path"));
scriptPath = import_node_path17.default.resolve(__dirname, "..", "wrangler-dist/ProxyServerWorker.js");
ProxyServerWorker_default = scriptPath;
}
});
// ../../node_modules/.pnpm/readdirp@4.0.1/node_modules/readdirp/esm/index.js
function defaultOptions() {
return {
root: ".",
fileFilter: /* @__PURE__ */ __name((_path) => true, "fileFilter"),
directoryFilter: /* @__PURE__ */ __name((_path) => true, "directoryFilter"),
type: FILE_TYPE,
lstat: false,
depth: 2147483648,
alwaysStat: false,
highWaterMark: 4096
};
}
var import_fs10, import_promises6, import_stream, import_path7, RECURSIVE_ERROR_CODE, NORMAL_FLOW_ERRORS, FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE, ALL_TYPES, DIR_TYPES, FILE_TYPES, isNormalFlowError, wantBigintFsStats, emptyFn, normalizeFilter, ReaddirpStream, readdirp;
var init_esm3 = __esm({
"../../node_modules/.pnpm/readdirp@4.0.1/node_modules/readdirp/esm/index.js"() {
init_import_meta_url();
import_fs10 = require("fs");
import_promises6 = require("fs/promises");
import_stream = require("stream");
import_path7 = require("path");
__name(defaultOptions, "defaultOptions");
RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
FILE_TYPE = "files";
DIR_TYPE = "directories";
FILE_DIR_TYPE = "files_directories";
EVERYTHING_TYPE = "all";
ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
DIR_TYPES = /* @__PURE__ */ new Set([DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]);
FILE_TYPES = /* @__PURE__ */ new Set([FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]);
isNormalFlowError = /* @__PURE__ */ __name((error2) => NORMAL_FLOW_ERRORS.has(error2.code), "isNormalFlowError");
wantBigintFsStats = process.platform === "win32";
emptyFn = /* @__PURE__ */ __name((_path) => true, "emptyFn");
normalizeFilter = /* @__PURE__ */ __name((filter) => {
if (filter === void 0)
return emptyFn;
if (typeof filter === "function")
return filter;
if (typeof filter === "string") {
const fl = filter.trim();
return (entry) => entry.basename === fl;
}
if (Array.isArray(filter)) {
const trItems = filter.map((item) => item.trim());
return (entry) => trItems.some((f6) => entry.basename === f6);
}
return emptyFn;
}, "normalizeFilter");
ReaddirpStream = class extends import_stream.Readable {
static {
__name(this, "ReaddirpStream");
}
constructor(options = {}) {
super({
objectMode: true,
autoDestroy: true,
highWaterMark: options.highWaterMark
});
const opts = { ...defaultOptions(), ...options };
const { root, type } = opts;
this._fileFilter = normalizeFilter(opts.fileFilter);
this._directoryFilter = normalizeFilter(opts.directoryFilter);
const statMethod = opts.lstat ? import_fs10.lstatSync : import_fs10.statSync;
if (wantBigintFsStats) {
this._stat = (path72) => statMethod(path72, { bigint: true });
} else {
this._stat = statMethod;
}
this._maxDepth = opts.depth;
this._wantsDir = DIR_TYPES.has(type);
this._wantsFile = FILE_TYPES.has(type);
this._wantsEverything = type === EVERYTHING_TYPE;
this._root = (0, import_path7.resolve)(root);
this._isDirent = !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 par = this.parent;
const fil = par && par.files;
if (fil && fil.length > 0) {
const { path: path72, depth } = par;
const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path72));
for (const entry of slice) {
if (!entry) {
batch--;
return;
}
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 (error2) {
this.destroy(error2);
} finally {
this.reading = false;
}
}
async _exploreDir(path72, depth) {
let files;
try {
files = await (0, import_promises6.readdir)(path72, this._rdOptions);
} catch (error2) {
this._onError(error2);
}
return { files, depth, path: path72 };
}
_formatEntry(dirent, path72) {
let entry;
const basename7 = this._isDirent ? dirent.name : dirent;
try {
const fullPath = (0, import_path7.resolve)((0, import_path7.join)(path72, basename7));
entry = { path: (0, import_path7.relative)(this._root, fullPath), fullPath, basename: basename7 };
entry[this._statsProp] = this._isDirent ? dirent : this._stat(fullPath);
} catch (err) {
this._onError(err);
return;
}
return entry;
}
_onError(err) {
if (isNormalFlowError(err) && !this.destroyed) {
this.emit("warn", err);
} else {
this.destroy(err);
}
}
async _getEntryType(entry) {
if (!entry && this._statsProp in entry) {
return "";
}
const stats = entry[this._statsProp];
if (stats.isFile())
return "file";
if (stats.isDirectory())
return "directory";
if (stats && stats.isSymbolicLink()) {
const full = entry.fullPath;
try {
const entryRealPath = await (0, import_promises6.realpath)(full);
const entryRealPathStats = (0, import_fs10.lstatSync)(entryRealPath);
if (entryRealPathStats.isFile()) {
return "file";
}
if (entryRealPathStats.isDirectory()) {
const len = entryRealPath.length;
if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_path7.sep) {
const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
recursiveError.code = RECURSIVE_ERROR_CODE;
return this._onError(recursiveError);
}
return "directory";
}
} catch (error2) {
this._onError(error2);
return "";
}
}
}
_includeAsFile(entry) {
const stats = entry && entry[this._statsProp];
return stats && this._wantsEverything && !stats.isDirectory();
}
};
readdirp = /* @__PURE__ */ __name((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);
}, "readdirp");
}
});
// ../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/handler.js
function createFsWatchInstance(path72, options, listener, errHandler, emitRaw) {
const handleEvent = /* @__PURE__ */ __name((rawEvent, evPath) => {
listener(path72);
emitRaw(rawEvent, evPath, { watchedPath: path72 });
if (evPath && path72 !== evPath) {
fsWatchBroadcast(sysPath.resolve(path72, evPath), KEY_LISTENERS, sysPath.join(path72, evPath));
}
}, "handleEvent");
try {
return (0, import_fs11.watch)(path72, {
persistent: options.persistent
}, handleEvent);
} catch (error2) {
errHandler(error2);
return void 0;
}
}
var import_fs11, import_promises7, sysPath, import_os, STR_DATA, STR_END, STR_CLOSE, EMPTY_FN, pl, isWindows2, isMacos, isLinux, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH, statMethods, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, binaryExtensions, isBinaryPath, foreach, addAndConvert, clearItem, delFromSet, isEmptySet, FsWatchInstances, fsWatchBroadcast, setFsWatchListener, FsWatchFileInstances, setFsWatchFileListener, NodeFsHandler;
var init_handler = __esm({
"../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/handler.js"() {
init_import_meta_url();
import_fs11 = require("fs");
import_promises7 = require("fs/promises");
sysPath = __toESM(require("path"), 1);
import_os = require("os");
STR_DATA = "data";
STR_END = "end";
STR_CLOSE = "close";
EMPTY_FN = /* @__PURE__ */ __name(() => {
}, "EMPTY_FN");
pl = process.platform;
isWindows2 = pl === "win32";
isMacos = pl === "darwin";
isLinux = pl === "linux";
isIBMi = (0, import_os.type)() === "OS400";
EVENTS = {
ALL: "all",
READY: "ready",
ADD: "add",
CHANGE: "change",
ADD_DIR: "addDir",
UNLINK: "unlink",
UNLINK_DIR: "unlinkDir",
RAW: "raw",
ERROR: "error"
};
EV = EVENTS;
THROTTLE_MODE_WATCH = "watch";
statMethods = { lstat: import_promises7.lstat, stat: import_promises7.stat };
KEY_LISTENERS = "listeners";
KEY_ERR = "errHandlers";
KEY_RAW = "rawEmitters";
HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
binaryExtensions = /* @__PURE__ */ new Set([
"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"
]);
isBinaryPath = /* @__PURE__ */ __name((filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()), "isBinaryPath");
foreach = /* @__PURE__ */ __name((val2, fn2) => {
if (val2 instanceof Set) {
val2.forEach(fn2);
} else {
fn2(val2);
}
}, "foreach");
addAndConvert = /* @__PURE__ */ __name((main2, prop, item) => {
let container = main2[prop];
if (!(container instanceof Set)) {
main2[prop] = container = /* @__PURE__ */ new Set([container]);
}
container.add(item);
}, "addAndConvert");
clearItem = /* @__PURE__ */ __name((cont) => (key) => {
const set = cont[key];
if (set instanceof Set) {
set.clear();
} else {
delete cont[key];
}
}, "clearItem");
delFromSet = /* @__PURE__ */ __name((main2, prop, item) => {
const container = main2[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete main2[prop];
}
}, "delFromSet");
isEmptySet = /* @__PURE__ */ __name((val2) => val2 instanceof Set ? val2.size === 0 : !val2, "isEmptySet");
FsWatchInstances = /* @__PURE__ */ new Map();
__name(createFsWatchInstance, "createFsWatchInstance");
fsWatchBroadcast = /* @__PURE__ */ __name((fullPath, listenerType, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont)
return;
foreach(cont[listenerType], (listener) => {
listener(val1, val2, val3);
});
}, "fsWatchBroadcast");
setFsWatchListener = /* @__PURE__ */ __name((path72, fullPath, options, handlers2) => {
const { listener, errHandler, rawEmitter } = handlers2;
let cont = FsWatchInstances.get(fullPath);
let watcher;
if (!options.persistent) {
watcher = createFsWatchInstance(path72, options, listener, errHandler, rawEmitter);
if (!watcher)
return;
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(
path72,
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 (error2) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
if (cont)
cont.watcherUnusable = true;
if (isWindows2 && error2.code === "EPERM") {
try {
const fd = await (0, import_promises7.open)(path72, "r");
await fd.close();
broadcastErr(error2);
} catch (err) {
}
} else {
broadcastErr(error2);
}
});
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);
}
};
}, "setFsWatchListener");
FsWatchFileInstances = /* @__PURE__ */ new Map();
setFsWatchFileListener = /* @__PURE__ */ __name((path72, fullPath, options, handlers2) => {
const { listener, rawEmitter } = handlers2;
let cont = FsWatchFileInstances.get(fullPath);
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
(0, import_fs11.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: (0, import_fs11.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(path72, curr));
}
})
};
FsWatchFileInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
(0, import_fs11.unwatchFile)(fullPath);
cont.options = cont.watcher = void 0;
Object.freeze(cont);
}
};
}, "setFsWatchFileListener");
NodeFsHandler = class {
static {
__name(this, "NodeFsHandler");
}
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error2) => fsW._handleError(error2);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param path to file or dir
* @param listener on fs change
* @returns closer for the watcher instance
*/
_watchWithNodeFs(path72, listener) {
const opts = this.fsw.options;
const directory = sysPath.dirname(path72);
const basename7 = sysPath.basename(path72);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename7);
const absolutePath = sysPath.resolve(path72);
const options = {
persistent: opts.persistent
};
if (!listener)
listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
const enableBin = opts.interval !== opts.binaryInterval;
options.interval = enableBin && isBinaryPath(basename7) ? opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path72, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw
});
} else {
closer = setFsWatchListener(path72, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
}
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @returns closer for the watcher instance
*/
_handleFile(file, stats, initialAdd) {
if (this.fsw.closed) {
return;
}
const dirname18 = sysPath.dirname(file);
const basename7 = sysPath.basename(file);
const parent = this.fsw._getWatchedDir(dirname18);
let prevStats = stats;
if (parent.has(basename7))
return;
const listener = /* @__PURE__ */ __name(async (path72, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats2 = await (0, import_promises7.stat)(file);
if (this.fsw.closed)
return;
const at2 = newStats2.atimeMs;
const mt = newStats2.mtimeMs;
if (!at2 || at2 <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV.CHANGE, file, newStats2);
}
if ((isMacos || isLinux) && prevStats.ino !== newStats2.ino) {
this.fsw._closeFile(path72);
prevStats = newStats2;
const closer2 = this._watchWithNodeFs(file, listener);
if (closer2)
this.fsw._addPathCloser(path72, closer2);
} else {
prevStats = newStats2;
}
} catch (error2) {
this.fsw._remove(dirname18, basename7);
}
} else if (parent.has(basename7)) {
const at2 = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at2 || at2 <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV.CHANGE, file, newStats);
}
prevStats = newStats;
}
}, "listener");
const closer = this._watchWithNodeFs(file, listener);
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV.ADD, file, 0))
return;
this.fsw._emit(EV.ADD, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param entry returned by readdirp
* @param directory path of dir being read
* @param path of this item
* @param item basename of this item
* @returns true if no more processing is needed for this entry.
*/
async _handleSymlink(entry, directory, path72, 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 (0, import_promises7.realpath)(path72);
} catch (e7) {
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, path72, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.ADD, path72, 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, "");
throttler = this.fsw._throttle("readdir", directory, 1e3);
if (!throttler)
return;
const previous = this.fsw._getWatchedDir(wh.path);
const current = /* @__PURE__ */ new Set();
let stream2 = this.fsw._readdirp(directory, {
fileFilter: /* @__PURE__ */ __name((entry) => wh.filterPath(entry), "fileFilter"),
directoryFilter: /* @__PURE__ */ __name((entry) => wh.filterDir(entry), "directoryFilter")
});
if (!stream2)
return;
stream2.on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream2 = void 0;
return;
}
const item = entry.path;
let path72 = sysPath.join(directory, item);
current.add(item);
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path72, item)) {
return;
}
if (this.fsw.closed) {
stream2 = void 0;
return;
}
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
path72 = sysPath.join(dir, sysPath.relative(dir, path72));
this._addToNodeFs(path72, initialAdd, wh, depth + 1);
}
}).on(EV.ERROR, this._boundHandleError);
return new Promise((resolve25, reject) => {
if (!stream2)
return reject();
stream2.once(STR_END, () => {
if (this.fsw.closed) {
stream2 = void 0;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve25(void 0);
previous.getChildren().filter((item) => {
return item !== directory && !current.has(item);
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream2 = 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 dir fs path
* @param stats
* @param initialAdd
* @param depth relative to user-supplied path
* @param target child path targeted for watch
* @param wh Common watch helpers for this path
* @param realpath
* @returns closer for the watcher instance.
*/
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
const tracked = parentDir.has(sysPath.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
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(realpath2)) {
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 path to file or ir
* @param initialAdd was the file added at watch instantiation?
* @param priorWh depth relative to user-supplied path
* @param depth Child path actually targeted for watch
* @param target Child path actually targeted for watch
*/
async _addToNodeFs(path72, initialAdd, priorWh, depth, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path72) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path72);
if (priorWh) {
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;
let closer;
if (stats.isDirectory()) {
const absPath = sysPath.resolve(path72);
const targetPath = follow ? await (0, import_promises7.realpath)(path72) : path72;
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 (0, import_promises7.realpath)(path72) : path72;
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, path72, wh, targetPath);
if (this.fsw.closed)
return;
if (targetPath !== void 0) {
this.fsw._symlinkPaths.set(sysPath.resolve(path72), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
if (closer)
this.fsw._addPathCloser(path72, closer);
return false;
} catch (error2) {
if (this.fsw._handleError(error2)) {
ready();
return path72;
}
}
}
};
}
});
// ../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/index.js
function arrify(item) {
return Array.isArray(item) ? item : [item];
}
function createPattern(matcher) {
if (typeof matcher === "function")
return matcher;
if (typeof matcher === "string")
return (string) => matcher === string;
if (matcher instanceof RegExp)
return (string) => matcher.test(string);
if (typeof matcher === "object" && matcher !== null) {
return (string) => {
if (matcher.path === string)
return true;
if (matcher.recursive) {
const relative15 = sysPath2.relative(matcher.path, string);
if (!relative15) {
return false;
}
return !relative15.startsWith("..") && !sysPath2.isAbsolute(relative15);
}
return false;
};
}
return () => false;
}
function normalizePath(path72) {
if (typeof path72 !== "string")
throw new Error("string expected");
path72 = sysPath2.normalize(path72);
path72 = path72.replace(/\\/g, "/");
let prepend = false;
if (path72.startsWith("//"))
prepend = true;
const DOUBLE_SLASH_RE2 = /\/\//;
while (path72.match(DOUBLE_SLASH_RE2))
path72 = path72.replace(DOUBLE_SLASH_RE2, "/");
if (prepend)
path72 = "/" + path72;
return path72;
}
function matchPatterns(patterns, testString, stats) {
const path72 = normalizePath(testString);
for (let index = 0; index < patterns.length; index++) {
const pattern = patterns[index];
if (pattern(path72, stats)) {
return true;
}
}
return false;
}
function anymatch(matchers, testString) {
if (matchers == null) {
throw new TypeError("anymatch: specify first argument");
}
const matchersArray = arrify(matchers);
const patterns = matchersArray.map((matcher) => createPattern(matcher));
if (testString == null) {
return (testString2, stats) => {
return matchPatterns(patterns, testString2, stats);
};
}
return matchPatterns(patterns, testString);
}
function watch(paths, options = {}) {
const watcher = new FSWatcher(options);
watcher.add(paths);
return watcher;
}
var import_fs12, import_promises8, import_events, sysPath2, SLASH, SLASH_SLASH, ONE_DOT, TWO_DOTS, STRING_TYPE, BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject, unifyPaths, toUnix, normalizePathToUnix, normalizeIgnored, getAbsolutePath, EMPTY_SET, DirEntry, STAT_METHOD_F, STAT_METHOD_L, WatchHelper, FSWatcher;
var init_esm4 = __esm({
"../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/index.js"() {
init_import_meta_url();
import_fs12 = require("fs");
import_promises8 = require("fs/promises");
import_events = require("events");
sysPath2 = __toESM(require("path"), 1);
init_esm3();
init_handler();
SLASH = "/";
SLASH_SLASH = "//";
ONE_DOT = ".";
TWO_DOTS = "..";
STRING_TYPE = "string";
BACK_SLASH_RE = /\\/g;
DOUBLE_SLASH_RE = /\/\//;
DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
REPLACER_RE = /^\.[/\\]/;
__name(arrify, "arrify");
isMatcherObject = /* @__PURE__ */ __name((matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp), "isMatcherObject");
__name(createPattern, "createPattern");
__name(normalizePath, "normalizePath");
__name(matchPatterns, "matchPatterns");
__name(anymatch, "anymatch");
unifyPaths = /* @__PURE__ */ __name((paths_) => {
const paths = arrify(paths_).flat();
if (!paths.every((p6) => typeof p6 === STRING_TYPE)) {
throw new TypeError(`Non-string provided as watch path: ${paths}`);
}
return paths.map(normalizePathToUnix);
}, "unifyPaths");
toUnix = /* @__PURE__ */ __name((string) => {
let str = string.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;
}, "toUnix");
normalizePathToUnix = /* @__PURE__ */ __name((path72) => toUnix(sysPath2.normalize(toUnix(path72))), "normalizePathToUnix");
normalizeIgnored = /* @__PURE__ */ __name((cwd2 = "") => (path72) => {
if (typeof path72 === "string") {
return normalizePathToUnix(sysPath2.isAbsolute(path72) ? path72 : sysPath2.join(cwd2, path72));
} else {
return path72;
}
}, "normalizeIgnored");
getAbsolutePath = /* @__PURE__ */ __name((path72, cwd2) => {
if (sysPath2.isAbsolute(path72)) {
return path72;
}
return sysPath2.join(cwd2, path72);
}, "getAbsolutePath");
EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
DirEntry = class {
static {
__name(this, "DirEntry");
}
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 (0, import_promises8.readdir)(dir);
} catch (err) {
if (this._removeWatcher) {
this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
}
}
}
has(item) {
const { items } = this;
if (!items)
return;
return items.has(item);
}
getChildren() {
const { items } = this;
if (!items)
return [];
return [...items.values()];
}
dispose() {
this.items.clear();
this.path = "";
this._removeWatcher = EMPTY_FN;
this.items = EMPTY_SET;
Object.freeze(this);
}
};
STAT_METHOD_F = "stat";
STAT_METHOD_L = "lstat";
WatchHelper = class {
static {
__name(this, "WatchHelper");
}
constructor(path72, follow, fsw) {
this.fsw = fsw;
const watchPath = path72;
this.path = path72 = path72.replace(REPLACER_RE, "");
this.watchPath = watchPath;
this.fullWatchPath = sysPath2.resolve(watchPath);
this.dirParts = [];
this.dirParts.forEach((parts) => {
if (parts.length > 1)
parts.pop();
});
this.followSymlinks = follow;
this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
}
entryPath(entry) {
return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
}
filterPath(entry) {
const { stats } = entry;
if (stats && stats.isSymbolicLink())
return this.filterDir(entry);
const resolvedPath2 = this.entryPath(entry);
return this.fsw._isntIgnored(resolvedPath2, stats) && this.fsw._hasReadPermissions(stats);
}
filterDir(entry) {
return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
}
};
FSWatcher = class extends import_events.EventEmitter {
static {
__name(this, "FSWatcher");
}
// Not indenting methods for history sake; for now.
constructor(_opts = {}) {
super();
this.closed = false;
this._closers = /* @__PURE__ */ new Map();
this._ignoredPaths = /* @__PURE__ */ new Set();
this._throttled = /* @__PURE__ */ new Map();
this._streams = /* @__PURE__ */ new Set();
this._symlinkPaths = /* @__PURE__ */ new Map();
this._watched = /* @__PURE__ */ new Map();
this._pendingWrites = /* @__PURE__ */ new Map();
this._pendingUnlinks = /* @__PURE__ */ new Map();
this._readyCount = 0;
this._readyEmitted = false;
const awf = _opts.awaitWriteFinish;
const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
const opts = {
// Defaults
persistent: true,
ignoreInitial: false,
ignorePermissionErrors: false,
interval: 100,
binaryInterval: 300,
followSymlinks: true,
usePolling: false,
// useAsync: false,
atomic: true,
// NOTE: overwritten later (depends on usePolling)
..._opts,
// Change format
ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
};
if (isIBMi)
opts.usePolling = true;
if (opts.atomic === void 0)
opts.atomic = !opts.usePolling;
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);
let readyCalls = 0;
this._emitReady = () => {
readyCalls++;
if (readyCalls >= this._readyCount) {
this._emitReady = EMPTY_FN;
this._readyEmitted = true;
process.nextTick(() => this.emit(EVENTS.READY));
}
};
this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
this._boundRemove = this._remove.bind(this);
this.options = opts;
this._nodeFsHandler = new NodeFsHandler(this);
Object.freeze(opts);
}
_addIgnoredPath(matcher) {
if (isMatcherObject(matcher)) {
for (const ignored of this._ignoredPaths) {
if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
return;
}
}
}
this._ignoredPaths.add(matcher);
}
_removeIgnoredPath(matcher) {
this._ignoredPaths.delete(matcher);
if (typeof matcher === "string") {
for (const ignored of this._ignoredPaths) {
if (isMatcherObject(ignored) && ignored.path === matcher) {
this._ignoredPaths.delete(ignored);
}
}
}
}
// Public methods
/**
* Adds paths to be watched on an existing FSWatcher instance.
* @param paths_ file or file list. Other arguments are unused
*/
add(paths_, _origAdd, _internal) {
const { cwd: cwd2 } = this.options;
this.closed = false;
this._closePromise = void 0;
let paths = unifyPaths(paths_);
if (cwd2) {
paths = paths.map((path72) => {
const absPath = getAbsolutePath(path72, cwd2);
return absPath;
});
}
paths.forEach((path72) => {
this._removeIgnoredPath(path72);
});
this._userIgnored = void 0;
if (!this._readyCount)
this._readyCount = 0;
this._readyCount += paths.length;
Promise.all(paths.map(async (path72) => {
const res = await this._nodeFsHandler._addToNodeFs(path72, !_internal, void 0, 0, _origAdd);
if (res)
this._emitReady();
return res;
})).then((results) => {
if (this.closed)
return;
results.forEach((item) => {
if (item)
this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
});
});
return this;
}
/**
* Close watchers or start ignoring events from specified paths.
*/
unwatch(paths_) {
if (this.closed)
return this;
const paths = unifyPaths(paths_);
const { cwd: cwd2 } = this.options;
paths.forEach((path72) => {
if (!sysPath2.isAbsolute(path72) && !this._closers.has(path72)) {
if (cwd2)
path72 = sysPath2.join(cwd2, path72);
path72 = sysPath2.resolve(path72);
}
this._closePath(path72);
this._addIgnoredPath(path72);
if (this._watched.has(path72)) {
this._addIgnoredPath({
path: path72,
recursive: true
});
}
this._userIgnored = void 0;
});
return this;
}
/**
* Close watchers and remove all listeners from watched paths.
*/
close() {
if (this._closePromise) {
return this._closePromise;
}
this.closed = true;
this.removeAllListeners();
const closers = [];
this._closers.forEach((closerList) => closerList.forEach((closer) => {
const promise = closer();
if (promise instanceof Promise)
closers.push(promise);
}));
this._streams.forEach((stream2) => stream2.destroy());
this._userIgnored = void 0;
this._readyCount = 0;
this._readyEmitted = false;
this._watched.forEach((dirent) => dirent.dispose());
this._closers.clear();
this._watched.clear();
this._streams.clear();
this._symlinkPaths.clear();
this._throttled.clear();
this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
return this._closePromise;
}
/**
* Expose list of watched paths
* @returns for chaining
*/
getWatched() {
const watchList = {};
this._watched.forEach((entry, dir) => {
const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
const index = key || ONE_DOT;
watchList[index] = entry.getChildren().sort();
});
return watchList;
}
emitWithAll(event, args) {
this.emit(...args);
if (event !== EVENTS.ERROR)
this.emit(EVENTS.ALL, ...args);
}
// Common helpers
// --------------
/**
* Normalize and emit events.
* Calling _emit DOES NOT MEAN emit() would be called!
* @param event Type of event
* @param path File or directory path
* @param stats arguments to be passed with event
* @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
async _emit(event, path72, stats) {
if (this.closed)
return;
const opts = this.options;
if (isWindows2)
path72 = sysPath2.normalize(path72);
if (opts.cwd)
path72 = sysPath2.relative(opts.cwd, path72);
const args = [event, path72];
if (stats != null)
args.push(stats);
const awf = opts.awaitWriteFinish;
let pw;
if (awf && (pw = this._pendingWrites.get(path72))) {
pw.lastChange = /* @__PURE__ */ new Date();
return this;
}
if (opts.atomic) {
if (event === EVENTS.UNLINK) {
this._pendingUnlinks.set(path72, args);
setTimeout(() => {
this._pendingUnlinks.forEach((entry, path73) => {
this.emit(...entry);
this.emit(EVENTS.ALL, ...entry);
this._pendingUnlinks.delete(path73);
});
}, typeof opts.atomic === "number" ? opts.atomic : 100);
return this;
}
if (event === EVENTS.ADD && this._pendingUnlinks.has(path72)) {
event = args[0] = EVENTS.CHANGE;
this._pendingUnlinks.delete(path72);
}
}
if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
const awfEmit = /* @__PURE__ */ __name((err, stats2) => {
if (err) {
event = args[0] = EVENTS.ERROR;
args[1] = err;
this.emitWithAll(event, args);
} else if (stats2) {
if (args.length > 2) {
args[2] = stats2;
} else {
args.push(stats2);
}
this.emitWithAll(event, args);
}
}, "awfEmit");
this._awaitWriteFinish(path72, awf.stabilityThreshold, event, awfEmit);
return this;
}
if (event === EVENTS.CHANGE) {
const isThrottled = !this._throttle(EVENTS.CHANGE, path72, 50);
if (isThrottled)
return this;
}
if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path72) : path72;
let stats2;
try {
stats2 = await (0, import_promises8.stat)(fullPath);
} catch (err) {
}
if (!stats2 || this.closed)
return;
args.push(stats2);
}
this.emitWithAll(event, args);
return this;
}
/**
* Common handler for errors
* @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
_handleError(error2) {
const code = error2 && error2.code;
if (error2 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
this.emit(EVENTS.ERROR, error2);
}
return error2 || this.closed;
}
/**
* Helper utility for throttling
* @param actionType type being throttled
* @param path being acted upon
* @param timeout duration of time to suppress duplicate actions
* @returns tracking object or false if action should be suppressed
*/
_throttle(actionType, path72, timeout2) {
if (!this._throttled.has(actionType)) {
this._throttled.set(actionType, /* @__PURE__ */ new Map());
}
const action = this._throttled.get(actionType);
if (!action)
throw new Error("invalid throttle");
const actionPath = action.get(path72);
if (actionPath) {
actionPath.count++;
return false;
}
let timeoutObject;
const clear = /* @__PURE__ */ __name(() => {
const item = action.get(path72);
const count = item ? item.count : 0;
action.delete(path72);
clearTimeout(timeoutObject);
if (item)
clearTimeout(item.timeoutObject);
return count;
}, "clear");
timeoutObject = setTimeout(clear, timeout2);
const thr = { timeoutObject, clear, count: 0 };
action.set(path72, 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 being acted upon
* @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
* @param event
* @param awfEmit Callback to be called when ready for event to be emitted.
*/
_awaitWriteFinish(path72, threshold, event, awfEmit) {
const awf = this.options.awaitWriteFinish;
if (typeof awf !== "object")
return;
const pollInterval = awf.pollInterval;
let timeoutHandler;
let fullPath = path72;
if (this.options.cwd && !sysPath2.isAbsolute(path72)) {
fullPath = sysPath2.join(this.options.cwd, path72);
}
const now = /* @__PURE__ */ new Date();
const writes = this._pendingWrites;
function awaitWriteFinishFn(prevStat) {
(0, import_fs12.stat)(fullPath, (err, curStat) => {
if (err || !writes.has(path72)) {
if (err && err.code !== "ENOENT")
awfEmit(err);
return;
}
const now2 = Number(/* @__PURE__ */ new Date());
if (prevStat && curStat.size !== prevStat.size) {
writes.get(path72).lastChange = now2;
}
const pw = writes.get(path72);
const df = now2 - pw.lastChange;
if (df >= threshold) {
writes.delete(path72);
awfEmit(void 0, curStat);
} else {
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
}
});
}
__name(awaitWriteFinishFn, "awaitWriteFinishFn");
if (!writes.has(path72)) {
writes.set(path72, {
lastChange: now,
cancelWait: /* @__PURE__ */ __name(() => {
writes.delete(path72);
clearTimeout(timeoutHandler);
return event;
}, "cancelWait")
});
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
}
}
/**
* Determines whether user has asked to ignore this path.
*/
_isIgnored(path72, stats) {
if (this.options.atomic && DOT_RE.test(path72))
return true;
if (!this._userIgnored) {
const { cwd: cwd2 } = this.options;
const ign = this.options.ignored;
const ignored = (ign || []).map(normalizeIgnored(cwd2));
const ignoredPaths = [...this._ignoredPaths];
const list = [...ignoredPaths.map(normalizeIgnored(cwd2)), ...ignored];
this._userIgnored = anymatch(list, void 0);
}
return this._userIgnored(path72, stats);
}
_isntIgnored(path72, stat8) {
return !this._isIgnored(path72, stat8);
}
/**
* Provides a set of common helpers and properties relating to symlink handling.
* @param path file or directory pattern being watched
*/
_getWatchHelpers(path72) {
return new WatchHelper(path72, this.options.followSymlinks, this);
}
// Directory helpers
// -----------------
/**
* Provides directory tracking objects
* @param directory path of the directory
*/
_getWatchedDir(directory) {
const dir = sysPath2.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: https://stackoverflow.com/a/11781404/1358405
*/
_hasReadPermissions(stats) {
if (this.options.ignorePermissionErrors)
return true;
return Boolean(Number(stats.mode) & 256);
}
/**
* Handles emitting unlink events for
* files and directories, and via recursion, for
* files and directories within directories that are unlinked
* @param directory within which the following item is located
* @param item base path of item/directory
*/
_remove(directory, item, isDirectory2) {
const path72 = sysPath2.join(directory, item);
const fullPath = sysPath2.resolve(path72);
isDirectory2 = isDirectory2 != null ? isDirectory2 : this._watched.has(path72) || this._watched.has(fullPath);
if (!this._throttle("remove", path72, 100))
return;
if (!isDirectory2 && this._watched.size === 1) {
this.add(directory, item, true);
}
const wp = this._getWatchedDir(path72);
const nestedDirectoryChildren = wp.getChildren();
nestedDirectoryChildren.forEach((nested) => this._remove(path72, 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 = path72;
if (this.options.cwd)
relPath = sysPath2.relative(this.options.cwd, path72);
if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
const event = this._pendingWrites.get(relPath).cancelWait();
if (event === EVENTS.ADD)
return;
}
this._watched.delete(path72);
this._watched.delete(fullPath);
const eventName = isDirectory2 ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
if (wasTracked && !this._isIgnored(path72))
this._emit(eventName, path72);
this._closePath(path72);
}
/**
* Closes all watchers for a path
*/
_closePath(path72) {
this._closeFile(path72);
const dir = sysPath2.dirname(path72);
this._getWatchedDir(dir).remove(sysPath2.basename(path72));
}
/**
* Closes only file-specific watchers
*/
_closeFile(path72) {
const closers = this._closers.get(path72);
if (!closers)
return;
closers.forEach((closer) => closer());
this._closers.delete(path72);
}
_addPathCloser(path72, closer) {
if (!closer)
return;
let list = this._closers.get(path72);
if (!list) {
list = [];
this._closers.set(path72, list);
}
list.push(closer);
}
_readdirp(root, opts) {
if (this.closed)
return;
const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
let stream2 = readdirp(root, options);
this._streams.add(stream2);
stream2.once(STR_CLOSE, () => {
stream2 = void 0;
});
stream2.once(STR_END, () => {
if (stream2) {
this._streams.delete(stream2);
stream2 = void 0;
}
});
return stream2;
}
};
__name(watch, "watch");
}
});
// src/utils/dedent.ts
function dedent2(strings, ...values) {
const raw = String.raw({ raw: strings }, ...values);
let lines = raw.split("\n");
(0, import_node_assert7.default)(lines.length > 0);
if (lines[lines.length - 1].trim() === "") {
lines = lines.slice(0, lines.length - 1);
}
let minIndent = "";
let minIndentLength = Infinity;
for (const line of lines.slice(1)) {
const indent = line.match(/^[ \t]*/)?.[0];
if (indent != null && indent.length < minIndentLength) {
minIndent = indent;
minIndentLength = indent.length;
}
}
if (lines.length > 0 && lines[0].trim() === "") {
lines = lines.slice(1);
}
lines = lines.map(
(line) => line.startsWith(minIndent) ? line.substring(minIndent.length) : line
);
return lines.join("\n");
}
var import_node_assert7;
var init_dedent = __esm({
"src/utils/dedent.ts"() {
init_import_meta_url();
import_node_assert7 = __toESM(require("assert"));
__name(dedent2, "dedent");
}
});
// src/deployment-bundle/apply-middleware.ts
async function applyMiddlewareLoaderFacade(entry, tmpDirPath, middleware) {
tmpDirPath = fs9.realpathSync(tmpDirPath);
const middlewareIdentifiers = middleware.map((m6, index) => [
`__MIDDLEWARE_${index}__`,
path19.resolve(getBasePath(), m6.path)
]);
const dynamicFacadePath = path19.join(
tmpDirPath,
"middleware-insertion-facade.js"
);
const imports = middlewareIdentifiers.map(
([id, middlewarePath]) => (
/*javascript*/
`import * as ${id} from "${prepareFilePath(
middlewarePath
)}";`
)
).join("\n");
const middlewareFns = middlewareIdentifiers.map(([m6]) => `${m6}.default`).join(",");
if (entry.format === "modules") {
await fs9.promises.writeFile(
dynamicFacadePath,
dedent2`
import worker, * as OTHER_EXPORTS from "${prepareFilePath(entry.file)}";
${imports}
export * from "${prepareFilePath(entry.file)}";
const MIDDLEWARE_TEST_INJECT = "__INJECT_FOR_TESTING_WRANGLER_MIDDLEWARE__";
export const __INTERNAL_WRANGLER_MIDDLEWARE__ = [
${false ? `...(OTHER_EXPORTS[MIDDLEWARE_TEST_INJECT] ?? []),` : ""}
${middlewareFns}
]
export default worker;
`
);
const targetPathLoader = path19.join(
tmpDirPath,
"middleware-loader.entry.ts"
);
const loaderPath = path19.resolve(
getBasePath(),
"templates/middleware/loader-modules.ts"
);
const baseLoader = await fs9.promises.readFile(loaderPath, "utf-8");
const transformedLoader = baseLoader.replaceAll("__ENTRY_POINT__", prepareFilePath(dynamicFacadePath)).replace(
"./common",
prepareFilePath(
path19.resolve(getBasePath(), "templates/middleware/common.ts")
)
);
await fs9.promises.writeFile(targetPathLoader, transformedLoader);
return {
entry: {
...entry,
file: targetPathLoader
}
};
} else {
const loaderSwPath = path19.resolve(
getBasePath(),
"templates/middleware/loader-sw.ts"
);
await fs9.promises.writeFile(
dynamicFacadePath,
dedent2`
import { __facade_registerInternal__ } from "${prepareFilePath(loaderSwPath)}";
${imports}
__facade_registerInternal__([${middlewareFns}])
`
);
return {
entry,
inject: [dynamicFacadePath]
};
}
}
function prepareFilePath(filePath) {
return JSON.stringify(filePath).slice(1, -1);
}
var fs9, path19;
var init_apply_middleware = __esm({
"src/deployment-bundle/apply-middleware.ts"() {
init_import_meta_url();
fs9 = __toESM(require("fs"));
path19 = __toESM(require("path"));
init_paths();
init_dedent();
__name(applyMiddlewareLoaderFacade, "applyMiddlewareLoaderFacade");
__name(prepareFilePath, "prepareFilePath");
}
});
// src/deployment-bundle/build-failures.ts
function rewriteNodeCompatBuildFailure(errors, compatMode = null) {
for (const error2 of errors) {
const match2 = nodeBuiltinResolveErrorText.exec(error2.text);
if (match2 !== null) {
let text = `The package "${match2[1]}" wasn't found on the file system but is built into node.
`;
if (compatMode === null || compatMode === "als") {
text += `- Add the "nodejs_compat" compatibility flag to your project.
`;
} else if (compatMode === "v1" && !match2[1].startsWith("node:")) {
text += `- Make sure to prefix the module name with "node:" or update your compatibility_date to 2024-09-23 or later.
`;
}
error2.notes = [
{
location: null,
text
}
];
}
}
}
function isBuildFailure(err) {
return typeof err === "object" && err !== null && "errors" in err && "warnings" in err;
}
function isBuildFailureFromCause(err) {
return typeof err === "object" && err !== null && "cause" in err && isBuildFailure(err.cause);
}
var import_node_module, nodeBuiltinResolveErrorText;
var init_build_failures = __esm({
"src/deployment-bundle/build-failures.ts"() {
init_import_meta_url();
import_node_module = require("module");
nodeBuiltinResolveErrorText = new RegExp(
'^Could not resolve "(' + import_node_module.builtinModules.join("|") + "|" + import_node_module.builtinModules.map((module3) => "node:" + module3).join("|") + ')"$'
);
__name(rewriteNodeCompatBuildFailure, "rewriteNodeCompatBuildFailure");
__name(isBuildFailure, "isBuildFailure");
__name(isBuildFailureFromCause, "isBuildFailureFromCause");
}
});
// src/deployment-bundle/dedupe-modules.ts
function dedupeModulesByName(modules) {
return Object.values(
modules.reduce(
(moduleMap, module3) => {
moduleMap[module3.name] = module3;
return moduleMap;
},
{}
)
);
}
var init_dedupe_modules = __esm({
"src/deployment-bundle/dedupe-modules.ts"() {
init_import_meta_url();
__name(dedupeModulesByName, "dedupeModulesByName");
}
});
// src/deployment-bundle/entry-point-from-metafile.ts
function getEntryPointFromMetafile(entryFile, metafile) {
const entryPoints = Object.entries(metafile.outputs).filter(
([_path, output]) => output.entryPoint !== void 0
);
if (entryPoints.length !== 1) {
const entryPointList = entryPoints.map(([_input, output]) => output.entryPoint).join("\n");
(0, import_node_assert8.default)(
entryPoints.length > 0,
`Cannot find entry-point "${entryFile}" in generated bundle.
${entryPointList}`
);
(0, import_node_assert8.default)(
entryPoints.length < 2,
`More than one entry-point found for generated bundle.
${entryPointList}`
);
}
const [relativePath, entryPoint] = entryPoints[0];
return {
relativePath,
exports: entryPoint.exports,
dependencies: entryPoint.inputs
};
}
var import_node_assert8;
var init_entry_point_from_metafile = __esm({
"src/deployment-bundle/entry-point-from-metafile.ts"() {
init_import_meta_url();
import_node_assert8 = __toESM(require("assert"));
__name(getEntryPointFromMetafile, "getEntryPointFromMetafile");
}
});
// src/deployment-bundle/esbuild-plugins/cloudflare-internal.ts
var cloudflareInternalPlugin;
var init_cloudflare_internal = __esm({
"src/deployment-bundle/esbuild-plugins/cloudflare-internal.ts"() {
init_import_meta_url();
init_dedent();
cloudflareInternalPlugin = {
name: "cloudflare-internal-imports",
setup(pluginBuild) {
const paths = /* @__PURE__ */ new Set();
pluginBuild.onStart(() => paths.clear());
pluginBuild.onResolve({ filter: /^cloudflare:.*/ }, (args) => {
paths.add(args.path);
return { external: true };
});
pluginBuild.onEnd(() => {
if (pluginBuild.initialOptions.format === "iife" && paths.size > 0) {
const pathList = new Intl.ListFormat("en-US").format(
Array.from(paths.keys()).map((p6) => `"${p6}"`).sort()
);
return {
errors: [
{
text: dedent2`
Unexpected external import of ${pathList}.
Your worker has no default export, which means it is assumed to be a Service Worker format Worker.
Did you mean to create a ES Module format Worker?
If so, try adding \`export default { ... }\` in your entry-point.
See https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/.
`
}
]
};
}
});
}
};
}
});
// src/deployment-bundle/esbuild-plugins/config-provider.ts
function configProviderPlugin(config) {
return {
name: "middleware-config-provider",
setup(build5) {
build5.onResolve({ filter: /^config:/ }, (args) => ({
path: args.path,
namespace: "wrangler-config"
}));
build5.onLoad(
{ filter: /.*/, namespace: "wrangler-config" },
async (args) => {
const middleware = args.path.split("config:middleware/")[1];
if (!config[middleware]) {
throw new Error(`No config found for ${middleware}`);
}
return {
loader: "json",
contents: JSON.stringify(config[middleware])
};
}
);
}
};
}
var init_config_provider = __esm({
"src/deployment-bundle/esbuild-plugins/config-provider.ts"() {
init_import_meta_url();
__name(configProviderPlugin, "configProviderPlugin");
}
});
// src/deployment-bundle/esbuild-plugins/als-external.ts
var asyncLocalStoragePlugin;
var init_als_external = __esm({
"src/deployment-bundle/esbuild-plugins/als-external.ts"() {
init_import_meta_url();
asyncLocalStoragePlugin = {
name: "async-local-storage-imports",
setup(pluginBuild) {
pluginBuild.onResolve({ filter: /^node:async_hooks(\/|$)/ }, () => {
return { external: true };
});
}
};
}
});
// src/deployment-bundle/esbuild-plugins/hybrid-nodejs-compat.ts
function nodejsHybridPlugin({
compatibilityDate,
compatibilityFlags
}) {
return {
name: "hybrid-nodejs_compat",
async setup(build5) {
const { defineEnv } = await import("unenv");
const { getCloudflarePreset } = await import("@cloudflare/unenv-preset");
const { alias, inject, external, polyfill: polyfill2 } = defineEnv({
presets: [
getCloudflarePreset({
compatibilityDate,
compatibilityFlags
}),
{
alias: {
// Force esbuild to use the node implementation of debug instead of unenv's no-op stub.
// The alias is processed by handleUnenvAliasedPackages which uses require.resolve().
debug: "debug"
}
}
],
npmShims: true
}).env;
errorOnServiceWorkerFormat(build5);
handleRequireCallsToNodeJSBuiltins(build5);
handleUnenvAliasedPackages(build5, alias, external);
handleNodeJSGlobals(build5, inject, polyfill2);
}
};
}
function errorOnServiceWorkerFormat(build5) {
const paths = /* @__PURE__ */ new Set();
build5.onStart(() => paths.clear());
build5.onResolve({ filter: NODEJS_MODULES_RE }, (args) => {
paths.add(args.path);
return null;
});
build5.onEnd(() => {
if (build5.initialOptions.format === "iife" && paths.size > 0) {
const pathList = new Intl.ListFormat("en-US").format(
Array.from(paths.keys()).map((p6) => `"${p6}"`).sort()
);
return {
errors: [
{
text: esm_default2`
Unexpected external import of ${pathList}.
Your worker has no default export, which means it is assumed to be a Service Worker format Worker.
Did you mean to create a ES Module format Worker?
If so, try adding \`export default { ... }\` in your entry-point.
See https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/.
`
}
]
};
}
});
}
function handleRequireCallsToNodeJSBuiltins(build5) {
build5.onResolve({ filter: NODEJS_MODULES_RE }, (args) => {
if (args.kind === "require-call") {
return {
path: args.path,
namespace: REQUIRED_NODE_BUILT_IN_NAMESPACE
};
}
});
build5.onLoad(
{ filter: /.*/, namespace: REQUIRED_NODE_BUILT_IN_NAMESPACE },
({ path: path72 }) => {
return {
contents: esm_default2`
import libDefault from '${path72}';
module.exports = libDefault;`,
loader: "js"
};
}
);
}
function handleUnenvAliasedPackages(build5, alias, external) {
const aliasAbsolute = {};
for (const [module3, unresolvedAlias] of Object.entries(alias)) {
try {
aliasAbsolute[module3] = require.resolve(unresolvedAlias);
} catch {
}
}
const UNENV_ALIAS_RE = new RegExp(
`^(${Object.keys(aliasAbsolute).join("|")})$`
);
build5.onResolve({ filter: UNENV_ALIAS_RE }, (args) => {
const unresolvedAlias = alias[args.path];
if (args.kind === "require-call" && (unresolvedAlias.startsWith("unenv/npm/") || unresolvedAlias.startsWith("unenv/mock/"))) {
return {
path: args.path,
namespace: REQUIRED_UNENV_ALIAS_NAMESPACE
};
}
return {
path: aliasAbsolute[args.path],
external: external.includes(unresolvedAlias)
};
});
build5.onLoad(
{ filter: /.*/, namespace: REQUIRED_UNENV_ALIAS_NAMESPACE },
({ path: path72 }) => {
return {
contents: esm_default2`
import * as esm from '${path72}';
module.exports = Object.entries(esm)
.filter(([k,]) => k !== 'default')
.reduce((cjs, [k, value]) =>
Object.defineProperty(cjs, k, { value, enumerable: true }),
"default" in esm ? esm.default : {}
);
`,
loader: "js"
};
}
);
}
function handleNodeJSGlobals(build5, inject, polyfill2) {
const UNENV_VIRTUAL_MODULE_RE = /_virtual_unenv_global_polyfill-(.+)$/;
const prefix = import_node_path18.default.resolve(
getBasePath(),
"_virtual_unenv_global_polyfill-"
);
const injectsByModule = /* @__PURE__ */ new Map();
const virtualModulePathToSpecifier = /* @__PURE__ */ new Map();
for (const [injectedName, moduleSpecifier] of Object.entries(inject)) {
const [module3, exportName, importName] = Array.isArray(moduleSpecifier) ? [moduleSpecifier[0], moduleSpecifier[1], moduleSpecifier[1]] : [moduleSpecifier, "default", "defaultExport"];
if (!injectsByModule.has(module3)) {
injectsByModule.set(module3, []);
virtualModulePathToSpecifier.set(
prefix + module3.replaceAll("/", "-"),
module3
);
}
injectsByModule.get(module3).push({ injectedName, exportName, importName });
}
build5.initialOptions.inject = [
...build5.initialOptions.inject ?? [],
// Inject the virtual modules
...virtualModulePathToSpecifier.keys(),
// Inject the polyfills - needs an absolute path
...polyfill2.map((m6) => require.resolve(m6))
];
build5.onResolve({ filter: UNENV_VIRTUAL_MODULE_RE }, ({ path: path72 }) => ({
path: path72
}));
build5.onLoad({ filter: UNENV_VIRTUAL_MODULE_RE }, ({ path: path72 }) => {
const module3 = virtualModulePathToSpecifier.get(path72);
(0, import_node_assert9.default)(module3, `Expected ${path72} to be mapped to a module specifier`);
const injects = injectsByModule.get(module3);
(0, import_node_assert9.default)(injects, `Expected ${module3} to inject values`);
const imports = injects.map(
({ exportName, importName }) => importName === exportName ? exportName : `${exportName} as ${importName}`
);
return {
contents: esm_default2`
import { ${imports.join(", ")} } from "${module3}";
${injects.map(({ injectedName, importName }) => `globalThis.${injectedName} = ${importName};`).join("\n")}
`
};
});
}
var import_node_assert9, import_node_module2, import_node_path18, REQUIRED_NODE_BUILT_IN_NAMESPACE, REQUIRED_UNENV_ALIAS_NAMESPACE, NODEJS_MODULES_RE;
var init_hybrid_nodejs_compat = __esm({
"src/deployment-bundle/esbuild-plugins/hybrid-nodejs-compat.ts"() {
init_import_meta_url();
import_node_assert9 = __toESM(require("assert"));
import_node_module2 = require("module");
import_node_path18 = __toESM(require("path"));
init_esm2();
init_paths();
REQUIRED_NODE_BUILT_IN_NAMESPACE = "node-built-in-modules";
REQUIRED_UNENV_ALIAS_NAMESPACE = "required-unenv-alias";
__name(nodejsHybridPlugin, "nodejsHybridPlugin");
NODEJS_MODULES_RE = new RegExp(`^(node:)?(${import_node_module2.builtinModules.join("|")})$`);
__name(errorOnServiceWorkerFormat, "errorOnServiceWorkerFormat");
__name(handleRequireCallsToNodeJSBuiltins, "handleRequireCallsToNodeJSBuiltins");
__name(handleUnenvAliasedPackages, "handleUnenvAliasedPackages");
__name(handleNodeJSGlobals, "handleNodeJSGlobals");
}
});
// src/deployment-bundle/esbuild-plugins/nodejs-compat.ts
function toList(items, absWorkingDir) {
return items.map((i5) => ` - ${source_default.blue((0, import_path8.relative)(absWorkingDir ?? "/", i5))}`).join("\n");
}
var import_path8, nodejsCompatPlugin;
var init_nodejs_compat = __esm({
"src/deployment-bundle/esbuild-plugins/nodejs-compat.ts"() {
init_import_meta_url();
import_path8 = require("path");
init_source();
init_logger();
init_dedent();
nodejsCompatPlugin = /* @__PURE__ */ __name((mode) => ({
name: "nodejs_compat-imports",
setup(pluginBuild) {
const seen = /* @__PURE__ */ new Set();
const warnedPackages = /* @__PURE__ */ new Map();
pluginBuild.onStart(() => {
seen.clear();
warnedPackages.clear();
});
pluginBuild.onResolve(
{ filter: /node:.*/ },
async ({ path: path72, kind, resolveDir, importer }) => {
const specifier = `${path72}:${kind}:${resolveDir}:${importer}`;
if (seen.has(specifier)) {
return;
}
seen.add(specifier);
const result = await pluginBuild.resolve(path72, {
kind,
resolveDir,
importer
});
if (result.errors.length > 0) {
const pathWarnedPackages = warnedPackages.get(path72) ?? [];
pathWarnedPackages.push(importer);
warnedPackages.set(path72, pathWarnedPackages);
return { external: true };
}
return result;
}
);
pluginBuild.onEnd(() => {
if (pluginBuild.initialOptions.format === "iife" && warnedPackages.size > 0) {
const paths = new Intl.ListFormat("en-US").format(
Array.from(warnedPackages.keys()).map((p6) => `"${p6}"`).sort()
);
return {
errors: [
{
text: dedent2`
Unexpected external import of ${paths}.
Your worker has no default export, which means it is assumed to be a Service Worker format Worker.
Did you mean to create a ES Module format Worker?
If so, try adding \`export default { ... }\` in your entry-point.
See https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/.
`
}
]
};
}
});
pluginBuild.onEnd(() => {
if (mode !== "v1") {
warnedPackages.forEach((importers, path72) => {
logger.warn(
dedent2`
The package "${path72}" wasn't found on the file system but is built into node.
Your Worker may throw errors at runtime unless you enable the "nodejs_compat" compatibility flag. Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details. Imported from:
${toList(importers, pluginBuild.initialOptions.absWorkingDir)}`
);
});
}
});
}
}), "nodejsCompatPlugin");
__name(toList, "toList");
}
});
// src/deployment-bundle/esbuild-plugins/nodejs-plugins.ts
function getNodeJSCompatPlugins({
mode,
compatibilityDate,
compatibilityFlags
}) {
switch (mode) {
case "als":
return [asyncLocalStoragePlugin, nodejsCompatPlugin(mode)];
case "v1":
return [nodejsCompatPlugin(mode)];
case "v2":
return [nodejsHybridPlugin({ compatibilityDate, compatibilityFlags })];
case null:
return [nodejsCompatPlugin(mode)];
}
}
var init_nodejs_plugins = __esm({
"src/deployment-bundle/esbuild-plugins/nodejs-plugins.ts"() {
init_import_meta_url();
init_als_external();
init_hybrid_nodejs_compat();
init_nodejs_compat();
__name(getNodeJSCompatPlugins, "getNodeJSCompatPlugins");
}
});
// src/deployment-bundle/bundle.ts
function getBuildConditions() {
const envVar = getBuildConditionsFromEnv();
if (envVar !== void 0) {
return envVar.split(",");
} else {
return ["workerd", "worker", "browser"];
}
}
function getBuildPlatform() {
const platform3 = getBuildPlatformFromEnv();
if (platform3 !== void 0 && !["browser", "node", "neutral"].includes(platform3)) {
throw new UserError(
"Invalid esbuild platform configuration defined in the WRANGLER_BUILD_PLATFORM environment variable.\nValid platform values are: 'browser', 'node' and 'neutral'."
);
}
return platform3;
}
async function bundleWorker(entry, destination, {
bundle,
moduleCollector = noopModuleCollector,
additionalModules = [],
doBindings,
workflowBindings,
jsxFactory,
jsxFragment,
entryName,
watch: watch2,
tsconfig,
minify,
keepNames,
nodejsCompatMode,
compatibilityDate,
compatibilityFlags,
alias,
define,
checkFetch,
targetConsumer,
testScheduled,
inject: injectOption,
sourcemap,
plugins,
isOutfile,
local,
projectRoot,
defineNavigatorUserAgent,
external,
metafile
}) {
const tmpDir = getWranglerTmpDir(projectRoot, "bundle");
const entryFile = entry.file;
const middlewareToLoad = [];
if (targetConsumer === "dev" && !process.env.WRANGLER_DISABLE_REQUEST_BODY_DRAINING) {
middlewareToLoad.push({
name: "ensure-req-body-drained",
path: "templates/middleware/middleware-ensure-req-body-drained.ts",
supports: ["modules", "service-worker"]
});
}
if (targetConsumer === "dev" && !!testScheduled) {
middlewareToLoad.push({
name: "scheduled",
path: "templates/middleware/middleware-scheduled.ts",
supports: ["modules", "service-worker"]
});
}
if (targetConsumer === "dev" && local) {
middlewareToLoad.push({
name: "miniflare3-json-error",
path: "templates/middleware/middleware-miniflare3-json-error.ts",
supports: ["modules", "service-worker"]
});
}
let initialBuildResult;
const initialBuildResultPromise = new Promise(
(resolve25) => initialBuildResult = resolve25
);
const buildResultPlugin = {
name: "Initial build result plugin",
setup(build5) {
build5.onEnd(initialBuildResult);
}
};
const inject = injectOption ?? [];
if (checkFetch) {
const checkedFetchFileToInject = path20.join(tmpDir.path, "checked-fetch.js");
if (checkFetch && !fs10.existsSync(checkedFetchFileToInject)) {
fs10.writeFileSync(
checkedFetchFileToInject,
fs10.readFileSync(
path20.resolve(getBasePath(), "templates/checked-fetch.js")
)
);
}
inject.push(checkedFetchFileToInject);
}
if (getFlag("MULTIWORKER")) {
middlewareToLoad.push({
name: "patch-console-prefix",
path: "templates/middleware/middleware-patch-console-prefix.ts",
supports: ["modules", "service-worker"],
config: {
prefix: source_default.blue(`[${entry.name}]`)
}
});
}
for (const middleware of middlewareToLoad) {
if (!middleware.supports.includes(entry.format)) {
throw new UserError(
`Your Worker is written using the "${entry.format}" format, which isn't supported by the "${middleware.name}" middleware. To use "${middleware.name}" middleware, convert your Worker to the "${middleware.supports[0]}" format`
);
}
}
if (middlewareToLoad.length > 0 || process.env.EXPERIMENTAL_MIDDLEWARE === "true") {
const result2 = await applyMiddlewareLoaderFacade(
entry,
tmpDir.path,
middlewareToLoad
);
entry = result2.entry;
inject.push(...result2.inject ?? []);
}
if (watch2) {
inject.push(path20.resolve(getBasePath(), "templates/modules-watch-stub.js"));
}
const aliasPlugin = {
name: "alias",
setup(build5) {
if (!alias) {
return;
}
const filter = new RegExp(
Object.keys(alias).map((key) => escapeRegex(key)).join("|")
);
build5.onResolve({ filter }, (args) => {
const aliasPath = alias[args.path];
if (aliasPath) {
return {
// resolve with node resolution
path: require.resolve(aliasPath, {
// From the esbuild alias docs: "Note that when an import path is substituted using an alias, the resulting import path is resolved in the working directory instead of in the directory containing the source file with the import path."
// https://esbuild.github.io/api/#alias:~:text=Note%20that%20when%20an%20import%20path%20is%20substituted%20using%20an%20alias%2C%20the%20resulting%20import%20path%20is%20resolved%20in%20the%20working%20directory%20instead%20of%20in%20the%20directory%20containing%20the%20source%20file%20with%20the%20import%20path.
paths: [entry.projectRoot]
})
};
}
});
}
};
const buildOptions = {
// Don't use entryFile here as the file may have been changed when applying the middleware
entryPoints: [entry.file],
bundle,
absWorkingDir: entry.projectRoot,
keepNames,
...isOutfile ? {
outdir: void 0,
outfile: destination,
entryNames: void 0
} : {
outdir: destination,
outfile: void 0,
entryNames: entryName || path20.parse(entryFile).name
},
inject,
external: bundle ? ["__STATIC_CONTENT_MANIFEST", ...external ? external : []] : void 0,
format: entry.format === "modules" ? "esm" : "iife",
target: COMMON_ESBUILD_OPTIONS.target,
sourcemap: sourcemap ?? true,
// Include a reference to the output folder in the sourcemap.
// This is omitted by default, but we need it to properly resolve source paths in error output.
sourceRoot: destination,
minify,
metafile: true,
conditions: getBuildConditions(),
platform: getBuildPlatform(),
...{
define: {
...defineNavigatorUserAgent ? { "navigator.userAgent": `"Cloudflare-Workers"` } : {},
// use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
// when we do a build of wrangler. (re: https://github.com/cloudflare/workers-sdk/issues/1477)
"process.env.NODE_ENV": `"${process.env["NODE_ENV"]}"`,
...define
}
},
loader: COMMON_ESBUILD_OPTIONS.loader,
plugins: [
aliasPlugin,
moduleCollector.plugin,
...getNodeJSCompatPlugins({
mode: nodejsCompatMode ?? null,
compatibilityDate,
compatibilityFlags
}),
cloudflareInternalPlugin,
buildResultPlugin,
...plugins || [],
configProviderPlugin(
Object.fromEntries(
middlewareToLoad.filter((m6) => m6.config !== void 0).map((m6) => [m6.name, m6.config])
)
)
],
...jsxFactory && { jsxFactory },
...jsxFragment && { jsxFragment },
...tsconfig && { tsconfig },
// The default logLevel is "warning". So that we can rewrite errors before
// logging, we disable esbuild's default logging, and log build failures
// ourselves.
logLevel: "silent"
};
let result;
let stop;
try {
if (watch2) {
const ctx = await esbuild.context(buildOptions);
await ctx.watch();
result = await initialBuildResultPromise;
if (result.errors.length > 0) {
throw new BuildFailure(
"Initial build failed.",
result.errors,
result.warnings
);
}
stop = /* @__PURE__ */ __name(async function() {
tmpDir.remove();
await ctx.dispose();
}, "stop");
} else {
result = await esbuild.build(buildOptions);
if (metafile && result.metafile) {
let metaFilePath;
if (typeof metafile === "string") {
metaFilePath = path20.resolve(metafile);
} else if (isOutfile) {
metaFilePath = `${destination}.bundle-meta.json`;
} else {
metaFilePath = path20.join(destination, "bundle-meta.json");
}
const metaJson = JSON.stringify(result.metafile, null, 2);
fs10.writeFileSync(metaFilePath, metaJson);
}
stop = /* @__PURE__ */ __name(async function() {
tmpDir.remove();
}, "stop");
}
} catch (e7) {
if (isBuildFailure(e7)) {
rewriteNodeCompatBuildFailure(e7.errors, nodejsCompatMode);
}
throw e7;
}
const entryPoint = getEntryPointFromMetafile(entryFile, result.metafile);
const notExportedDOs = doBindings.filter((x6) => !x6.script_name && !entryPoint.exports.includes(x6.class_name)).map((x6) => x6.class_name);
if (notExportedDOs.length) {
const relativePath = path20.relative(process.cwd(), entryFile);
throw new UserError(
`Your Worker depends on the following Durable Objects, which are not exported in your entrypoint file: ${notExportedDOs.join(
", "
)}.
You should export these objects from your entrypoint, ${relativePath}.`
);
}
const notExportedWorkflows = workflowBindings.filter((x6) => !x6.script_name && !entryPoint.exports.includes(x6.class_name)).map((x6) => x6.class_name);
if (notExportedWorkflows.length) {
const relativePath = path20.relative(process.cwd(), entryFile);
throw new UserError(
`Your Worker depends on the following Workflows, which are not exported in your entrypoint file: ${notExportedWorkflows.join(
", "
)}.
You should export these objects from your entrypoint, ${relativePath}.`
);
}
const bundleType = entryPoint.exports.length > 0 ? "esm" : "commonjs";
const sourceMapPath = Object.keys(result.metafile.outputs).filter(
(_path) => _path.includes(".map")
)[0];
const resolvedEntryPointPath = path20.resolve(
entry.projectRoot,
entryPoint.relativePath
);
const modules = dedupeModulesByName([
...moduleCollector.modules,
...additionalModules
]);
await writeAdditionalModules(modules, path20.dirname(resolvedEntryPointPath));
return {
modules,
dependencies: entryPoint.dependencies,
resolvedEntryPointPath,
bundleType,
stop,
sourceMapPath,
sourceMapMetadata: {
tmpDir: tmpDir.path,
entryDirectory: entry.projectRoot
}
};
}
function shouldCheckFetch(compatibilityDate = "2000-01-01", compatibilityFlags = []) {
if (compatibilityFlags.includes("ignore_custom_ports")) {
return true;
}
if (compatibilityFlags.includes("allow_custom_ports")) {
return false;
}
return compatibilityDate < "2024-09-02";
}
var fs10, path20, esbuild, ESCAPE_REGEX_CHARACTERS, escapeRegex, COMMON_ESBUILD_OPTIONS, BuildFailure;
var init_bundle = __esm({
"src/deployment-bundle/bundle.ts"() {
init_import_meta_url();
fs10 = __toESM(require("fs"));
path20 = __toESM(require("path"));
init_source();
esbuild = __toESM(require("esbuild"));
init_misc_variables();
init_errors();
init_experimental_flags();
init_paths();
init_apply_middleware();
init_build_failures();
init_dedupe_modules();
init_entry_point_from_metafile();
init_cloudflare_internal();
init_config_provider();
init_nodejs_plugins();
init_find_additional_modules();
init_module_collection();
ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
escapeRegex = /* @__PURE__ */ __name((str) => {
return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&");
}, "escapeRegex");
COMMON_ESBUILD_OPTIONS = {
// Our workerd runtime uses the same V8 version as recent Chrome, which is highly ES2022 compliant: https://kangax.github.io/compat-table/es2016plus/
target: "es2022",
loader: { ".js": "jsx", ".mjs": "jsx", ".cjs": "jsx" }
};
__name(getBuildConditions, "getBuildConditions");
__name(getBuildPlatform, "getBuildPlatform");
__name(bundleWorker, "bundleWorker");
BuildFailure = class extends Error {
constructor(message, errors, warnings) {
super(message);
this.errors = errors;
this.warnings = warnings;
}
static {
__name(this, "BuildFailure");
}
};
__name(shouldCheckFetch, "shouldCheckFetch");
}
});
// src/deployment-bundle/no-bundle-worker.ts
async function noBundleWorker(entry, rules, outDir) {
const modules = await findAdditionalModules(entry, rules);
if (outDir) {
await writeAdditionalModules(modules, outDir);
}
const bundleType = getBundleType(entry.format, entry.file);
return {
modules,
dependencies: {},
resolvedEntryPointPath: entry.file,
bundleType
};
}
var init_no_bundle_worker = __esm({
"src/deployment-bundle/no-bundle-worker.ts"() {
init_import_meta_url();
init_bundle_type();
init_find_additional_modules();
__name(noBundleWorker, "noBundleWorker");
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
var require_windows = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports2, module3) {
init_import_meta_url();
module3.exports = isexe;
isexe.sync = sync;
var fs24 = require("fs");
function checkPathExt(path72, 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 i5 = 0; i5 < pathext.length; i5++) {
var p6 = pathext[i5].toLowerCase();
if (p6 && path72.substr(-p6.length).toLowerCase() === p6) {
return true;
}
}
return false;
}
__name(checkPathExt, "checkPathExt");
function checkStat(stat8, path72, options) {
if (!stat8.isSymbolicLink() && !stat8.isFile()) {
return false;
}
return checkPathExt(path72, options);
}
__name(checkStat, "checkStat");
function isexe(path72, options, cb2) {
fs24.stat(path72, function(er, stat8) {
cb2(er, er ? false : checkStat(stat8, path72, options));
});
}
__name(isexe, "isexe");
function sync(path72, options) {
return checkStat(fs24.statSync(path72), path72, options);
}
__name(sync, "sync");
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
var require_mode = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports2, module3) {
init_import_meta_url();
module3.exports = isexe;
isexe.sync = sync;
var fs24 = require("fs");
function isexe(path72, options, cb2) {
fs24.stat(path72, function(er, stat8) {
cb2(er, er ? false : checkStat(stat8, options));
});
}
__name(isexe, "isexe");
function sync(path72, options) {
return checkStat(fs24.statSync(path72), options);
}
__name(sync, "sync");
function checkStat(stat8, options) {
return stat8.isFile() && checkMode(stat8, options);
}
__name(checkStat, "checkStat");
function checkMode(stat8, options) {
var mod = stat8.mode;
var uid = stat8.uid;
var gid = stat8.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 u5 = parseInt("100", 8);
var g6 = parseInt("010", 8);
var o5 = parseInt("001", 8);
var ug = u5 | g6;
var ret = mod & o5 || mod & g6 && gid === myGid || mod & u5 && uid === myUid || mod & ug && myUid === 0;
return ret;
}
__name(checkMode, "checkMode");
}
});
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
var require_isexe = __commonJS({
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports2, module3) {
init_import_meta_url();
var fs24 = require("fs");
var core;
if (process.platform === "win32" || global.TESTING_WINDOWS) {
core = require_windows();
} else {
core = require_mode();
}
module3.exports = isexe;
isexe.sync = sync;
function isexe(path72, options, cb2) {
if (typeof options === "function") {
cb2 = options;
options = {};
}
if (!cb2) {
if (typeof Promise !== "function") {
throw new TypeError("callback not provided");
}
return new Promise(function(resolve25, reject) {
isexe(path72, options || {}, function(er, is) {
if (er) {
reject(er);
} else {
resolve25(is);
}
});
});
}
core(path72, options || {}, function(er, is) {
if (er) {
if (er.code === "EACCES" || options && options.ignoreErrors) {
er = null;
is = false;
}
}
cb2(er, is);
});
}
__name(isexe, "isexe");
function sync(path72, options) {
try {
return core.sync(path72, options || {});
} catch (er) {
if (options && options.ignoreErrors || er.code === "EACCES") {
return false;
} else {
throw er;
}
}
}
__name(sync, "sync");
}
});
// ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
var require_which = __commonJS({
"../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports2, module3) {
init_import_meta_url();
var isWindows4 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
var path72 = require("path");
var COLON = isWindows4 ? ";" : ":";
var isexe = require_isexe();
var getNotFoundError = /* @__PURE__ */ __name((cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }), "getNotFoundError");
var getPathInfo = /* @__PURE__ */ __name((cmd, opt) => {
const colon = opt.colon || COLON;
const pathEnv = cmd.match(/\//) || isWindows4 && cmd.match(/\\/) ? [""] : [
// windows always checks the cwd first
...isWindows4 ? [process.cwd()] : [],
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
"").split(colon)
];
const pathExtExe = isWindows4 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
const pathExt = isWindows4 ? pathExtExe.split(colon) : [""];
if (isWindows4) {
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
pathExt.unshift("");
}
return {
pathEnv,
pathExt,
pathExtExe
};
}, "getPathInfo");
var which = /* @__PURE__ */ __name((cmd, opt, cb2) => {
if (typeof opt === "function") {
cb2 = opt;
opt = {};
}
if (!opt)
opt = {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found = [];
const step = /* @__PURE__ */ __name((i5) => new Promise((resolve25, reject) => {
if (i5 === pathEnv.length)
return opt.all && found.length ? resolve25(found) : reject(getNotFoundError(cmd));
const ppRaw = pathEnv[i5];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path72.join(pathPart, cmd);
const p6 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
resolve25(subStep(p6, i5, 0));
}), "step");
const subStep = /* @__PURE__ */ __name((p6, i5, ii) => new Promise((resolve25, reject) => {
if (ii === pathExt.length)
return resolve25(step(i5 + 1));
const ext = pathExt[ii];
isexe(p6 + ext, { pathExt: pathExtExe }, (er, is) => {
if (!er && is) {
if (opt.all)
found.push(p6 + ext);
else
return resolve25(p6 + ext);
}
return resolve25(subStep(p6, i5, ii + 1));
});
}), "subStep");
return cb2 ? step(0).then((res) => cb2(null, res), cb2) : step(0);
}, "which");
var whichSync = /* @__PURE__ */ __name((cmd, opt) => {
opt = opt || {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found = [];
for (let i5 = 0; i5 < pathEnv.length; i5++) {
const ppRaw = pathEnv[i5];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path72.join(pathPart, cmd);
const p6 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
for (let j6 = 0; j6 < pathExt.length; j6++) {
const cur = p6 + pathExt[j6];
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);
}, "whichSync");
module3.exports = which;
which.sync = whichSync;
}
});
// ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
var require_path_key = __commonJS({
"../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var pathKey2 = /* @__PURE__ */ __name((options = {}) => {
const environment = options.env || process.env;
const platform3 = options.platform || process.platform;
if (platform3 !== "win32") {
return "PATH";
}
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
}, "pathKey");
module3.exports = pathKey2;
module3.exports.default = pathKey2;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var path72 = require("path");
var which = require_which();
var getPathKey = require_path_key();
function resolveCommandAttempt(parsed, withoutPathExt) {
const env6 = parsed.options.env || process.env;
const cwd2 = 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: env6[getPathKey({ env: env6 })],
pathExt: withoutPathExt ? path72.delimiter : void 0
});
} catch (e7) {
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd2);
}
}
if (resolved) {
resolved = path72.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
}
return resolved;
}
__name(resolveCommandAttempt, "resolveCommandAttempt");
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
__name(resolveCommand, "resolveCommand");
module3.exports = resolveCommand;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
arg = arg.replace(metaCharsRegExp, "^$1");
return arg;
}
__name(escapeCommand, "escapeCommand");
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;
}
__name(escapeArgument, "escapeArgument");
module3.exports.command = escapeCommand;
module3.exports.argument = escapeArgument;
}
});
// ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
"../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = /^#!(.*)/;
}
});
// ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
"../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var shebangRegex = require_shebang_regex();
module3.exports = (string = "") => {
const match2 = string.match(shebangRegex);
if (!match2) {
return null;
}
const [path72, argument] = match2[0].replace(/#! ?/, "").split(" ");
const binary = path72.split("/").pop();
if (binary === "env") {
return argument;
}
return argument ? `${binary} ${argument}` : binary;
};
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var fs24 = require("fs");
var shebangCommand = require_shebang_command();
function readShebang(command2) {
const size = 150;
const buffer = Buffer.alloc(size);
let fd;
try {
fd = fs24.openSync(command2, "r");
fs24.readSync(fd, buffer, 0, size, 0);
fs24.closeSync(fd);
} catch (e7) {
}
return shebangCommand(buffer.toString());
}
__name(readShebang, "readShebang");
module3.exports = readShebang;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
var require_parse3 = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var path72 = require("path");
var resolveCommand = require_resolveCommand();
var escape2 = require_escape();
var readShebang = require_readShebang();
var isWin = 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;
}
__name(detectShebang, "detectShebang");
function parseNonShell(parsed) {
if (!isWin) {
return parsed;
}
const commandFile = detectShebang(parsed);
const needsShell = !isExecutableRegExp.test(commandFile);
if (parsed.options.forceShell || needsShell) {
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
parsed.command = path72.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;
}
__name(parseNonShell, "parseNonShell");
function parse7(command2, args, options) {
if (args && !Array.isArray(args)) {
options = args;
args = null;
}
args = args ? args.slice(0) : [];
options = Object.assign({}, options);
const parsed = {
command: command2,
args,
options,
file: void 0,
original: {
command: command2,
args
}
};
return options.shell ? parsed : parseNonShell(parsed);
}
__name(parse7, "parse");
module3.exports = parse7;
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var isWin = 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
});
}
__name(notFoundError, "notFoundError");
function hookChildProcess(cp3, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp3.emit;
cp3.emit = function(name2, arg1) {
if (name2 === "exit") {
const err = verifyENOENT(arg1, parsed);
if (err) {
return originalEmit.call(cp3, "error", err);
}
}
return originalEmit.apply(cp3, arguments);
};
}
__name(hookChildProcess, "hookChildProcess");
function verifyENOENT(status2, parsed) {
if (isWin && status2 === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawn");
}
return null;
}
__name(verifyENOENT, "verifyENOENT");
function verifyENOENTSync(status2, parsed) {
if (isWin && status2 === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawnSync");
}
return null;
}
__name(verifyENOENTSync, "verifyENOENTSync");
module3.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError
};
}
});
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var cp3 = require("child_process");
var parse7 = require_parse3();
var enoent = require_enoent();
function spawn6(command2, args, options) {
const parsed = parse7(command2, args, options);
const spawned = cp3.spawn(parsed.command, parsed.args, parsed.options);
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
__name(spawn6, "spawn");
function spawnSync3(command2, args, options) {
const parsed = parse7(command2, args, options);
const result = cp3.spawnSync(parsed.command, parsed.args, parsed.options);
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
__name(spawnSync3, "spawnSync");
module3.exports = spawn6;
module3.exports.spawn = spawn6;
module3.exports.sync = spawnSync3;
module3.exports._parse = parse7;
module3.exports._enoent = enoent;
}
});
// ../../node_modules/.pnpm/strip-final-newline@3.0.0/node_modules/strip-final-newline/index.js
function stripFinalNewline(input) {
const LF = typeof input === "string" ? "\n" : "\n".charCodeAt();
const CR = typeof input === "string" ? "\r" : "\r".charCodeAt();
if (input[input.length - 1] === LF) {
input = input.slice(0, -1);
}
if (input[input.length - 1] === CR) {
input = input.slice(0, -1);
}
return input;
}
var init_strip_final_newline = __esm({
"../../node_modules/.pnpm/strip-final-newline@3.0.0/node_modules/strip-final-newline/index.js"() {
init_import_meta_url();
__name(stripFinalNewline, "stripFinalNewline");
}
});
// ../../node_modules/.pnpm/path-key@4.0.0/node_modules/path-key/index.js
function pathKey(options = {}) {
const {
env: env6 = process.env,
platform: platform3 = process.platform
} = options;
if (platform3 !== "win32") {
return "PATH";
}
return Object.keys(env6).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
}
var init_path_key = __esm({
"../../node_modules/.pnpm/path-key@4.0.0/node_modules/path-key/index.js"() {
init_import_meta_url();
__name(pathKey, "pathKey");
}
});
// ../../node_modules/.pnpm/npm-run-path@5.1.0/node_modules/npm-run-path/index.js
function npmRunPath(options = {}) {
const {
cwd: cwd2 = import_node_process7.default.cwd(),
path: path_ = import_node_process7.default.env[pathKey()],
execPath = import_node_process7.default.execPath
} = options;
let previous;
const cwdString = cwd2 instanceof URL ? import_node_url7.default.fileURLToPath(cwd2) : cwd2;
let cwdPath = import_node_path19.default.resolve(cwdString);
const result = [];
while (previous !== cwdPath) {
result.push(import_node_path19.default.join(cwdPath, "node_modules/.bin"));
previous = cwdPath;
cwdPath = import_node_path19.default.resolve(cwdPath, "..");
}
result.push(import_node_path19.default.resolve(cwdString, execPath, ".."));
return [...result, path_].join(import_node_path19.default.delimiter);
}
function npmRunPathEnv({ env: env6 = import_node_process7.default.env, ...options } = {}) {
env6 = { ...env6 };
const path72 = pathKey({ env: env6 });
options.path = env6[path72];
env6[path72] = npmRunPath(options);
return env6;
}
var import_node_process7, import_node_path19, import_node_url7;
var init_npm_run_path = __esm({
"../../node_modules/.pnpm/npm-run-path@5.1.0/node_modules/npm-run-path/index.js"() {
init_import_meta_url();
import_node_process7 = __toESM(require("process"), 1);
import_node_path19 = __toESM(require("path"), 1);
import_node_url7 = __toESM(require("url"), 1);
init_path_key();
__name(npmRunPath, "npmRunPath");
__name(npmRunPathEnv, "npmRunPathEnv");
}
});
// ../../node_modules/.pnpm/mimic-fn@4.0.0/node_modules/mimic-fn/index.js
function mimicFunction(to, from, { ignoreNonConfigurable = false } = {}) {
const { name: name2 } = to;
for (const property of Reflect.ownKeys(from)) {
copyProperty(to, from, property, ignoreNonConfigurable);
}
changePrototype(to, from);
changeToString(to, from, name2);
return to;
}
var copyProperty, canCopyProperty, changePrototype, wrappedToString, toStringDescriptor, toStringName, changeToString;
var init_mimic_fn = __esm({
"../../node_modules/.pnpm/mimic-fn@4.0.0/node_modules/mimic-fn/index.js"() {
init_import_meta_url();
copyProperty = /* @__PURE__ */ __name((to, from, property, ignoreNonConfigurable) => {
if (property === "length" || property === "prototype") {
return;
}
if (property === "arguments" || property === "caller") {
return;
}
const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
return;
}
Object.defineProperty(to, property, fromDescriptor);
}, "copyProperty");
canCopyProperty = /* @__PURE__ */ __name(function(toDescriptor, fromDescriptor) {
return toDescriptor === void 0 || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
}, "canCopyProperty");
changePrototype = /* @__PURE__ */ __name((to, from) => {
const fromPrototype = Object.getPrototypeOf(from);
if (fromPrototype === Object.getPrototypeOf(to)) {
return;
}
Object.setPrototypeOf(to, fromPrototype);
}, "changePrototype");
wrappedToString = /* @__PURE__ */ __name((withName, fromBody) => `/* Wrapped ${withName}*/
${fromBody}`, "wrappedToString");
toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, "toString");
toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, "name");
changeToString = /* @__PURE__ */ __name((to, from, name2) => {
const withName = name2 === "" ? "" : `with ${name2.trim()}() `;
const newToString = wrappedToString.bind(null, withName, from.toString());
Object.defineProperty(newToString, "name", toStringName);
Object.defineProperty(to, "toString", { ...toStringDescriptor, value: newToString });
}, "changeToString");
__name(mimicFunction, "mimicFunction");
}
});
// ../../node_modules/.pnpm/onetime@6.0.0/node_modules/onetime/index.js
var calledFunctions, onetime2, onetime_default;
var init_onetime = __esm({
"../../node_modules/.pnpm/onetime@6.0.0/node_modules/onetime/index.js"() {
init_import_meta_url();
init_mimic_fn();
calledFunctions = /* @__PURE__ */ new WeakMap();
onetime2 = /* @__PURE__ */ __name((function_, options = {}) => {
if (typeof function_ !== "function") {
throw new TypeError("Expected a function");
}
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || "<anonymous>";
const onetime3 = /* @__PURE__ */ __name(function(...arguments_) {
calledFunctions.set(onetime3, ++callCount);
if (callCount === 1) {
returnValue = function_.apply(this, arguments_);
function_ = null;
} else if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
}
return returnValue;
}, "onetime");
mimicFunction(onetime3, function_);
calledFunctions.set(onetime3, callCount);
return onetime3;
}, "onetime");
onetime2.callCount = (function_) => {
if (!calledFunctions.has(function_)) {
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions.get(function_);
};
onetime_default = onetime2;
}
});
// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/realtime.js
var getRealtimeSignals, getRealtimeSignal, SIGRTMIN, SIGRTMAX;
var init_realtime = __esm({
"../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/realtime.js"() {
init_import_meta_url();
getRealtimeSignals = /* @__PURE__ */ __name(function() {
const length = SIGRTMAX - SIGRTMIN + 1;
return Array.from({ length }, getRealtimeSignal);
}, "getRealtimeSignals");
getRealtimeSignal = /* @__PURE__ */ __name(function(value, index) {
return {
name: `SIGRT${index + 1}`,
number: SIGRTMIN + index,
action: "terminate",
description: "Application-specific signal (realtime)",
standard: "posix"
};
}, "getRealtimeSignal");
SIGRTMIN = 34;
SIGRTMAX = 64;
}
});
// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/core.js
var SIGNALS;
var init_core = __esm({
"../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/core.js"() {
init_import_meta_url();
SIGNALS = [
{
name: "SIGHUP",
number: 1,
action: "terminate",
description: "Terminal closed",
standard: "posix"
},
{
name: "SIGINT",
number: 2,
action: "terminate",
description: "User interruption with CTRL-C",
standard: "ansi"
},
{
name: "SIGQUIT",
number: 3,
action: "core",
description: "User interruption with CTRL-\\",
standard: "posix"
},
{
name: "SIGILL",
number: 4,
action: "core",
description: "Invalid machine instruction",
standard: "ansi"
},
{
name: "SIGTRAP",
number: 5,
action: "core",
description: "Debugger breakpoint",
standard: "posix"
},
{
name: "SIGABRT",
number: 6,
action: "core",
description: "Aborted",
standard: "ansi"
},
{
name: "SIGIOT",
number: 6,
action: "core",
description: "Aborted",
standard: "bsd"
},
{
name: "SIGBUS",
number: 7,
action: "core",
description: "Bus error due to misaligned, non-existing address or paging error",
standard: "bsd"
},
{
name: "SIGEMT",
number: 7,
action: "terminate",
description: "Command should be emulated but is not implemented",
standard: "other"
},
{
name: "SIGFPE",
number: 8,
action: "core",
description: "Floating point arithmetic error",
standard: "ansi"
},
{
name: "SIGKILL",
number: 9,
action: "terminate",
description: "Forced termination",
standard: "posix",
forced: true
},
{
name: "SIGUSR1",
number: 10,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGSEGV",
number: 11,
action: "core",
description: "Segmentation fault",
standard: "ansi"
},
{
name: "SIGUSR2",
number: 12,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGPIPE",
number: 13,
action: "terminate",
description: "Broken pipe or socket",
standard: "posix"
},
{
name: "SIGALRM",
number: 14,
action: "terminate",
description: "Timeout or timer",
standard: "posix"
},
{
name: "SIGTERM",
number: 15,
action: "terminate",
description: "Termination",
standard: "ansi"
},
{
name: "SIGSTKFLT",
number: 16,
action: "terminate",
description: "Stack is empty or overflowed",
standard: "other"
},
{
name: "SIGCHLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "posix"
},
{
name: "SIGCLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "other"
},
{
name: "SIGCONT",
number: 18,
action: "unpause",
description: "Unpaused",
standard: "posix",
forced: true
},
{
name: "SIGSTOP",
number: 19,
action: "pause",
description: "Paused",
standard: "posix",
forced: true
},
{
name: "SIGTSTP",
number: 20,
action: "pause",
description: 'Paused using CTRL-Z or "suspend"',
standard: "posix"
},
{
name: "SIGTTIN",
number: 21,
action: "pause",
description: "Background process cannot read terminal input",
standard: "posix"
},
{
name: "SIGBREAK",
number: 21,
action: "terminate",
description: "User interruption with CTRL-BREAK",
standard: "other"
},
{
name: "SIGTTOU",
number: 22,
action: "pause",
description: "Background process cannot write to terminal output",
standard: "posix"
},
{
name: "SIGURG",
number: 23,
action: "ignore",
description: "Socket received out-of-band data",
standard: "bsd"
},
{
name: "SIGXCPU",
number: 24,
action: "core",
description: "Process timed out",
standard: "bsd"
},
{
name: "SIGXFSZ",
number: 25,
action: "core",
description: "File too big",
standard: "bsd"
},
{
name: "SIGVTALRM",
number: 26,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGPROF",
number: 27,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGWINCH",
number: 28,
action: "ignore",
description: "Terminal window size changed",
standard: "bsd"
},
{
name: "SIGIO",
number: 29,
action: "terminate",
description: "I/O is available",
standard: "other"
},
{
name: "SIGPOLL",
number: 29,
action: "terminate",
description: "Watched event",
standard: "other"
},
{
name: "SIGINFO",
number: 29,
action: "ignore",
description: "Request for process information",
standard: "other"
},
{
name: "SIGPWR",
number: 30,
action: "terminate",
description: "Device running out of power",
standard: "systemv"
},
{
name: "SIGSYS",
number: 31,
action: "core",
description: "Invalid system call",
standard: "other"
},
{
name: "SIGUNUSED",
number: 31,
action: "terminate",
description: "Invalid system call",
standard: "other"
}
];
}
});
// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/signals.js
var import_os2, getSignals, normalizeSignal;
var init_signals = __esm({
"../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/signals.js"() {
init_import_meta_url();
import_os2 = require("os");
init_core();
init_realtime();
getSignals = /* @__PURE__ */ __name(function() {
const realtimeSignals = getRealtimeSignals();
const signals = [...SIGNALS, ...realtimeSignals].map(normalizeSignal);
return signals;
}, "getSignals");
normalizeSignal = /* @__PURE__ */ __name(function({
name: name2,
number: defaultNumber,
description,
action,
forced = false,
standard
}) {
const {
signals: { [name2]: constantSignal }
} = import_os2.constants;
const supported = constantSignal !== void 0;
const number = supported ? constantSignal : defaultNumber;
return { name: name2, number, description, supported, action, forced, standard };
}, "normalizeSignal");
}
});
// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/main.js
var import_os3, getSignalsByName, getSignalByName, signalsByName, getSignalsByNumber, getSignalByNumber, findSignalByNumber, signalsByNumber;
var init_main2 = __esm({
"../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/main.js"() {
init_import_meta_url();
import_os3 = require("os");
init_realtime();
init_signals();
getSignalsByName = /* @__PURE__ */ __name(function() {
const signals = getSignals();
return signals.reduce(getSignalByName, {});
}, "getSignalsByName");
getSignalByName = /* @__PURE__ */ __name(function(signalByNameMemo, { name: name2, number, description, supported, action, forced, standard }) {
return {
...signalByNameMemo,
[name2]: { name: name2, number, description, supported, action, forced, standard }
};
}, "getSignalByName");
signalsByName = getSignalsByName();
getSignalsByNumber = /* @__PURE__ */ __name(function() {
const signals = getSignals();
const length = SIGRTMAX + 1;
const signalsA = Array.from({ length }, (value, number) => getSignalByNumber(number, signals));
return Object.assign({}, ...signalsA);
}, "getSignalsByNumber");
getSignalByNumber = /* @__PURE__ */ __name(function(number, signals) {
const signal = findSignalByNumber(number, signals);
if (signal === void 0) {
return {};
}
const { name: name2, description, supported, action, forced, standard } = signal;
return {
[number]: {
name: name2,
number,
description,
supported,
action,
forced,
standard
}
};
}, "getSignalByNumber");
findSignalByNumber = /* @__PURE__ */ __name(function(number, signals) {
const signal = signals.find(({ name: name2 }) => import_os3.constants.signals[name2] === number);
if (signal !== void 0) {
return signal;
}
return signals.find((signalA) => signalA.number === number);
}, "findSignalByNumber");
signalsByNumber = getSignalsByNumber();
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/error.js
var getErrorPrefix, makeError;
var init_error2 = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/error.js"() {
init_import_meta_url();
init_main2();
getErrorPrefix = /* @__PURE__ */ __name(({ timedOut, timeout: timeout2, errorCode, signal, signalDescription, exitCode, isCanceled }) => {
if (timedOut) {
return `timed out after ${timeout2} milliseconds`;
}
if (isCanceled) {
return "was canceled";
}
if (errorCode !== void 0) {
return `failed with ${errorCode}`;
}
if (signal !== void 0) {
return `was killed with ${signal} (${signalDescription})`;
}
if (exitCode !== void 0) {
return `failed with exit code ${exitCode}`;
}
return "failed";
}, "getErrorPrefix");
makeError = /* @__PURE__ */ __name(({
stdout: stdout2,
stderr: stderr2,
all: all2,
error: error2,
signal,
exitCode,
command: command2,
escapedCommand,
timedOut,
isCanceled,
killed,
parsed: { options: { timeout: timeout2 } }
}) => {
exitCode = exitCode === null ? void 0 : exitCode;
signal = signal === null ? void 0 : signal;
const signalDescription = signal === void 0 ? void 0 : signalsByName[signal].description;
const errorCode = error2 && error2.code;
const prefix = getErrorPrefix({ timedOut, timeout: timeout2, errorCode, signal, signalDescription, exitCode, isCanceled });
const execaMessage = `Command ${prefix}: ${command2}`;
const isError2 = Object.prototype.toString.call(error2) === "[object Error]";
const shortMessage = isError2 ? `${execaMessage}
${error2.message}` : execaMessage;
const message = [shortMessage, stderr2, stdout2].filter(Boolean).join("\n");
if (isError2) {
error2.originalMessage = error2.message;
error2.message = message;
} else {
error2 = new Error(message);
}
error2.shortMessage = shortMessage;
error2.command = command2;
error2.escapedCommand = escapedCommand;
error2.exitCode = exitCode;
error2.signal = signal;
error2.signalDescription = signalDescription;
error2.stdout = stdout2;
error2.stderr = stderr2;
if (all2 !== void 0) {
error2.all = all2;
}
if ("bufferedData" in error2) {
delete error2.bufferedData;
}
error2.failed = true;
error2.timedOut = Boolean(timedOut);
error2.isCanceled = isCanceled;
error2.killed = killed && !timedOut;
return error2;
}, "makeError");
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stdio.js
var aliases, hasAlias, normalizeStdio;
var init_stdio2 = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stdio.js"() {
init_import_meta_url();
aliases = ["stdin", "stdout", "stderr"];
hasAlias = /* @__PURE__ */ __name((options) => aliases.some((alias) => options[alias] !== void 0), "hasAlias");
normalizeStdio = /* @__PURE__ */ __name((options) => {
if (!options) {
return;
}
const { stdio } = options;
if (stdio === void 0) {
return aliases.map((alias) => options[alias]);
}
if (hasAlias(options)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map((alias) => `\`${alias}\``).join(", ")}`);
}
if (typeof stdio === "string") {
return stdio;
}
if (!Array.isArray(stdio)) {
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
}
const length = Math.max(stdio.length, aliases.length);
return Array.from({ length }, (value, index) => stdio[index]);
}, "normalizeStdio");
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/kill.js
var import_node_os5, import_signal_exit4, DEFAULT_FORCE_KILL_TIMEOUT, spawnedKill, setKillTimeout, shouldForceKill, isSigterm, getForceKillAfterTimeout, spawnedCancel, timeoutKill, setupTimeout, validateTimeout, setExitHandler;
var init_kill = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/kill.js"() {
init_import_meta_url();
import_node_os5 = __toESM(require("os"), 1);
import_signal_exit4 = __toESM(require_signal_exit(), 1);
DEFAULT_FORCE_KILL_TIMEOUT = 1e3 * 5;
spawnedKill = /* @__PURE__ */ __name((kill, signal = "SIGTERM", options = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
}, "spawnedKill");
setKillTimeout = /* @__PURE__ */ __name((kill, signal, options, killResult) => {
if (!shouldForceKill(signal, options, killResult)) {
return;
}
const timeout2 = getForceKillAfterTimeout(options);
const t7 = setTimeout(() => {
kill("SIGKILL");
}, timeout2);
if (t7.unref) {
t7.unref();
}
}, "setKillTimeout");
shouldForceKill = /* @__PURE__ */ __name((signal, { forceKillAfterTimeout }, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult, "shouldForceKill");
isSigterm = /* @__PURE__ */ __name((signal) => signal === import_node_os5.default.constants.signals.SIGTERM || typeof signal === "string" && signal.toUpperCase() === "SIGTERM", "isSigterm");
getForceKillAfterTimeout = /* @__PURE__ */ __name(({ forceKillAfterTimeout = true }) => {
if (forceKillAfterTimeout === true) {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
}
return forceKillAfterTimeout;
}, "getForceKillAfterTimeout");
spawnedCancel = /* @__PURE__ */ __name((spawned, context2) => {
const killResult = spawned.kill();
if (killResult) {
context2.isCanceled = true;
}
}, "spawnedCancel");
timeoutKill = /* @__PURE__ */ __name((spawned, signal, reject) => {
spawned.kill(signal);
reject(Object.assign(new Error("Timed out"), { timedOut: true, signal }));
}, "timeoutKill");
setupTimeout = /* @__PURE__ */ __name((spawned, { timeout: timeout2, killSignal = "SIGTERM" }, spawnedPromise) => {
if (timeout2 === 0 || timeout2 === void 0) {
return spawnedPromise;
}
let timeoutId;
const timeoutPromise = new Promise((resolve25, reject) => {
timeoutId = setTimeout(() => {
timeoutKill(spawned, killSignal, reject);
}, timeout2);
});
const safeSpawnedPromise = spawnedPromise.finally(() => {
clearTimeout(timeoutId);
});
return Promise.race([timeoutPromise, safeSpawnedPromise]);
}, "setupTimeout");
validateTimeout = /* @__PURE__ */ __name(({ timeout: timeout2 }) => {
if (timeout2 !== void 0 && (!Number.isFinite(timeout2) || timeout2 < 0)) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout2}\` (${typeof timeout2})`);
}
}, "validateTimeout");
setExitHandler = /* @__PURE__ */ __name(async (spawned, { cleanup, detached }, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
const removeExitHandler = (0, import_signal_exit4.default)(() => {
spawned.kill();
});
return timedPromise.finally(() => {
removeExitHandler();
});
}, "setExitHandler");
}
});
// ../../node_modules/.pnpm/is-stream@3.0.0/node_modules/is-stream/index.js
function isStream(stream2) {
return stream2 !== null && typeof stream2 === "object" && typeof stream2.pipe === "function";
}
var init_is_stream = __esm({
"../../node_modules/.pnpm/is-stream@3.0.0/node_modules/is-stream/index.js"() {
init_import_meta_url();
__name(isStream, "isStream");
}
});
// ../../node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
"../../node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/buffer-stream.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { PassThrough: PassThroughStream } = require("stream");
module3.exports = (options) => {
options = { ...options };
const { array } = options;
let { encoding } = options;
const isBuffer = encoding === "buffer";
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || "utf8";
}
if (isBuffer) {
encoding = null;
}
const stream2 = new PassThroughStream({ objectMode });
if (encoding) {
stream2.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream2.on("data", (chunk) => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream2.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join("");
};
stream2.getBufferedLength = () => length;
return stream2;
};
}
});
// ../../node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/index.js
var require_get_stream = __commonJS({
"../../node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { constants: BufferConstants } = require("buffer");
var stream2 = require("stream");
var { promisify: promisify3 } = require("util");
var bufferStream = require_buffer_stream();
var streamPipelinePromisified = promisify3(stream2.pipeline);
var MaxBufferError = class extends Error {
static {
__name(this, "MaxBufferError");
}
constructor() {
super("maxBuffer exceeded");
this.name = "MaxBufferError";
}
};
async function getStream2(inputStream, options) {
if (!inputStream) {
throw new Error("Expected a stream");
}
options = {
maxBuffer: Infinity,
...options
};
const { maxBuffer } = options;
const stream3 = bufferStream(options);
await new Promise((resolve25, reject) => {
const rejectPromise = /* @__PURE__ */ __name((error2) => {
if (error2 && stream3.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
error2.bufferedData = stream3.getBufferedValue();
}
reject(error2);
}, "rejectPromise");
(async () => {
try {
await streamPipelinePromisified(inputStream, stream3);
resolve25();
} catch (error2) {
rejectPromise(error2);
}
})();
stream3.on("data", () => {
if (stream3.getBufferedLength() > maxBuffer) {
rejectPromise(new MaxBufferError());
}
});
});
return stream3.getBufferedValue();
}
__name(getStream2, "getStream");
module3.exports = getStream2;
module3.exports.buffer = (stream3, options) => getStream2(stream3, { ...options, encoding: "buffer" });
module3.exports.array = (stream3, options) => getStream2(stream3, { ...options, array: true });
module3.exports.MaxBufferError = MaxBufferError;
}
});
// ../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js
var require_merge_stream = __commonJS({
"../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { PassThrough: PassThrough3 } = require("stream");
module3.exports = function() {
var sources = [];
var output = new PassThrough3({ objectMode: true });
output.setMaxListeners(0);
output.add = add;
output.isEmpty = isEmpty;
output.on("unpipe", remove);
Array.prototype.slice.call(arguments).forEach(add);
return output;
function add(source) {
if (Array.isArray(source)) {
source.forEach(add);
return this;
}
sources.push(source);
source.once("end", remove.bind(null, source));
source.once("error", output.emit.bind(output, "error"));
source.pipe(output, { end: false });
return this;
}
__name(add, "add");
function isEmpty() {
return sources.length == 0;
}
__name(isEmpty, "isEmpty");
function remove(source) {
sources = sources.filter(function(it) {
return it !== source;
});
if (!sources.length && output.readable) {
output.end();
}
}
__name(remove, "remove");
};
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stream.js
var import_get_stream, import_merge_stream, handleInput, makeAllStream, getBufferedData, getStreamPromise, getSpawnedResult, validateInputSync;
var init_stream = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stream.js"() {
init_import_meta_url();
init_is_stream();
import_get_stream = __toESM(require_get_stream(), 1);
import_merge_stream = __toESM(require_merge_stream(), 1);
handleInput = /* @__PURE__ */ __name((spawned, input) => {
if (input === void 0 || spawned.stdin === void 0) {
return;
}
if (isStream(input)) {
input.pipe(spawned.stdin);
} else {
spawned.stdin.end(input);
}
}, "handleInput");
makeAllStream = /* @__PURE__ */ __name((spawned, { all: all2 }) => {
if (!all2 || !spawned.stdout && !spawned.stderr) {
return;
}
const mixed = (0, import_merge_stream.default)();
if (spawned.stdout) {
mixed.add(spawned.stdout);
}
if (spawned.stderr) {
mixed.add(spawned.stderr);
}
return mixed;
}, "makeAllStream");
getBufferedData = /* @__PURE__ */ __name(async (stream2, streamPromise) => {
if (!stream2) {
return;
}
stream2.destroy();
try {
return await streamPromise;
} catch (error2) {
return error2.bufferedData;
}
}, "getBufferedData");
getStreamPromise = /* @__PURE__ */ __name((stream2, { encoding, buffer, maxBuffer }) => {
if (!stream2 || !buffer) {
return;
}
if (encoding) {
return (0, import_get_stream.default)(stream2, { encoding, maxBuffer });
}
return import_get_stream.default.buffer(stream2, { maxBuffer });
}, "getStreamPromise");
getSpawnedResult = /* @__PURE__ */ __name(async ({ stdout: stdout2, stderr: stderr2, all: all2 }, { encoding, buffer, maxBuffer }, processDone) => {
const stdoutPromise = getStreamPromise(stdout2, { encoding, buffer, maxBuffer });
const stderrPromise = getStreamPromise(stderr2, { encoding, buffer, maxBuffer });
const allPromise = getStreamPromise(all2, { encoding, buffer, maxBuffer: maxBuffer * 2 });
try {
return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
} catch (error2) {
return Promise.all([
{ error: error2, signal: error2.signal, timedOut: error2.timedOut },
getBufferedData(stdout2, stdoutPromise),
getBufferedData(stderr2, stderrPromise),
getBufferedData(all2, allPromise)
]);
}
}, "getSpawnedResult");
validateInputSync = /* @__PURE__ */ __name(({ input }) => {
if (isStream(input)) {
throw new TypeError("The `input` option cannot be a stream in sync mode");
}
}, "validateInputSync");
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/promise.js
var nativePromisePrototype, descriptors, mergePromise, getSpawnedPromise;
var init_promise = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/promise.js"() {
init_import_meta_url();
nativePromisePrototype = (async () => {
})().constructor.prototype;
descriptors = ["then", "catch", "finally"].map((property) => [
property,
Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
]);
mergePromise = /* @__PURE__ */ __name((spawned, promise) => {
for (const [property, descriptor2] of descriptors) {
const value = typeof promise === "function" ? (...args) => Reflect.apply(descriptor2.value, promise(), args) : descriptor2.value.bind(promise);
Reflect.defineProperty(spawned, property, { ...descriptor2, value });
}
return spawned;
}, "mergePromise");
getSpawnedPromise = /* @__PURE__ */ __name((spawned) => new Promise((resolve25, reject) => {
spawned.on("exit", (exitCode, signal) => {
resolve25({ exitCode, signal });
});
spawned.on("error", (error2) => {
reject(error2);
});
if (spawned.stdin) {
spawned.stdin.on("error", (error2) => {
reject(error2);
});
}
}), "getSpawnedPromise");
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/command.js
var normalizeArgs, NO_ESCAPE_REGEXP, DOUBLE_QUOTES_REGEXP, escapeArg, joinCommand, getEscapedCommand, SPACES_REGEXP, parseCommand;
var init_command = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/command.js"() {
init_import_meta_url();
normalizeArgs = /* @__PURE__ */ __name((file, args = []) => {
if (!Array.isArray(args)) {
return [file];
}
return [file, ...args];
}, "normalizeArgs");
NO_ESCAPE_REGEXP = /^[\w.-]+$/;
DOUBLE_QUOTES_REGEXP = /"/g;
escapeArg = /* @__PURE__ */ __name((arg) => {
if (typeof arg !== "string" || NO_ESCAPE_REGEXP.test(arg)) {
return arg;
}
return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
}, "escapeArg");
joinCommand = /* @__PURE__ */ __name((file, args) => normalizeArgs(file, args).join(" "), "joinCommand");
getEscapedCommand = /* @__PURE__ */ __name((file, args) => normalizeArgs(file, args).map((arg) => escapeArg(arg)).join(" "), "getEscapedCommand");
SPACES_REGEXP = / +/g;
parseCommand = /* @__PURE__ */ __name((command2) => {
const tokens = [];
for (const token of command2.trim().split(SPACES_REGEXP)) {
const previousToken = tokens[tokens.length - 1];
if (previousToken && previousToken.endsWith("\\")) {
tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
} else {
tokens.push(token);
}
}
return tokens;
}, "parseCommand");
}
});
// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/index.js
function execa(file, args, options) {
const parsed = handleArguments(file, args, options);
const command2 = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
validateTimeout(parsed.options);
let spawned;
try {
spawned = import_node_child_process2.default.spawn(parsed.file, parsed.args, parsed.options);
} catch (error2) {
const dummySpawned = new import_node_child_process2.default.ChildProcess();
const errorPromise = Promise.reject(makeError({
error: error2,
stdout: "",
stderr: "",
all: "",
command: command2,
escapedCommand,
parsed,
timedOut: false,
isCanceled: false,
killed: false
}));
return mergePromise(dummySpawned, errorPromise);
}
const spawnedPromise = getSpawnedPromise(spawned);
const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
const processDone = setExitHandler(spawned, parsed.options, timedPromise);
const context2 = { isCanceled: false };
spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
spawned.cancel = spawnedCancel.bind(null, spawned, context2);
const handlePromise = /* @__PURE__ */ __name(async () => {
const [{ error: error2, exitCode, signal, timedOut }, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
const stdout2 = handleOutput(parsed.options, stdoutResult);
const stderr2 = handleOutput(parsed.options, stderrResult);
const all2 = handleOutput(parsed.options, allResult);
if (error2 || exitCode !== 0 || signal !== null) {
const returnedError = makeError({
error: error2,
exitCode,
signal,
stdout: stdout2,
stderr: stderr2,
all: all2,
command: command2,
escapedCommand,
parsed,
timedOut,
isCanceled: context2.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),
killed: spawned.killed
});
if (!parsed.options.reject) {
return returnedError;
}
throw returnedError;
}
return {
command: command2,
escapedCommand,
exitCode: 0,
stdout: stdout2,
stderr: stderr2,
all: all2,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
}, "handlePromise");
const handlePromiseOnce = onetime_default(handlePromise);
handleInput(spawned, parsed.options.input);
spawned.all = makeAllStream(spawned, parsed.options);
return mergePromise(spawned, handlePromiseOnce);
}
function execaSync(file, args, options) {
const parsed = handleArguments(file, args, options);
const command2 = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
validateInputSync(parsed.options);
let result;
try {
result = import_node_child_process2.default.spawnSync(parsed.file, parsed.args, parsed.options);
} catch (error2) {
throw makeError({
error: error2,
stdout: "",
stderr: "",
all: "",
command: command2,
escapedCommand,
parsed,
timedOut: false,
isCanceled: false,
killed: false
});
}
const stdout2 = handleOutput(parsed.options, result.stdout, result.error);
const stderr2 = handleOutput(parsed.options, result.stderr, result.error);
if (result.error || result.status !== 0 || result.signal !== null) {
const error2 = makeError({
stdout: stdout2,
stderr: stderr2,
error: result.error,
signal: result.signal,
exitCode: result.status,
command: command2,
escapedCommand,
parsed,
timedOut: result.error && result.error.code === "ETIMEDOUT",
isCanceled: false,
killed: result.signal !== null
});
if (!parsed.options.reject) {
return error2;
}
throw error2;
}
return {
command: command2,
escapedCommand,
exitCode: 0,
stdout: stdout2,
stderr: stderr2,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
}
function execaCommand(command2, options) {
const [file, ...args] = parseCommand(command2);
return execa(file, args, options);
}
function execaCommandSync(command2, options) {
const [file, ...args] = parseCommand(command2);
return execaSync(file, args, options);
}
var import_node_buffer, import_node_path20, import_node_child_process2, import_node_process8, import_cross_spawn, DEFAULT_MAX_BUFFER, getEnv, handleArguments, handleOutput;
var init_execa = __esm({
"../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/index.js"() {
init_import_meta_url();
import_node_buffer = require("buffer");
import_node_path20 = __toESM(require("path"), 1);
import_node_child_process2 = __toESM(require("child_process"), 1);
import_node_process8 = __toESM(require("process"), 1);
import_cross_spawn = __toESM(require_cross_spawn(), 1);
init_strip_final_newline();
init_npm_run_path();
init_onetime();
init_error2();
init_stdio2();
init_kill();
init_stream();
init_promise();
init_command();
DEFAULT_MAX_BUFFER = 1e3 * 1e3 * 100;
getEnv = /* @__PURE__ */ __name(({ env: envOption, extendEnv, preferLocal, localDir, execPath }) => {
const env6 = extendEnv ? { ...import_node_process8.default.env, ...envOption } : envOption;
if (preferLocal) {
return npmRunPathEnv({ env: env6, cwd: localDir, execPath });
}
return env6;
}, "getEnv");
handleArguments = /* @__PURE__ */ __name((file, args, options = {}) => {
const parsed = import_cross_spawn.default._parse(file, args, options);
file = parsed.command;
args = parsed.args;
options = parsed.options;
options = {
maxBuffer: DEFAULT_MAX_BUFFER,
buffer: true,
stripFinalNewline: true,
extendEnv: true,
preferLocal: false,
localDir: options.cwd || import_node_process8.default.cwd(),
execPath: import_node_process8.default.execPath,
encoding: "utf8",
reject: true,
cleanup: true,
all: false,
windowsHide: true,
...options
};
options.env = getEnv(options);
options.stdio = normalizeStdio(options);
if (import_node_process8.default.platform === "win32" && import_node_path20.default.basename(file, ".exe") === "cmd") {
args.unshift("/q");
}
return { file, args, options, parsed };
}, "handleArguments");
handleOutput = /* @__PURE__ */ __name((options, value, error2) => {
if (typeof value !== "string" && !import_node_buffer.Buffer.isBuffer(value)) {
return error2 === void 0 ? void 0 : "";
}
if (options.stripFinalNewline) {
return stripFinalNewline(value);
}
return value;
}, "handleOutput");
__name(execa, "execa");
__name(execaSync, "execaSync");
__name(execaCommand, "execaCommand");
__name(execaCommandSync, "execaCommandSync");
}
});
// src/deployment-bundle/run-custom-build.ts
async function runCustomBuild(expectedEntryAbsolute, expectedEntryRelative, build5, configPath) {
if (build5.command) {
logger.log(source_default.blue("[custom build]"), "Running:", build5.command);
try {
const res = execaCommand(build5.command, {
shell: true,
...build5.cwd && { cwd: build5.cwd }
});
res.stdout?.pipe(
new import_node_stream.Writable({
write(chunk, _4, callback) {
const lines = chunk.toString().split("\n");
for (const line of lines) {
logger.log(source_default.blue("[custom build]"), line);
}
callback();
}
})
);
res.stderr?.pipe(
new import_node_stream.Writable({
write(chunk, _4, callback) {
const lines = chunk.toString().split("\n");
for (const line of lines) {
logger.log(source_default.red("[custom build]"), line);
}
callback();
}
})
);
await res;
} catch (e7) {
logger.error(e7);
throw new UserError(
`Running custom build \`${build5.command}\` failed. There are likely more logs from your build command above.`,
{
cause: e7
}
);
}
assertEntryPointExists(
expectedEntryAbsolute,
expectedEntryRelative,
`The expected output file at "${expectedEntryRelative}" was not found after running custom build: ${build5.command}.
The \`main\` property in your ${configFileName(configPath)} file should point to the file generated by the custom build.`
);
} else {
assertEntryPointExists(
expectedEntryAbsolute,
expectedEntryRelative,
`The entry-point file at "${expectedEntryRelative}" was not found.`
);
}
}
function assertEntryPointExists(expectedEntryAbsolute, expectedEntryRelative, errorMessage) {
if (!fileExists(expectedEntryAbsolute)) {
throw new UserError(
getMissingEntryPointMessage(
errorMessage,
expectedEntryAbsolute,
expectedEntryRelative
)
);
}
}
function getMissingEntryPointMessage(message, absoluteEntryPointPath, relativeEntryPointPath) {
if ((0, import_node_fs11.existsSync)(absoluteEntryPointPath) && (0, import_node_fs11.statSync)(absoluteEntryPointPath).isDirectory()) {
message += `
The provided entry-point path, "${relativeEntryPointPath}", points to a directory, rather than a file.
`;
const possiblePaths = [];
for (const basenamePath of [
"worker",
"dist/worker",
"index",
"dist/index"
]) {
for (const extension of [".ts", ".tsx", ".js", ".jsx"]) {
const filePath = basenamePath + extension;
if (fileExists(import_node_path21.default.resolve(absoluteEntryPointPath, filePath))) {
possiblePaths.push(import_node_path21.default.join(relativeEntryPointPath, filePath));
}
}
}
if (possiblePaths.length > 0) {
message += `
Did you mean to set the main field to${possiblePaths.length > 1 ? " one of" : ""}:
\`\`\`
` + possiblePaths.map((filePath) => `main = "./${filePath}"
`).join("") + "```";
} else {
message += `
If you want to deploy a directory of static assets, you can do so by using the \`--assets\` flag. For example:
wrangler deploy --assets=./${relativeEntryPointPath}
`;
}
}
return message;
}
function fileExists(filePath) {
const SOURCE_FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
if (import_node_path21.default.extname(filePath) !== "") {
return (0, import_node_fs11.existsSync)(filePath);
}
const base = import_node_path21.default.join(import_node_path21.default.dirname(filePath), import_node_path21.default.basename(filePath));
for (const ext of SOURCE_FILE_EXTENSIONS) {
if ((0, import_node_fs11.existsSync)(base + ext)) {
return true;
}
}
return false;
}
var import_node_fs11, import_node_path21, import_node_stream;
var init_run_custom_build = __esm({
"src/deployment-bundle/run-custom-build.ts"() {
init_import_meta_url();
import_node_fs11 = require("fs");
import_node_path21 = __toESM(require("path"));
import_node_stream = require("stream");
init_source();
init_execa();
init_config2();
init_errors();
init_logger();
__name(runCustomBuild, "runCustomBuild");
__name(assertEntryPointExists, "assertEntryPointExists");
__name(getMissingEntryPointMessage, "getMissingEntryPointMessage");
__name(fileExists, "fileExists");
}
});
// src/deployment-bundle/esbuild-plugins/log-build-output.ts
function logBuildOutput(nodejsCompatMode, onStart, updateBundle) {
let bundled = false;
return {
name: "log-build-output",
setup(build5) {
build5.onStart(() => {
onStart?.();
});
build5.onEnd(async ({ errors, warnings }) => {
if (!bundled) {
bundled = true;
if (warnings.length > 0) {
logBuildWarnings(warnings);
}
} else {
if (errors.length > 0) {
logBuildFailure(errors, warnings);
return;
}
if (warnings.length > 0) {
logBuildWarnings(warnings);
}
await updateBundle?.();
}
});
}
};
}
var init_log_build_output = __esm({
"src/deployment-bundle/esbuild-plugins/log-build-output.ts"() {
init_import_meta_url();
init_logger();
__name(logBuildOutput, "logBuildOutput");
}
});
// src/dev/use-esbuild.ts
function runBuild({
entry,
destination,
jsxFactory,
jsxFragment,
processEntrypoint,
additionalModules,
rules,
tsconfig,
minify,
keepNames,
nodejsCompatMode,
compatibilityDate,
compatibilityFlags,
define,
alias,
noBundle,
findAdditionalModules: findAdditionalModules2,
durableObjects,
workflows,
local,
targetConsumer,
testScheduled,
projectRoot,
onStart,
defineNavigatorUserAgent,
checkFetch
}, setBundle, onErr) {
let stopWatching = void 0;
const entryDirectory = import_node_path22.default.dirname(entry.file);
const moduleCollector = noBundle ? noopModuleCollector : createModuleCollector({
wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences(
entryDirectory,
entry.file
),
entry,
findAdditionalModules: findAdditionalModules2 ?? false,
rules
});
async function getAdditionalModules() {
return noBundle ? dedupeModulesByName([
...await findAdditionalModules(entry, rules) ?? [],
...additionalModules
]) : additionalModules;
}
__name(getAdditionalModules, "getAdditionalModules");
async function updateBundle() {
const newAdditionalModules = await getAdditionalModules();
setBundle((previousBundle) => {
(0, import_node_assert10.default)(
previousBundle,
"Rebuild triggered with no previous build available"
);
previousBundle.modules = dedupeModulesByName([
...moduleCollector?.modules ?? [],
...newAdditionalModules
]);
return {
...previousBundle,
entrypointSource: (0, import_node_fs12.readFileSync)(previousBundle.path, "utf8"),
id: previousBundle.id + 1
};
});
}
__name(updateBundle, "updateBundle");
async function build5() {
if (!destination) {
return;
}
const newAdditionalModules = await getAdditionalModules();
const bundleResult = processEntrypoint || !noBundle ? await bundleWorker(entry, destination, {
bundle: !noBundle,
moduleCollector,
additionalModules: newAdditionalModules,
jsxFactory,
jsxFragment,
watch: true,
tsconfig,
minify,
keepNames,
nodejsCompatMode,
compatibilityDate,
compatibilityFlags,
doBindings: durableObjects.bindings,
workflowBindings: workflows,
alias,
define,
targetConsumer,
testScheduled,
plugins: [logBuildOutput(nodejsCompatMode, onStart, updateBundle)],
local,
projectRoot,
defineNavigatorUserAgent,
// Pages specific options used by wrangler pages commands
entryName: void 0,
inject: void 0,
isOutfile: void 0,
external: void 0,
// sourcemap defaults to true in dev
sourcemap: void 0,
checkFetch,
metafile: void 0
}) : void 0;
stopWatching = bundleResult?.stop;
if (noBundle) {
const watching = [import_node_path22.default.resolve(entry.moduleRoot)];
const watchPythonRequirements = getBundleType(entry.format, entry.file) === "python" ? import_node_path22.default.resolve(entry.projectRoot, "cf-requirements.txt") : void 0;
if (watchPythonRequirements) {
watching.push(watchPythonRequirements);
}
const watcher = watch(watching, {
persistent: true,
ignored: [".git", "node_modules"]
}).on("change", async (_event) => {
await updateBundle();
});
stopWatching = /* @__PURE__ */ __name(() => watcher.close(), "stopWatching");
}
const entrypointPath = (0, import_node_fs12.realpathSync)(
bundleResult?.resolvedEntryPointPath ?? entry.file
);
setBundle(() => ({
id: 0,
entry,
path: entrypointPath,
type: bundleResult?.bundleType ?? getBundleType(entry.format, entry.file),
modules: bundleResult ? bundleResult.modules : newAdditionalModules,
dependencies: bundleResult?.dependencies ?? {},
sourceMapPath: bundleResult?.sourceMapPath,
sourceMapMetadata: bundleResult?.sourceMapMetadata,
entrypointSource: (0, import_node_fs12.readFileSync)(entrypointPath, "utf8")
}));
}
__name(build5, "build");
build5().catch((err) => {
onErr(err);
});
return () => stopWatching?.();
}
var import_node_assert10, import_node_fs12, import_node_path22;
var init_use_esbuild = __esm({
"src/dev/use-esbuild.ts"() {
init_import_meta_url();
import_node_assert10 = __toESM(require("assert"));
import_node_fs12 = require("fs");
import_node_path22 = __toESM(require("path"));
init_esm4();
init_bundle();
init_bundle_type();
init_dedupe_modules();
init_log_build_output();
init_find_additional_modules();
init_module_collection();
__name(runBuild, "runBuild");
}
});
// src/navigator-user-agent.ts
function isNavigatorDefined(compatibility_date, compatibility_flags = []) {
if (compatibility_flags.includes("global_navigator") && compatibility_flags.includes("no_global_navigator")) {
throw new UserError("Can't both enable and disable a flag");
}
if (compatibility_flags.includes("global_navigator")) {
return true;
}
if (compatibility_flags.includes("no_global_navigator")) {
return false;
}
return !!compatibility_date && compatibility_date >= "2022-03-21";
}
var init_navigator_user_agent = __esm({
"src/navigator-user-agent.ts"() {
init_import_meta_url();
init_errors();
__name(isNavigatorDefined, "isNavigatorDefined");
}
});
// src/utils/debounce.ts
function debounce(fn2, delayMs = 100) {
let crrTimeoutId;
return () => {
if (crrTimeoutId) {
clearTimeout(crrTimeoutId);
}
crrTimeoutId = setTimeout(() => {
fn2();
}, delayMs);
};
}
var init_debounce = __esm({
"src/utils/debounce.ts"() {
init_import_meta_url();
__name(debounce, "debounce");
}
});
// src/api/startDevWorker/BundlerController.ts
var import_assert2, import_fs13, import_path9, BundlerController;
var init_BundlerController = __esm({
"src/api/startDevWorker/BundlerController.ts"() {
init_import_meta_url();
import_assert2 = __toESM(require("assert"));
import_fs13 = require("fs");
import_path9 = __toESM(require("path"));
init_esm4();
init_bundle();
init_bundle_type();
init_module_collection();
init_no_bundle_worker();
init_run_custom_build();
init_dev2();
init_use_esbuild();
init_logger();
init_navigator_user_agent();
init_paths();
init_debounce();
init_BaseController();
init_events();
init_utils2();
BundlerController = class extends Controller {
static {
__name(this, "BundlerController");
}
#currentBundle;
#customBuildWatcher;
// Handle aborting in-flight custom builds as new ones come in from the filesystem watcher
#customBuildAborter = new AbortController();
async #runCustomBuild(config, filePath) {
this.#customBuildAborter.abort();
this.#customBuildAborter = new AbortController();
const buildAborter = this.#customBuildAborter;
const relativeFile = import_path9.default.relative(config.projectRoot, config.entrypoint) || ".";
logger.log(`The file ${filePath} changed, restarting build...`);
this.emitBundleStartEvent(config);
try {
await runCustomBuild(
config.entrypoint,
relativeFile,
{
cwd: config.build?.custom?.workingDirectory,
command: config.build?.custom?.command
},
config.config
);
if (buildAborter.signal.aborted) {
return;
}
(0, import_assert2.default)(this.#tmpDir);
if (!config.build?.bundle) {
const destinationDir = this.#tmpDir.path;
(0, import_fs13.writeFileSync)(
import_path9.default.join(destinationDir, import_path9.default.basename(config.entrypoint)),
(0, import_fs13.readFileSync)(config.entrypoint, "utf-8")
);
}
const entry = {
file: config.entrypoint,
projectRoot: config.projectRoot,
configPath: config.config,
format: config.build.format,
moduleRoot: config.build.moduleRoot,
exports: config.build.exports
};
const entryDirectory = import_path9.default.dirname(config.entrypoint);
const moduleCollector = createModuleCollector({
wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences(
entryDirectory,
config.entrypoint
),
entry,
// `moduleCollector` doesn't get used when `noBundle` is set, so
// `findAdditionalModules` always defaults to `false`
findAdditionalModules: config.build.findAdditionalModules ?? false,
rules: config.build.moduleRules
});
const bindings = (await convertBindingsToCfWorkerInitBindings(config.bindings)).bindings;
const bundleResult = !config.build?.bundle ? await noBundleWorker(
entry,
config.build.moduleRules,
this.#tmpDir.path
) : await bundleWorker(entry, this.#tmpDir.path, {
bundle: true,
additionalModules: [],
moduleCollector,
workflowBindings: bindings?.workflows ?? [],
doBindings: bindings?.durable_objects?.bindings ?? [],
jsxFactory: config.build.jsxFactory,
jsxFragment: config.build.jsxFactory,
tsconfig: config.build.tsconfig,
minify: config.build.minify,
keepNames: config.build.keepNames ?? true,
nodejsCompatMode: config.build.nodejsCompatMode,
compatibilityDate: config.compatibilityDate,
compatibilityFlags: config.compatibilityFlags,
define: config.build.define,
checkFetch: shouldCheckFetch(
config.compatibilityDate,
config.compatibilityFlags
),
alias: config.build.alias,
// We want to know if the build is for development or publishing
// This could potentially cause issues as we no longer have identical behaviour between dev and deploy?
targetConsumer: "dev",
local: !config.dev?.remote,
projectRoot: config.projectRoot,
defineNavigatorUserAgent: isNavigatorDefined(
config.compatibilityDate,
config.compatibilityFlags
),
testScheduled: config.dev.testScheduled,
plugins: void 0,
// Pages specific options used by wrangler pages commands
entryName: void 0,
inject: void 0,
isOutfile: void 0,
external: void 0,
// We don't use esbuild watching for custom builds
watch: void 0,
// sourcemap defaults to true in dev
sourcemap: void 0,
metafile: void 0
});
if (buildAborter.signal.aborted) {
return;
}
const entrypointPath = (0, import_fs13.realpathSync)(
bundleResult?.resolvedEntryPointPath ?? config.entrypoint
);
this.emitBundleCompleteEvent(config, {
id: 0,
entry,
path: entrypointPath,
type: bundleResult?.bundleType ?? getBundleType(config.build.format, config.entrypoint),
modules: bundleResult.modules,
dependencies: bundleResult?.dependencies ?? {},
sourceMapPath: bundleResult?.sourceMapPath,
sourceMapMetadata: bundleResult?.sourceMapMetadata,
entrypointSource: (0, import_fs13.readFileSync)(entrypointPath, "utf8")
});
} catch (err) {
logger.error("Custom build failed:", err);
this.emitErrorEvent({
type: "error",
reason: "Custom build failed",
cause: castErrorCause(err),
source: "BundlerController",
data: { config, filePath }
});
}
}
async #startCustomBuild(config) {
await this.#customBuildWatcher?.close();
this.#customBuildAborter?.abort();
if (!config.build?.custom?.command) {
return;
}
const pathsToWatch = config.build.custom.watch;
(0, import_assert2.default)(pathsToWatch, "config.build.custom.watch");
this.#customBuildWatcher = watch(pathsToWatch, {
persistent: true,
// The initial custom build is always done in getEntry()
ignoreInitial: true
});
this.#customBuildWatcher.on("ready", () => {
void this.#runCustomBuild(config, String(pathsToWatch));
});
this.#customBuildWatcher.on(
"all",
(_event, filePath) => void this.#runCustomBuild(config, filePath)
);
}
#bundlerCleanup;
#bundleBuildAborter = new AbortController();
async #startBundle(config) {
await this.#bundlerCleanup?.();
this.#bundleBuildAborter.abort();
this.#bundleBuildAborter = new AbortController();
const buildAborter = this.#bundleBuildAborter;
if (config.build?.custom?.command) {
return;
}
(0, import_assert2.default)(this.#tmpDir);
const entry = {
file: config.entrypoint,
projectRoot: config.projectRoot,
configPath: config.config,
format: config.build.format,
moduleRoot: config.build.moduleRoot,
exports: config.build.exports,
name: config.name
};
const { bindings } = await convertBindingsToCfWorkerInitBindings(
config.bindings
);
this.#bundlerCleanup = runBuild(
{
entry,
destination: this.#tmpDir.path,
jsxFactory: config.build?.jsxFactory,
jsxFragment: config.build?.jsxFragment,
processEntrypoint: Boolean(config.build?.processEntrypoint),
additionalModules: config.build?.additionalModules ?? [],
rules: config.build.moduleRules,
tsconfig: config.build?.tsconfig,
minify: config.build?.minify,
keepNames: config.build?.keepNames ?? true,
nodejsCompatMode: config.build.nodejsCompatMode,
compatibilityDate: config.compatibilityDate,
compatibilityFlags: config.compatibilityFlags,
define: config.build.define,
alias: config.build.alias,
noBundle: !config.build?.bundle,
findAdditionalModules: config.build?.findAdditionalModules,
durableObjects: bindings?.durable_objects ?? { bindings: [] },
workflows: bindings?.workflows ?? [],
local: !config.dev?.remote,
// startDevWorker only applies to "dev"
targetConsumer: "dev",
testScheduled: Boolean(config.dev?.testScheduled),
projectRoot: config.projectRoot,
onStart: /* @__PURE__ */ __name(() => {
this.emitBundleStartEvent(config);
}, "onStart"),
checkFetch: shouldCheckFetch(
config.compatibilityDate,
config.compatibilityFlags
),
defineNavigatorUserAgent: isNavigatorDefined(
config.compatibilityDate,
config.compatibilityFlags
)
},
(cb2) => {
const newBundle = cb2(this.#currentBundle);
if (!buildAborter.signal.aborted) {
this.emitBundleCompleteEvent(config, newBundle);
this.#currentBundle = newBundle;
}
},
(err) => {
if (!buildAborter.signal.aborted) {
this.emitErrorEvent({
type: "error",
reason: "Failed to construct initial bundle",
cause: castErrorCause(err),
source: "BundlerController",
data: void 0
});
}
}
);
}
#assetsWatcher;
async #ensureWatchingAssets(config) {
await this.#assetsWatcher?.close();
const debouncedRefreshBundle = debounce(() => {
if (this.#currentBundle) {
this.emitBundleCompleteEvent(config, this.#currentBundle);
}
});
if (config.assets?.directory) {
this.#assetsWatcher = watch(config.assets.directory, {
persistent: true,
ignoreInitial: true
}).on("all", async (eventName, filePath) => {
const message = getAssetChangeMessage(eventName, filePath);
logger.debug(`\u{1F300} ${message}...`);
debouncedRefreshBundle();
});
}
}
#tmpDir;
onConfigUpdate(event) {
this.#tmpDir?.remove();
try {
this.#tmpDir = getWranglerTmpDir(event.config.projectRoot, "dev");
} catch (e7) {
logger.error(
"Failed to create temporary directory to store built files."
);
this.emitErrorEvent({
type: "error",
reason: "Failed to create temporary directory to store built files.",
cause: castErrorCause(e7),
source: "BundlerController",
data: void 0
});
}
void this.#startCustomBuild(event.config);
void this.#startBundle(event.config);
void this.#ensureWatchingAssets(event.config);
}
async teardown() {
logger.debug("BundlerController teardown beginning...");
this.#customBuildAborter?.abort();
this.#tmpDir?.remove();
await Promise.all([
this.#bundlerCleanup?.(),
this.#customBuildWatcher?.close(),
this.#assetsWatcher?.close()
]);
logger.debug("BundlerController teardown complete");
}
emitBundleStartEvent(config) {
this.emit("bundleStart", { type: "bundleStart", config });
}
emitBundleCompleteEvent(config, bundle) {
this.emit("bundleComplete", { type: "bundleComplete", config, bundle });
}
};
}
});
// ../workers-shared/utils/configuration/parseStaticRouting.ts
function parseStaticRouting(input) {
if (input.length === 0) {
throw new Error(
"No `run_worker_first` rules were provided; must provide at least 1 rule."
);
}
if (input.length > MAX_ROUTES_RULES) {
throw new Error(
`Too many \`run_worker_first\` rules were provided; ${input.length} rules provided exceeds max of ${MAX_ROUTES_RULES}.`
);
}
const rawAssetWorkerRules = [];
const assetWorkerRules = [];
const userWorkerRules = [];
const invalidRules = [];
for (const rule of input) {
if (rule.startsWith("!/")) {
assetWorkerRules.push(rule.slice(1));
rawAssetWorkerRules.push(rule);
} else if (rule.startsWith("/")) {
userWorkerRules.push(rule);
} else if (rule.startsWith("!")) {
invalidRules.push(`'${rule}': negative rules must start with '!/'`);
} else {
invalidRules.push(`'${rule}': rules must start with '/' or '!/'`);
}
}
if (assetWorkerRules.length > 0 && userWorkerRules.length === 0) {
throw new Error(
"Only negative `run_worker_first` rules were provided; must provide at least 1 non-negative rule"
);
}
const invalidAssetWorkerRules = validateStaticRoutingRules(rawAssetWorkerRules);
const invalidUserWorkerRules = validateStaticRoutingRules(userWorkerRules);
const errorMessage = formatInvalidRoutes([
...invalidRules,
...invalidUserWorkerRules,
...invalidAssetWorkerRules
]);
if (errorMessage) {
throw new Error(errorMessage);
}
return { asset_worker: assetWorkerRules, user_worker: userWorkerRules };
}
function validateStaticRoutingRules(rules) {
const invalid = [];
const seen = /* @__PURE__ */ new Set();
for (const rule of rules) {
if (rule.length > MAX_ROUTES_RULE_LENGTH) {
invalid.push(
`'${rule}': all rules must be less than ${MAX_ROUTES_RULE_LENGTH} characters in length`
);
}
if (seen.has(rule)) {
invalid.push(`'${rule}': rule is a duplicate; rules must be unique`);
}
if (rule.endsWith("*")) {
for (const otherRule of rules) {
if (otherRule !== rule && otherRule.startsWith(rule.slice(0, -1))) {
invalid.push(`'${otherRule}': rule '${rule}' makes it redundant`);
}
}
}
seen.add(rule);
}
return invalid;
}
var formatInvalidRoutes;
var init_parseStaticRouting = __esm({
"../workers-shared/utils/configuration/parseStaticRouting.ts"() {
init_import_meta_url();
init_constants3();
__name(parseStaticRouting, "parseStaticRouting");
__name(validateStaticRoutingRules, "validateStaticRoutingRules");
formatInvalidRoutes = /* @__PURE__ */ __name((invalidRules) => {
if (invalidRules.length === 0) {
return void 0;
}
return `Invalid routes in \`run_worker_first\`:
` + invalidRules.join("\n");
}, "formatInvalidRoutes");
}
});
// ../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js
var require_eventemitter3 = __commonJS({
"../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var has = Object.prototype.hasOwnProperty;
var prefix = "~";
function Events() {
}
__name(Events, "Events");
if (Object.create) {
Events.prototype = /* @__PURE__ */ Object.create(null);
if (!new Events().__proto__) prefix = false;
}
function EE(fn2, context2, once) {
this.fn = fn2;
this.context = context2;
this.once = once || false;
}
__name(EE, "EE");
function addListener(emitter, event, fn2, context2, once) {
if (typeof fn2 !== "function") {
throw new TypeError("The listener must be a function");
}
var listener = new EE(fn2, context2 || emitter, once), evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
__name(addListener, "addListener");
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
__name(clearEvent, "clearEvent");
function EventEmitter5() {
this._events = new Events();
this._eventsCount = 0;
}
__name(EventEmitter5, "EventEmitter");
EventEmitter5.prototype.eventNames = /* @__PURE__ */ __name(function eventNames() {
var names = [], events6, name2;
if (this._eventsCount === 0) return names;
for (name2 in events6 = this._events) {
if (has.call(events6, name2)) names.push(prefix ? name2.slice(1) : name2);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events6));
}
return names;
}, "eventNames");
EventEmitter5.prototype.listeners = /* @__PURE__ */ __name(function listeners(event) {
var evt = prefix ? prefix + event : event, handlers2 = this._events[evt];
if (!handlers2) return [];
if (handlers2.fn) return [handlers2.fn];
for (var i5 = 0, l6 = handlers2.length, ee = new Array(l6); i5 < l6; i5++) {
ee[i5] = handlers2[i5].fn;
}
return ee;
}, "listeners");
EventEmitter5.prototype.listenerCount = /* @__PURE__ */ __name(function listenerCount(event) {
var evt = prefix ? prefix + event : event, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
}, "listenerCount");
EventEmitter5.prototype.emit = /* @__PURE__ */ __name(function emit(event, a1, a22, a32, a42, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt], len = arguments.length, args, i5;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
switch (len) {
case 1:
return listeners.fn.call(listeners.context), true;
case 2:
return listeners.fn.call(listeners.context, a1), true;
case 3:
return listeners.fn.call(listeners.context, a1, a22), true;
case 4:
return listeners.fn.call(listeners.context, a1, a22, a32), true;
case 5:
return listeners.fn.call(listeners.context, a1, a22, a32, a42), true;
case 6:
return listeners.fn.call(listeners.context, a1, a22, a32, a42, a5), true;
}
for (i5 = 1, args = new Array(len - 1); i5 < len; i5++) {
args[i5 - 1] = arguments[i5];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length, j6;
for (i5 = 0; i5 < length; i5++) {
if (listeners[i5].once) this.removeListener(event, listeners[i5].fn, void 0, true);
switch (len) {
case 1:
listeners[i5].fn.call(listeners[i5].context);
break;
case 2:
listeners[i5].fn.call(listeners[i5].context, a1);
break;
case 3:
listeners[i5].fn.call(listeners[i5].context, a1, a22);
break;
case 4:
listeners[i5].fn.call(listeners[i5].context, a1, a22, a32);
break;
default:
if (!args) for (j6 = 1, args = new Array(len - 1); j6 < len; j6++) {
args[j6 - 1] = arguments[j6];
}
listeners[i5].fn.apply(listeners[i5].context, args);
}
}
}
return true;
}, "emit");
EventEmitter5.prototype.on = /* @__PURE__ */ __name(function on(event, fn2, context2) {
return addListener(this, event, fn2, context2, false);
}, "on");
EventEmitter5.prototype.once = /* @__PURE__ */ __name(function once(event, fn2, context2) {
return addListener(this, event, fn2, context2, true);
}, "once");
EventEmitter5.prototype.removeListener = /* @__PURE__ */ __name(function removeListener(event, fn2, context2, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn2) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (listeners.fn === fn2 && (!once || listeners.once) && (!context2 || listeners.context === context2)) {
clearEvent(this, evt);
}
} else {
for (var i5 = 0, events6 = [], length = listeners.length; i5 < length; i5++) {
if (listeners[i5].fn !== fn2 || once && !listeners[i5].once || context2 && listeners[i5].context !== context2) {
events6.push(listeners[i5]);
}
}
if (events6.length) this._events[evt] = events6.length === 1 ? events6[0] : events6;
else clearEvent(this, evt);
}
return this;
}, "removeListener");
EventEmitter5.prototype.removeAllListeners = /* @__PURE__ */ __name(function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
}, "removeAllListeners");
EventEmitter5.prototype.off = EventEmitter5.prototype.removeListener;
EventEmitter5.prototype.addListener = EventEmitter5.prototype.on;
EventEmitter5.prefixed = prefix;
EventEmitter5.EventEmitter = EventEmitter5;
if ("undefined" !== typeof module3) {
module3.exports = EventEmitter5;
}
}
});
// ../../node_modules/.pnpm/p-timeout@5.0.2/node_modules/p-timeout/index.js
function pTimeout(promise, milliseconds, fallback, options) {
let timer;
const cancelablePromise = new Promise((resolve25, reject) => {
if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
}
if (milliseconds === Number.POSITIVE_INFINITY) {
resolve25(promise);
return;
}
options = {
customTimers: { setTimeout, clearTimeout },
...options
};
timer = options.customTimers.setTimeout.call(void 0, () => {
if (typeof fallback === "function") {
try {
resolve25(fallback());
} catch (error2) {
reject(error2);
}
return;
}
const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
const timeoutError2 = fallback instanceof Error ? fallback : new TimeoutError(message);
if (typeof promise.cancel === "function") {
promise.cancel();
}
reject(timeoutError2);
}, milliseconds);
(async () => {
try {
resolve25(await promise);
} catch (error2) {
reject(error2);
} finally {
options.customTimers.clearTimeout.call(void 0, timer);
}
})();
});
cancelablePromise.clear = () => {
clearTimeout(timer);
timer = void 0;
};
return cancelablePromise;
}
var TimeoutError;
var init_p_timeout = __esm({
"../../node_modules/.pnpm/p-timeout@5.0.2/node_modules/p-timeout/index.js"() {
init_import_meta_url();
TimeoutError = class extends Error {
static {
__name(this, "TimeoutError");
}
constructor(message) {
super(message);
this.name = "TimeoutError";
}
};
__name(pTimeout, "pTimeout");
}
});
// ../../node_modules/.pnpm/p-queue@7.2.0/node_modules/p-queue/dist/lower-bound.js
function lowerBound(array, value, comparator) {
let first = 0;
let count = array.length;
while (count > 0) {
const step = Math.trunc(count / 2);
let it = first + step;
if (comparator(array[it], value) <= 0) {
first = ++it;
count -= step + 1;
} else {
count = step;
}
}
return first;
}
var init_lower_bound = __esm({
"../../node_modules/.pnpm/p-queue@7.2.0/node_modules/p-queue/dist/lower-bound.js"() {
init_import_meta_url();
__name(lowerBound, "lowerBound");
}
});
// ../../node_modules/.pnpm/p-queue@7.2.0/node_modules/p-queue/dist/priority-queue.js
var __classPrivateFieldGet2, _PriorityQueue_queue, PriorityQueue;
var init_priority_queue = __esm({
"../../node_modules/.pnpm/p-queue@7.2.0/node_modules/p-queue/dist/priority-queue.js"() {
init_import_meta_url();
init_lower_bound();
__classPrivateFieldGet2 = function(receiver, state2, kind, f6) {
if (kind === "a" && !f6) throw new TypeError("Private accessor was defined without a getter");
if (typeof state2 === "function" ? receiver !== state2 || !f6 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f6 : kind === "a" ? f6.call(receiver) : f6 ? f6.value : state2.get(receiver);
};
PriorityQueue = class {
static {
__name(this, "PriorityQueue");
}
constructor() {
_PriorityQueue_queue.set(this, []);
}
enqueue(run2, options) {
options = {
priority: 0,
...options
};
const element = {
priority: options.priority,
run: run2
};
if (this.size && __classPrivateFieldGet2(this, _PriorityQueue_queue, "f")[this.size - 1].priority >= options.priority) {
__classPrivateFieldGet2(this, _PriorityQueue_queue, "f").push(element);
return;
}
const index = lowerBound(__classPrivateFieldGet2(this, _PriorityQueue_queue, "f"), element, (a5, b6) => b6.priority - a5.priority);
__classPrivateFieldGet2(this, _PriorityQueue_queue, "f").splice(index, 0, element);
}
dequeue() {
const item = __classPrivateFieldGet2(this, _PriorityQueue_queue, "f").shift();
return item === null || item === void 0 ? void 0 : item.run;
}
filter(options) {
return __classPrivateFieldGet2(this, _PriorityQueue_queue, "f").filter((element) => element.priority === options.priority).map((element) => element.run);
}
get size() {
return __classPrivateFieldGet2(this, _PriorityQueue_queue, "f").length;
}
};
_PriorityQueue_queue = /* @__PURE__ */ new WeakMap();
}
});
// ../../node_modules/.pnpm/p-queue@7.2.0/node_modules/p-queue/dist/index.js
var import_eventemitter3, __classPrivateFieldSet, __classPrivateFieldGet3, _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pendingCount, _PQueue_concurrency, _PQueue_isPaused, _PQueue_resolveEmpty, _PQueue_resolveIdle, _PQueue_timeout, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_resolvePromises, _PQueue_onResumeInterval, _PQueue_isIntervalPaused, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, empty, timeoutError, AbortError, PQueue;
var init_dist2 = __esm({
"../../node_modules/.pnpm/p-queue@7.2.0/node_modules/p-queue/dist/index.js"() {
init_import_meta_url();
import_eventemitter3 = __toESM(require_eventemitter3(), 1);
init_p_timeout();
init_priority_queue();
__classPrivateFieldSet = function(receiver, state2, value, kind, f6) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f6) throw new TypeError("Private accessor was defined without a setter");
if (typeof state2 === "function" ? receiver !== state2 || !f6 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f6.call(receiver, value) : f6 ? f6.value = value : state2.set(receiver, value), value;
};
__classPrivateFieldGet3 = function(receiver, state2, kind, f6) {
if (kind === "a" && !f6) throw new TypeError("Private accessor was defined without a getter");
if (typeof state2 === "function" ? receiver !== state2 || !f6 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f6 : kind === "a" ? f6.call(receiver) : f6 ? f6.value : state2.get(receiver);
};
empty = /* @__PURE__ */ __name(() => {
}, "empty");
timeoutError = new TimeoutError();
AbortError = class extends Error {
static {
__name(this, "AbortError");
}
};
PQueue = class extends import_eventemitter3.default {
static {
__name(this, "PQueue");
}
constructor(options) {
var _a4, _b2, _c3, _d2;
super();
_PQueue_instances.add(this);
_PQueue_carryoverConcurrencyCount.set(this, void 0);
_PQueue_isIntervalIgnored.set(this, void 0);
_PQueue_intervalCount.set(this, 0);
_PQueue_intervalCap.set(this, void 0);
_PQueue_interval.set(this, void 0);
_PQueue_intervalEnd.set(this, 0);
_PQueue_intervalId.set(this, void 0);
_PQueue_timeoutId.set(this, void 0);
_PQueue_queue.set(this, void 0);
_PQueue_queueClass.set(this, void 0);
_PQueue_pendingCount.set(this, 0);
_PQueue_concurrency.set(this, void 0);
_PQueue_isPaused.set(this, void 0);
_PQueue_resolveEmpty.set(this, empty);
_PQueue_resolveIdle.set(this, empty);
_PQueue_timeout.set(this, void 0);
_PQueue_throwOnTimeout.set(this, void 0);
options = {
carryoverConcurrencyCount: false,
intervalCap: Number.POSITIVE_INFINITY,
interval: 0,
concurrency: Number.POSITIVE_INFINITY,
autoStart: true,
queueClass: PriorityQueue,
...options
};
if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b2 = (_a4 = options.intervalCap) === null || _a4 === void 0 ? void 0 : _a4.toString()) !== null && _b2 !== void 0 ? _b2 : ""}\` (${typeof options.intervalCap})`);
}
if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d2 = (_c3 = options.interval) === null || _c3 === void 0 ? void 0 : _c3.toString()) !== null && _d2 !== void 0 ? _d2 : ""}\` (${typeof options.interval})`);
}
__classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, "f");
__classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, "f");
__classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, "f");
__classPrivateFieldSet(this, _PQueue_interval, options.interval, "f");
__classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), "f");
__classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, "f");
this.concurrency = options.concurrency;
__classPrivateFieldSet(this, _PQueue_timeout, options.timeout, "f");
__classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, "f");
__classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, "f");
}
get concurrency() {
return __classPrivateFieldGet3(this, _PQueue_concurrency, "f");
}
set concurrency(newConcurrency) {
if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
}
__classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, "f");
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_processQueue).call(this);
}
/**
Adds a sync or async task to the queue. Always returns a promise.
*/
async add(fn2, options = {}) {
return new Promise((resolve25, reject) => {
const run2 = /* @__PURE__ */ __name(async () => {
var _a4;
var _b2, _c3;
__classPrivateFieldSet(this, _PQueue_pendingCount, (_b2 = __classPrivateFieldGet3(this, _PQueue_pendingCount, "f"), _b2++, _b2), "f");
__classPrivateFieldSet(this, _PQueue_intervalCount, (_c3 = __classPrivateFieldGet3(this, _PQueue_intervalCount, "f"), _c3++, _c3), "f");
try {
if ((_a4 = options.signal) === null || _a4 === void 0 ? void 0 : _a4.aborted) {
reject(new AbortError("The task was aborted."));
return;
}
const operation = __classPrivateFieldGet3(this, _PQueue_timeout, "f") === void 0 && options.timeout === void 0 ? fn2({ signal: options.signal }) : pTimeout(Promise.resolve(fn2({ signal: options.signal })), options.timeout === void 0 ? __classPrivateFieldGet3(this, _PQueue_timeout, "f") : options.timeout, () => {
if (options.throwOnTimeout === void 0 ? __classPrivateFieldGet3(this, _PQueue_throwOnTimeout, "f") : options.throwOnTimeout) {
reject(timeoutError);
}
return void 0;
});
const result = await operation;
resolve25(result);
this.emit("completed", result);
} catch (error2) {
reject(error2);
this.emit("error", error2);
}
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_next).call(this);
}, "run");
__classPrivateFieldGet3(this, _PQueue_queue, "f").enqueue(run2, options);
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this);
this.emit("add");
});
}
/**
Same as `.add()`, but accepts an array of sync or async functions.
@returns A promise that resolves when all functions are resolved.
*/
async addAll(functions, options) {
return Promise.all(functions.map(async (function_) => this.add(function_, options)));
}
/**
Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
*/
start() {
if (!__classPrivateFieldGet3(this, _PQueue_isPaused, "f")) {
return this;
}
__classPrivateFieldSet(this, _PQueue_isPaused, false, "f");
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_processQueue).call(this);
return this;
}
/**
Put queue execution on hold.
*/
pause() {
__classPrivateFieldSet(this, _PQueue_isPaused, true, "f");
}
/**
Clear the queue.
*/
clear() {
__classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet3(this, _PQueue_queueClass, "f"))(), "f");
}
/**
Can be called multiple times. Useful if you for example add additional items at a later time.
@returns A promise that settles when the queue becomes empty.
*/
async onEmpty() {
if (__classPrivateFieldGet3(this, _PQueue_queue, "f").size === 0) {
return;
}
return new Promise((resolve25) => {
const existingResolve = __classPrivateFieldGet3(this, _PQueue_resolveEmpty, "f");
__classPrivateFieldSet(this, _PQueue_resolveEmpty, () => {
existingResolve();
resolve25();
}, "f");
});
}
/**
@returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
*/
async onSizeLessThan(limit) {
if (__classPrivateFieldGet3(this, _PQueue_queue, "f").size < limit) {
return;
}
return new Promise((resolve25) => {
const listener = /* @__PURE__ */ __name(() => {
if (__classPrivateFieldGet3(this, _PQueue_queue, "f").size < limit) {
this.removeListener("next", listener);
resolve25();
}
}, "listener");
this.on("next", listener);
});
}
/**
The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
@returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
*/
async onIdle() {
if (__classPrivateFieldGet3(this, _PQueue_pendingCount, "f") === 0 && __classPrivateFieldGet3(this, _PQueue_queue, "f").size === 0) {
return;
}
return new Promise((resolve25) => {
const existingResolve = __classPrivateFieldGet3(this, _PQueue_resolveIdle, "f");
__classPrivateFieldSet(this, _PQueue_resolveIdle, () => {
existingResolve();
resolve25();
}, "f");
});
}
/**
Size of the queue, the number of queued items waiting to run.
*/
get size() {
return __classPrivateFieldGet3(this, _PQueue_queue, "f").size;
}
/**
Size of the queue, filtered by the given options.
For example, this can be used to find the number of items remaining in the queue with a specific priority level.
*/
sizeBy(options) {
return __classPrivateFieldGet3(this, _PQueue_queue, "f").filter(options).length;
}
/**
Number of running items (no longer in the queue).
*/
get pending() {
return __classPrivateFieldGet3(this, _PQueue_pendingCount, "f");
}
/**
Whether the queue is currently paused.
*/
get isPaused() {
return __classPrivateFieldGet3(this, _PQueue_isPaused, "f");
}
get timeout() {
return __classPrivateFieldGet3(this, _PQueue_timeout, "f");
}
/**
Set the timeout for future operations.
*/
set timeout(milliseconds) {
__classPrivateFieldSet(this, _PQueue_timeout, milliseconds, "f");
}
};
_PQueue_carryoverConcurrencyCount = /* @__PURE__ */ new WeakMap(), _PQueue_isIntervalIgnored = /* @__PURE__ */ new WeakMap(), _PQueue_intervalCount = /* @__PURE__ */ new WeakMap(), _PQueue_intervalCap = /* @__PURE__ */ new WeakMap(), _PQueue_interval = /* @__PURE__ */ new WeakMap(), _PQueue_intervalEnd = /* @__PURE__ */ new WeakMap(), _PQueue_intervalId = /* @__PURE__ */ new WeakMap(), _PQueue_timeoutId = /* @__PURE__ */ new WeakMap(), _PQueue_queue = /* @__PURE__ */ new WeakMap(), _PQueue_queueClass = /* @__PURE__ */ new WeakMap(), _PQueue_pendingCount = /* @__PURE__ */ new WeakMap(), _PQueue_concurrency = /* @__PURE__ */ new WeakMap(), _PQueue_isPaused = /* @__PURE__ */ new WeakMap(), _PQueue_resolveEmpty = /* @__PURE__ */ new WeakMap(), _PQueue_resolveIdle = /* @__PURE__ */ new WeakMap(), _PQueue_timeout = /* @__PURE__ */ new WeakMap(), _PQueue_throwOnTimeout = /* @__PURE__ */ new WeakMap(), _PQueue_instances = /* @__PURE__ */ new WeakSet(), _PQueue_doesIntervalAllowAnother_get = /* @__PURE__ */ __name(function _PQueue_doesIntervalAllowAnother_get2() {
return __classPrivateFieldGet3(this, _PQueue_isIntervalIgnored, "f") || __classPrivateFieldGet3(this, _PQueue_intervalCount, "f") < __classPrivateFieldGet3(this, _PQueue_intervalCap, "f");
}, "_PQueue_doesIntervalAllowAnother_get"), _PQueue_doesConcurrentAllowAnother_get = /* @__PURE__ */ __name(function _PQueue_doesConcurrentAllowAnother_get2() {
return __classPrivateFieldGet3(this, _PQueue_pendingCount, "f") < __classPrivateFieldGet3(this, _PQueue_concurrency, "f");
}, "_PQueue_doesConcurrentAllowAnother_get"), _PQueue_next = /* @__PURE__ */ __name(function _PQueue_next2() {
var _a4;
__classPrivateFieldSet(this, _PQueue_pendingCount, (_a4 = __classPrivateFieldGet3(this, _PQueue_pendingCount, "f"), _a4--, _a4), "f");
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this);
this.emit("next");
}, "_PQueue_next"), _PQueue_resolvePromises = /* @__PURE__ */ __name(function _PQueue_resolvePromises2() {
__classPrivateFieldGet3(this, _PQueue_resolveEmpty, "f").call(this);
__classPrivateFieldSet(this, _PQueue_resolveEmpty, empty, "f");
if (__classPrivateFieldGet3(this, _PQueue_pendingCount, "f") === 0) {
__classPrivateFieldGet3(this, _PQueue_resolveIdle, "f").call(this);
__classPrivateFieldSet(this, _PQueue_resolveIdle, empty, "f");
this.emit("idle");
}
}, "_PQueue_resolvePromises"), _PQueue_onResumeInterval = /* @__PURE__ */ __name(function _PQueue_onResumeInterval2() {
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_onInterval).call(this);
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_initializeIntervalIfNeeded).call(this);
__classPrivateFieldSet(this, _PQueue_timeoutId, void 0, "f");
}, "_PQueue_onResumeInterval"), _PQueue_isIntervalPaused = /* @__PURE__ */ __name(function _PQueue_isIntervalPaused2() {
const now = Date.now();
if (__classPrivateFieldGet3(this, _PQueue_intervalId, "f") === void 0) {
const delay = __classPrivateFieldGet3(this, _PQueue_intervalEnd, "f") - now;
if (delay < 0) {
__classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet3(this, _PQueue_carryoverConcurrencyCount, "f") ? __classPrivateFieldGet3(this, _PQueue_pendingCount, "f") : 0, "f");
} else {
if (__classPrivateFieldGet3(this, _PQueue_timeoutId, "f") === void 0) {
__classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_onResumeInterval).call(this);
}, delay), "f");
}
return true;
}
}
return false;
}, "_PQueue_isIntervalPaused"), _PQueue_tryToStartAnother = /* @__PURE__ */ __name(function _PQueue_tryToStartAnother2() {
if (__classPrivateFieldGet3(this, _PQueue_queue, "f").size === 0) {
if (__classPrivateFieldGet3(this, _PQueue_intervalId, "f")) {
clearInterval(__classPrivateFieldGet3(this, _PQueue_intervalId, "f"));
}
__classPrivateFieldSet(this, _PQueue_intervalId, void 0, "f");
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_resolvePromises).call(this);
return false;
}
if (!__classPrivateFieldGet3(this, _PQueue_isPaused, "f")) {
const canInitializeInterval = !__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_isIntervalPaused).call(this);
if (__classPrivateFieldGet3(this, _PQueue_instances, "a", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet3(this, _PQueue_instances, "a", _PQueue_doesConcurrentAllowAnother_get)) {
const job = __classPrivateFieldGet3(this, _PQueue_queue, "f").dequeue();
if (!job) {
return false;
}
this.emit("active");
job();
if (canInitializeInterval) {
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_initializeIntervalIfNeeded).call(this);
}
return true;
}
}
return false;
}, "_PQueue_tryToStartAnother"), _PQueue_initializeIntervalIfNeeded = /* @__PURE__ */ __name(function _PQueue_initializeIntervalIfNeeded2() {
if (__classPrivateFieldGet3(this, _PQueue_isIntervalIgnored, "f") || __classPrivateFieldGet3(this, _PQueue_intervalId, "f") !== void 0) {
return;
}
__classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_onInterval).call(this);
}, __classPrivateFieldGet3(this, _PQueue_interval, "f")), "f");
__classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet3(this, _PQueue_interval, "f"), "f");
}, "_PQueue_initializeIntervalIfNeeded"), _PQueue_onInterval = /* @__PURE__ */ __name(function _PQueue_onInterval2() {
if (__classPrivateFieldGet3(this, _PQueue_intervalCount, "f") === 0 && __classPrivateFieldGet3(this, _PQueue_pendingCount, "f") === 0 && __classPrivateFieldGet3(this, _PQueue_intervalId, "f")) {
clearInterval(__classPrivateFieldGet3(this, _PQueue_intervalId, "f"));
__classPrivateFieldSet(this, _PQueue_intervalId, void 0, "f");
}
__classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet3(this, _PQueue_carryoverConcurrencyCount, "f") ? __classPrivateFieldGet3(this, _PQueue_pendingCount, "f") : 0, "f");
__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_processQueue).call(this);
}, "_PQueue_onInterval"), _PQueue_processQueue = /* @__PURE__ */ __name(function _PQueue_processQueue2() {
while (__classPrivateFieldGet3(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this)) {
}
}, "_PQueue_processQueue");
}
});
// src/cloudchamber/instance-type/instance-type.ts
async function promptForInstanceType(allowSkipping) {
let options = [
{ label: "dev: 1/16 vCPU, 256 MiB memory, 2 GB disk", value: "dev" },
{ label: "basic: 1/4 vCPU, 1 GiB memory, 4 GB disk", value: "basic" },
{ label: "standard: 1/2 vCPU, 4 GiB memory, 4 GB disk", value: "standard" }
];
if (allowSkipping) {
options = [{ label: "Do not set", value: "skip" }].concat(options);
}
const action = await inputPrompt({
question: "Which instance type should we use for your container?",
label: "",
defaultValue: false,
helpText: "",
type: "select",
options
});
switch (action) {
case "dev":
case "basic":
case "standard":
return action;
default:
return void 0;
}
}
function checkInstanceType(args, config) {
const instance_type = args.instanceType ?? config.instance_type;
if (instance_type === void 0) {
return;
}
if (args.memory !== void 0 || args.vcpu !== void 0) {
throw new UserError(
`Field "instance_type" is mutually exclusive with "memory" and "vcpu". These fields cannot be set together.`
);
}
switch (instance_type) {
case "dev":
case "basic":
case "standard":
return instance_type;
default:
throw new UserError(
`"instance_type" field value is expected to be one of "dev", "basic", or "standard", but got "${instance_type}"`
);
}
}
function getInstanceTypeUsage(instanceType) {
return instanceTypes[instanceType];
}
function inferInstanceType(config) {
for (const [instanceType, configuration] of Object.entries(instanceTypes)) {
if (config.vcpu === configuration.vcpu && config.memory_mib === configuration.memory_mib && config.disk?.size_mb === configuration.disk_mb) {
return instanceType;
}
}
}
function cleanForInstanceType(app) {
if (!("configuration" in app)) {
return app;
}
const instance_type = inferInstanceType(app.configuration);
if (instance_type !== void 0) {
app.configuration.instance_type = instance_type;
}
delete app.configuration.disk;
delete app.configuration.memory;
delete app.configuration.memory_mib;
delete app.configuration.vcpu;
return app;
}
var instanceTypes;
var init_instance_type = __esm({
"src/cloudchamber/instance-type/instance-type.ts"() {
init_import_meta_url();
init_interactive();
init_errors();
instanceTypes = {
// dev is the default instance type when REQUIRE_INSTANCE_TYPE is set
dev: {
vcpu: 0.0625,
memory_mib: 256,
disk_mb: 2e3
},
basic: {
vcpu: 0.25,
memory_mib: 1024,
disk_mb: 4e3
},
standard: {
vcpu: 0.5,
memory_mib: 4096,
disk_mb: 4e3
}
};
__name(promptForInstanceType, "promptForInstanceType");
__name(checkInstanceType, "checkInstanceType");
__name(getInstanceTypeUsage, "getInstanceTypeUsage");
__name(inferInstanceType, "inferInstanceType");
__name(cleanForInstanceType, "cleanForInstanceType");
}
});
// src/cloudchamber/limits.ts
function configToUsage(containerConfig) {
if ("instance_type" in containerConfig) {
return getInstanceTypeUsage(containerConfig.instance_type);
}
return {
vcpu: containerConfig.vcpu,
memory_mib: containerConfig.memory_mib,
disk_mb: containerConfig.disk_bytes / MB
};
}
function accountToLimits(account) {
return {
vcpu: account.limits.vcpu_per_deployment,
memory_mib: account.limits.memory_mib_per_deployment,
disk_mb: account.limits.disk_mb_per_deployment
};
}
async function ensureContainerLimits(options) {
const limits = accountToLimits(options.account);
if (!options.containerConfig) {
await ensureImageFitsLimits({
availableSizeInBytes: limits.disk_mb * MB,
pathToDocker: options.pathToDocker,
imageTag: options.imageTag
});
return;
}
const usage2 = configToUsage(options.containerConfig);
const errors = [];
if (usage2.vcpu > limits.vcpu) {
errors.push(
`Your container configuration uses ${usage2.vcpu} vCPU which exceeds the account limit of ${limits.vcpu} vCPU.`
);
}
if (usage2.memory_mib > limits.memory_mib) {
errors.push(
`Your container configuration uses ${usage2.memory_mib} MiB of memory which exceeds the account limit of ${limits.memory_mib} MiB.`
);
}
if (usage2.disk_mb > limits.disk_mb) {
errors.push(
`Your container configuration uses ${usage2.disk_mb} MB of disk which exceeds the account limit of ${limits.disk_mb} MB.`
);
}
if (errors.length > 0) {
throw new UserError(`Exceeded account limits: ${errors.join(" ")}`);
}
await ensureImageFitsLimits({
availableSizeInBytes: usage2.disk_mb * MB,
pathToDocker: options.pathToDocker,
imageTag: options.imageTag
});
}
async function ensureImageFitsLimits(options) {
const inspectOutput = await dockerImageInspect(options.pathToDocker, {
imageTag: options.imageTag,
formatString: "{{ .Size }} {{ len .RootFS.Layers }}"
});
const [sizeStr, layerStr] = inspectOutput.split(" ");
const size = parseInt(sizeStr, 10);
const layers = parseInt(layerStr, 10);
const requiredSizeInBytes = Math.ceil(size * 1.1 + layers * 16 * MiB);
logger.debug(
`Disk size limits when building container image: availableSize=${Math.ceil(options.availableSizeInBytes / MB)}MB, requiredSize=${Math.ceil(requiredSizeInBytes / MB)}MB`
);
if (options.availableSizeInBytes < requiredSizeInBytes) {
throw new UserError(
`Image too large: needs ${Math.ceil(requiredSizeInBytes / MB)}MB, but your app is limited to images with size ${options.availableSizeInBytes / MB}MB. Your need more disk for this image.`
);
}
}
var MB, MiB;
var init_limits = __esm({
"src/cloudchamber/limits.ts"() {
init_import_meta_url();
init_containers_shared();
init_errors();
init_logger();
init_instance_type();
MB = 1e3 * 1e3;
MiB = 1024 * 1024;
__name(configToUsage, "configToUsage");
__name(accountToLimits, "accountToLimits");
__name(ensureContainerLimits, "ensureContainerLimits");
__name(ensureImageFitsLimits, "ensureImageFitsLimits");
}
});
// src/cloudchamber/locations.ts
async function loadAccount() {
if (cachedAccount !== void 0) {
return cachedAccount;
}
const account = await AccountService.getMe();
cachedAccount = account;
return cachedAccount;
}
async function getLocations() {
return (await loadAccount()).locations;
}
function idToLocationName(locationId) {
if (!cachedAccount) {
throw new Error("Needs a call to loadAccount beforehand");
}
const locations = cachedAccount.locations;
for (const location of locations) {
if (location.location === locationId) {
return location.name;
}
}
return `Other (${locationId})`;
}
var cachedAccount;
var init_locations = __esm({
"src/cloudchamber/locations.ts"() {
init_import_meta_url();
init_containers_shared();
__name(loadAccount, "loadAccount");
__name(getLocations, "getLocations");
__name(idToLocationName, "idToLocationName");
}
});
// src/cloudchamber/build.ts
function buildYargs(yargs) {
return yargs.positional("PATH", {
type: "string",
describe: "Path for the directory containing the Dockerfile to build",
demandOption: true
}).option("tag", {
alias: "t",
type: "string",
demandOption: true,
describe: 'Name and optionally a tag (format: "name:tag")'
}).option("path-to-docker", {
type: "string",
default: "docker",
describe: "Path to your docker binary if it's not on $PATH",
demandOption: false
}).option("push", {
alias: "p",
type: "boolean",
describe: "Push the built image to Cloudflare's managed registry",
default: false
}).option("platform", {
type: "string",
default: "linux/amd64",
describe: "Platform to build for. Defaults to the architecture support by Workers (linux/amd64)",
demandOption: false,
hidden: true,
deprecated: true
});
}
function pushYargs(yargs) {
return yargs.option("path-to-docker", {
type: "string",
default: "docker",
describe: "Path to your docker binary if it's not on $PATH",
demandOption: false
}).positional("TAG", { type: "string", demandOption: true });
}
async function buildAndMaybePush(args, pathToDocker, push, containerConfig) {
try {
const imageTag = `${getCloudflareContainerRegistry()}/${args.tag}`;
const { buildCmd, dockerfile } = await constructBuildCommand(
{
tag: imageTag,
pathToDockerfile: args.pathToDockerfile,
buildContext: args.buildContext,
args: args.args,
platform: args.platform,
setNetworkToHost: Boolean(getCIOverrideNetworkModeHost())
},
logger
);
await dockerBuild(pathToDocker, {
buildCmd,
dockerfile
}).ready;
if (push) {
const imageInfo = await dockerImageInspect(pathToDocker, {
imageTag,
formatString: "{{ json .RepoDigests }} {{ .Id }}"
});
logger.debug(`'docker image inspect ${imageTag}':`, imageInfo);
const account = await loadAccount();
await ensureContainerLimits({
pathToDocker,
imageTag,
account,
containerConfig
});
await dockerLoginManagedRegistry(pathToDocker);
try {
const [digests, imageId] = imageInfo.split(" ");
const parsedDigests = JSON.parse(digests);
if (!Array.isArray(parsedDigests)) {
throw new Error(
`Expected RepoDigests from docker inspect to be an array but got ${JSON.stringify(parsedDigests)}`
);
}
const repositoryOnly = resolveImageName(
account.external_account_id,
imageTag
).split(":")[0];
const [digest, ...rest] = parsedDigests.filter((d6) => {
const resolved = resolveImageName(account.external_account_id, d6);
return typeof d6 === "string" && resolved.split("@")[0] === repositoryOnly;
});
if (rest.length > 0) {
throw new Error(
`Expected there to only be 1 valid digests for this repository: ${repositoryOnly} but there were ${rest.length + 1}`
);
}
const [image, hash] = digest.split("@");
const resolvedImage = resolveImageName(
account.external_account_id,
image
);
const remoteDigest = `${resolvedImage}@${hash}`;
const remoteManifest = runDockerCmdWithOutput(pathToDocker, [
"manifest",
"inspect",
"-v",
remoteDigest
]);
logger.debug(
`'docker manifest inspect -v ${remoteDigest}:`,
remoteManifest
);
const parsedRemoteManifest = JSON.parse(remoteManifest);
if (parsedRemoteManifest.Descriptor.digest === imageId) {
logger.log("Image already exists remotely, skipping push");
logger.debug(
`Untagging built image: ${args.tag} since there was no change.`
);
await runDockerCmd(pathToDocker, ["image", "rm", imageTag]);
return { remoteDigest };
}
} catch (error2) {
if (error2 instanceof Error) {
logger.debug(
`Checking for local image ${args.tag} failed with error: ${error2.message}`
);
}
}
const namespacedImageTag = getCloudflareRegistryWithAccountNamespace(
account.external_account_id,
args.tag
);
logger.log(
`Image does not exist remotely, pushing: ${namespacedImageTag}`
);
await runDockerCmd(pathToDocker, ["tag", imageTag, namespacedImageTag]);
await runDockerCmd(pathToDocker, ["push", namespacedImageTag]);
await runDockerCmd(pathToDocker, ["image", "rm", namespacedImageTag]);
}
return { newTag: imageTag };
} catch (error2) {
if (error2 instanceof Error) {
throw new UserError(error2.message, { cause: error2 });
}
throw new UserError("An unknown error occurred");
}
}
async function buildCommand(args) {
if ((0, import_fs14.existsSync)(args.PATH) && !isDir(args.PATH)) {
throw new UserError(
`${args.PATH} is not a directory. Please specify a valid directory path.`
);
}
if (args.platform !== "linux/amd64") {
throw new UserError(
`Unsupported platform: Platform "${args.platform}" is unsupported. Please use "linux/amd64" instead.`
);
}
const pathToDockerfile = (0, import_path10.join)(args.PATH, "Dockerfile");
await buildAndMaybePush(
{
tag: args.tag,
pathToDockerfile,
buildContext: args.PATH,
platform: args.platform
// no option to add env vars at build time...?
},
getDockerPath() ?? args.pathToDocker,
args.push,
// this means we aren't validating defined limits for a container when building an image
// we will, however, still validate the image size against account level disk limits
void 0
);
}
async function pushCommand(args, config) {
try {
await dockerLoginManagedRegistry(args.pathToDocker);
const accountId = config.account_id || await getAccountId(config);
const newTag = getCloudflareRegistryWithAccountNamespace(
accountId,
args.TAG
);
const dockerPath = args.pathToDocker ?? getDockerPath();
await checkImagePlatform(dockerPath, args.TAG);
await runDockerCmd(dockerPath, ["tag", args.TAG, newTag]);
await runDockerCmd(dockerPath, ["push", newTag]);
logger.log(`Pushed image: ${newTag}`);
} catch (error2) {
if (error2 instanceof Error) {
throw new UserError(error2.message);
}
throw new UserError("An unknown error occurred");
}
}
async function checkImagePlatform(pathToDocker, imageTag, expectedPlatform = "linux/amd64") {
const platform3 = await dockerImageInspect(pathToDocker, {
imageTag,
formatString: "{{ .Os }}/{{ .Architecture }}"
});
if (platform3 !== expectedPlatform) {
throw new Error(
`Unsupported platform: Image platform (${platform3}) does not match the expected platform (${expectedPlatform})`
);
}
}
var import_fs14, import_path10;
var init_build2 = __esm({
"src/cloudchamber/build.ts"() {
init_import_meta_url();
import_fs14 = require("fs");
import_path10 = require("path");
init_containers_shared();
init_misc_variables();
init_errors();
init_logger();
init_user2();
init_limits();
init_locations();
__name(buildYargs, "buildYargs");
__name(pushYargs, "pushYargs");
__name(buildAndMaybePush, "buildAndMaybePush");
__name(buildCommand, "buildCommand");
__name(pushCommand, "pushCommand");
__name(checkImagePlatform, "checkImagePlatform");
}
});
// src/core/helpers.ts
function demandOneOfOption(...options) {
return function(argv) {
const count = options.filter((option) => argv[option]).length;
const lastOption = options.pop();
if (count === 0) {
throw new CommandLineArgsError(
`Exactly one of the arguments ${options.join(
", "
)} and ${lastOption} is required`
);
} else if (count > 1) {
throw new CommandLineArgsError(
`Arguments ${options.join(
", "
)} and ${lastOption} are mutually exclusive`
);
}
return true;
};
}
function demandSingleValue(key, allow) {
return function(argv) {
if (Array.isArray(argv[key]) && !allow?.(argv)) {
throw new CommandLineArgsError(
`The argument "--${key}" expects a single value, but received multiple: ${JSON.stringify(argv[key])}.`
);
}
return true;
};
}
function isAliasDefinition(def) {
return def.aliasOf !== void 0;
}
function isCommandDefinition(def) {
return def.handler !== void 0;
}
function isNamespaceDefinition(def) {
return !isAliasDefinition(def) && !isCommandDefinition(def);
}
var init_helpers3 = __esm({
"src/core/helpers.ts"() {
init_import_meta_url();
init_errors();
__name(demandOneOfOption, "demandOneOfOption");
__name(demandSingleValue, "demandSingleValue");
__name(isAliasDefinition, "isAliasDefinition");
__name(isCommandDefinition, "isCommandDefinition");
__name(isNamespaceDefinition, "isNamespaceDefinition");
}
});
// src/core/CommandRegistry.ts
function constructStatusMessage(command2, status2) {
const indefiniteArticle = "aeiou".includes(status2[0]) ? "an" : "a";
return `\u{1F6A7} \`${command2}\` is ${indefiniteArticle} ${status2} command. Please report any issues to https://github.com/cloudflare/workers-sdk/issues/new/choose`;
}
var import_node_assert11, BETA_CMD_COLOR, CommandRegistry, CommandRegistrationError;
var init_CommandRegistry = __esm({
"src/core/CommandRegistry.ts"() {
init_import_meta_url();
import_node_assert11 = __toESM(require("assert"));
init_source();
init_helpers3();
BETA_CMD_COLOR = "#BD5B08";
CommandRegistry = class {
static {
__name(this, "CommandRegistry");
}
/**
* Root node of the definition tree.
*/
#DefinitionTreeRoot;
/**
* Set of registered namespaces.
*/
#registeredNamespaces;
/**
* Function to register a command.
*/
#registerCommand;
/**
* The tree structure representing all command definitions.
*/
#tree;
/**
* Initializes the command registry with the given command registration function.
*/
constructor(registerCommand) {
this.#DefinitionTreeRoot = { subtree: /* @__PURE__ */ new Map() };
this.#registeredNamespaces = /* @__PURE__ */ new Set();
this.#registerCommand = registerCommand;
this.#tree = this.#DefinitionTreeRoot.subtree;
}
/**
* Defines multiple commands and their corresponding definitions.
*/
define(defs) {
for (const def of defs) {
this.#defineOne(def);
}
}
getDefinitionTreeRoot() {
return this.#DefinitionTreeRoot;
}
/**
* Registers all commands in the command registry, walking through the definition tree.
*/
registerAll() {
for (const [segment, node2] of this.#tree.entries()) {
if (this.#registeredNamespaces.has(segment)) {
continue;
}
this.#registeredNamespaces.add(segment);
this.#walkTreeAndRegister(segment, node2, `wrangler ${segment}`);
}
}
/**
* Registers a specific namespace if not already registered.
* TODO: Remove this once all commands use the command registry.
* See https://github.com/cloudflare/workers-sdk/pull/7357#discussion_r1862138470 for more details.
*/
registerNamespace(namespace) {
if (this.#registeredNamespaces.has(namespace)) {
return;
}
const node2 = this.#tree.get(namespace);
if (!node2?.definition) {
throw new CommandRegistrationError(
`Missing namespace definition for 'wrangler ${namespace}'`
);
}
this.#registeredNamespaces.add(namespace);
this.#walkTreeAndRegister(namespace, node2, `wrangler ${namespace}`);
}
/**
* Defines a single command and its corresponding definition.
*/
#defineOne({
command: command2,
definition
}) {
if (isAliasDefinition(definition)) {
this.#upsertDefinition({ type: "alias", command: command2, ...definition });
}
if (isCommandDefinition(definition)) {
this.#upsertDefinition({ type: "command", command: command2, ...definition });
} else if (isNamespaceDefinition(definition)) {
this.#upsertDefinition({ type: "namespace", command: command2, ...definition });
}
}
/**
* Finds a node in the definition tree for the given command.
*
* @example
*
* this.#upsertDefinition({
* type: 'command',
* command: 'wrangler hello',
* handler: "helloHandlerFunction",
* metadata: {
* description: "Say hello",
* status: "stable",
* owner: "Cloudflare Team"
* }
* });
*
* const node = this.#findNodeFor('wrangler hello');
* console.log(node.definition.command); // Output: 'wrangler hello'
*
* const nonExistentNode = this.#findNodeFor('wrangler unknown');
* console.log(nonExistentNode); // Output: undefined
*/
#findNodeFor(command2) {
const segments = command2.split(" ").slice(1);
let node2 = this.#DefinitionTreeRoot;
for (const segment of segments) {
const child = node2.subtree.get(segment);
if (!child) {
return void 0;
}
node2 = child;
}
return node2;
}
/**
* Finds the parent node of a command in the tree.
*
* @example
*
* this.#upsertDefinition({
* type: 'namespace',
* command: 'wrangler interact',
* metadata: {
* description: "Greet",
* status: "stable",
* }
* });
* this.#upsertDefinition({
* type: 'command',
* command: 'wrangler interact hello',
* handler: () => {},
* metadata: {
* description: "Say hello",
* status: "stable",
* owner: "Cloudflare Team"
* }
* });
*
* const parentNode = this.#findParentFor('wrangler interact hello');
* console.log(parentNode.definition.command); // Output: 'wrangler interact'
*/
#findParentFor(command2) {
const parentCommand = command2.split(" ").slice(0, -2).join(" ");
return this.#findNodeFor(parentCommand);
}
/**
* Resolves the definition chain for a given command, following aliases and parent commands.
*
* @example
*
* this.#upsertDefinition({
* type: 'alias',
* command: 'wrangler greet',
* aliasOf: 'wrangler hello',
* metadata: {
* description: "A greeting alias for hello",
* status: "stable"
* }
* });
*
* const chain = this.#resolveDefinitionChain({
* type: 'alias',
* command: 'wrangler greet',
* aliasOf: 'wrangler hello',
* metadata: {
* description: "A greeting alias for hello",
* status: "stable"
* }
* });
* console.log(chain.map(def => def.command)); // Output: ['"wrangler greet" => "wrangler hello"']
*
* // The example throws an error because of a circular reference
* this.#upsertDefinition({
* type: 'alias',
* command: 'wrangler hello',
* aliasOf: 'wrangler greet',
* metadata: {
* description: "Alias for greet",
* status: "stable"
* }
* });
* const chain = this.#resolveDefinitionChain({
* type: 'alias',
* command: 'wrangler greet',
* aliasOf: 'wrangler hello',
* metadata: {
* description: "A greeting alias for hello",
* status: "stable"
* }
* });
*/
#resolveDefinitionChain(def) {
const chain2 = [];
const stringifyChain = /* @__PURE__ */ __name((...extra) => [...chain2, ...extra].map(({ command: command2 }) => `"${command2}"`).join(" => "), "stringifyChain");
while (true) {
if (chain2.includes(def)) {
throw new CommandRegistrationError(
`Circular reference detected for alias definition: "${def.command}" (resolving from ${stringifyChain(def)})`
);
}
chain2.push(def);
const node2 = def.type === "alias" ? this.#findNodeFor(def.aliasOf) : this.#findParentFor(def.command);
if (node2 === this.#DefinitionTreeRoot) {
return chain2;
}
if (!node2?.definition) {
throw new CommandRegistrationError(
`Missing definition for "${def.type === "alias" ? def.aliasOf : def.command}" (resolving from ${stringifyChain()})`
);
}
def = node2.definition;
}
}
/**
* Resolves a definition node, returning a non-alias definition and its associated metadata.
*
* @example
*
* this.#upsertDefinition({
* type: 'command',
* command: 'wrangler hello',
* handler: (args, { config }) => {},
* metadata: {
* description: "Say hello",
* status: "stable",
* owner: "Cloudflare Team"
* }
* });
* this.#upsertDefinition({
* type: 'alias',
* command: 'wrangler greet',
* aliasOf: 'wrangler hello',
* metadata: {
* description: "A greeting alias for hello",
* status: "stable"
* }
* });
*
* const { definition, subtree } = this.#resolveDefinitionNode({
* type: 'alias',
* command: 'wrangler greet',
* aliasOf: 'wrangler hello',
* metadata: {
* description: "A greeting alias for hello",
* status: "stable"
* }
* });
* console.log(definition.command); // Output: 'wrangler hello'
* console.log(subtree); // Output: empty Map if 'wrangler hello' has no further subcommands
*/
#resolveDefinitionNode(node2) {
(0, import_node_assert11.default)(node2.definition);
const chain2 = this.#resolveDefinitionChain(node2.definition);
const resolvedDef = chain2.find((def) => def.type !== "alias");
(0, import_node_assert11.default)(resolvedDef);
const { subtree } = node2.definition.type !== "alias" ? node2 : this.#findNodeFor(resolvedDef.command) ?? node2;
const definition = {
// take all properties from the resolved alias
...resolvedDef,
// keep the original command
command: node2.definition.command,
// flatten metadata from entire chain (decreasing precedence)
metadata: Object.assign(
{},
...chain2.map((def) => def.metadata).reverse()
)
};
return { definition, subtree };
}
/**
* Inserts or updates a command definition in the tree. When a command, alias, or namespace is added to the tree
* it will first split it into segments, e.g.
*
* `wrangler namespace-a` => ["namespace-a", "command-a"]
*
* Then it will walk through the segments and create a new node for each segment, creating an empty definition and
* a subtree for each. The next segment is then defined on that subtree.
*
* When the last segment is reached, the definition is added. This way, only commands and aliases have definitions, while
* namespaces are just nodes in the tree.
*
* @example
*
* this.#upsertDefinition({ type: 'command', command: 'wrangler command-a', ... });
* this.#upsertDefinition({ type: 'namespace', command: 'wrangler namespace-b', ... });
* this.#upsertDefinition({ type: 'command', command: 'wrangler command-b', ... });
*
* // Resulting tree:
*
* this.#DefinitionTreeRoot: {
* "subtree": {
* "command-a": {
* "definition": {
* "type": "command",
* "command": "wrangler command-a",
* "handler": (args, { config }) => {},
* "metadata": { "description": "Command a" }
* },
* "subtree": new Map()
* },
* "namespace-b": {
* "subtree": {
* "command-b": {
* "definition": {
* "type": "command",
* "command": "wrangler namespace-b command-b",
* "handler": (args, { config }) => {},
* "metadata": { "description": "Command b" }
* },
* "subtree": new Map()
* }
* }
* }
* }
* }
*/
#upsertDefinition(def) {
const segments = def.command.split(" ").slice(1);
let node2 = this.#DefinitionTreeRoot;
for (const segment of segments) {
const subtree = node2.subtree;
let child = subtree.get(segment);
if (!child) {
child = {
definition: void 0,
subtree: /* @__PURE__ */ new Map()
};
subtree.set(segment, child);
}
node2 = child;
}
if (node2.definition) {
throw new CommandRegistrationError(
`Duplicate definition for "${def.command}"`
);
}
node2.definition = def;
return node2;
}
/**
* Walks through the definition tree and registers all subcommands for a given segment.
*/
#walkTreeAndRegister(segment, node2, fullCommand) {
if (!node2.definition) {
throw new CommandRegistrationError(
`Missing namespace definition for '${fullCommand}'`
);
}
const aliasOf = node2.definition.type === "alias" && node2.definition.aliasOf;
const { definition: def, subtree } = this.#resolveDefinitionNode(node2);
if (aliasOf) {
def.metadata.description += `
Alias for "${aliasOf}".`;
}
if (def.metadata.deprecated) {
def.metadata.deprecatedMessage ??= `Deprecated: "${def.command}" is deprecated`;
}
if (def.metadata.status !== "stable") {
def.metadata.description += source_default.hex(BETA_CMD_COLOR)(
` [${def.metadata.status}]`
);
def.metadata.statusMessage ??= constructStatusMessage(
def.command,
def.metadata.status
);
}
if (def.type === "command") {
const commandPositionalArgsSuffix = def.positionalArgs?.map((key) => {
const { demandOption, array } = def.args?.[key] ?? {};
return demandOption ? `<${key}${array ? ".." : ""}>` : `[${key}${array ? ".." : ""}]`;
}).join(" ");
if (commandPositionalArgsSuffix) {
segment += " " + commandPositionalArgsSuffix;
}
}
const registerSubTreeCallback = /* @__PURE__ */ __name(() => {
for (const [nextSegment, nextNode] of subtree.entries()) {
this.#walkTreeAndRegister(
nextSegment,
nextNode,
`${fullCommand} ${nextSegment}`
);
}
}, "registerSubTreeCallback");
this.#registerCommand(segment, def, registerSubTreeCallback);
}
};
CommandRegistrationError = class extends Error {
static {
__name(this, "CommandRegistrationError");
}
};
__name(constructStatusMessage, "constructStatusMessage");
}
});
// ../../node_modules/.pnpm/semiver@1.1.0/node_modules/semiver/dist/semiver.mjs
function semiver_default(a5, b6, bool) {
a5 = a5.split(".");
b6 = b6.split(".");
return fn(a5[0], b6[0]) || fn(a5[1], b6[1]) || (b6[2] = b6.slice(2).join("."), bool = /[.-]/.test(a5[2] = a5.slice(2).join(".")), bool == /[.-]/.test(b6[2]) ? fn(a5[2], b6[2]) : bool ? -1 : 1);
}
var fn;
var init_semiver = __esm({
"../../node_modules/.pnpm/semiver@1.1.0/node_modules/semiver/dist/semiver.mjs"() {
init_import_meta_url();
fn = new Intl.Collator(0, { numeric: 1 }).compare;
__name(semiver_default, "default");
}
});
// ../../node_modules/.pnpm/supports-color@9.2.2/node_modules/supports-color/index.js
var supports_color_exports = {};
__export(supports_color_exports, {
createSupportsColor: () => createSupportsColor2,
default: () => supports_color_default2
});
function hasFlag2(flag, argv = import_node_process9.default.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);
}
function envForceColor2() {
if ("FORCE_COLOR" in env3) {
if (env3.FORCE_COLOR === "true") {
return 1;
}
if (env3.FORCE_COLOR === "false") {
return 0;
}
return env3.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env3.FORCE_COLOR, 10), 3);
}
}
function translateLevel2(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor2();
if (noFlagForceColor !== void 0) {
flagForceColor2 = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor2 : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
return 3;
}
if (hasFlag2("color=256")) {
return 2;
}
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env3.TERM === "dumb") {
return min;
}
if (import_node_process9.default.platform === "win32") {
const osRelease = import_node_os6.default.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env3) {
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env3) || env3.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env3) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
}
if ("TF_BUILD" in env3 && "AGENT_NAME" in env3) {
return 1;
}
if (env3.COLORTERM === "truecolor") {
return 3;
}
if ("TERM_PROGRAM" in env3) {
const version5 = Number.parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env3.TERM_PROGRAM) {
case "iTerm.app":
return version5 >= 3 ? 3 : 2;
case "Apple_Terminal":
return 2;
}
}
if (/-256(color)?$/i.test(env3.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
return 1;
}
if ("COLORTERM" in env3) {
return 1;
}
return min;
}
function createSupportsColor2(stream2, options = {}) {
const level = _supportsColor2(stream2, {
streamIsTTY: stream2 && stream2.isTTY,
...options
});
return translateLevel2(level);
}
var import_node_process9, import_node_os6, import_node_tty3, env3, flagForceColor2, supportsColor2, supports_color_default2;
var init_supports_color2 = __esm({
"../../node_modules/.pnpm/supports-color@9.2.2/node_modules/supports-color/index.js"() {
init_import_meta_url();
import_node_process9 = __toESM(require("process"), 1);
import_node_os6 = __toESM(require("os"), 1);
import_node_tty3 = __toESM(require("tty"), 1);
__name(hasFlag2, "hasFlag");
({ env: env3 } = import_node_process9.default);
if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
flagForceColor2 = 0;
} else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
flagForceColor2 = 1;
}
__name(envForceColor2, "envForceColor");
__name(translateLevel2, "translateLevel");
__name(_supportsColor2, "_supportsColor");
__name(createSupportsColor2, "createSupportsColor");
supportsColor2 = {
stdout: createSupportsColor2({ isTTY: import_node_tty3.default.isatty(1) }),
stderr: createSupportsColor2({ isTTY: import_node_tty3.default.isatty(2) })
};
supports_color_default2 = supportsColor2;
}
});
// src/wrangler-banner.ts
async function printWranglerBanner(performUpdateCheck = true) {
let text = typeof WRANGLER_PRERELEASE_LABEL === "undefined" ? ` \u26C5\uFE0F wrangler ${version}` : ` \u26C5\uFE0F wrangler ${version} (${source_default.blue(WRANGLER_PRERELEASE_LABEL)})`;
let maybeNewVersion;
if (performUpdateCheck) {
maybeNewVersion = await updateCheck();
if (maybeNewVersion !== void 0) {
text += ` (update available ${source_default.green(maybeNewVersion)})`;
}
}
logger.log(
"\n" + text + "\n" + (supports_color_default2.stdout ? source_default.hex("#FF8800")("\u2500".repeat(stripAnsi2(text).length)) : "\u2500".repeat(text.length))
);
if (semiver_default(process.versions.node, MIN_NODE_VERSION) < 0) {
logger.warn(
`Wrangler requires at least Node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}. Please update your version of Node.js.`
);
}
if (maybeNewVersion !== void 0) {
const currentMajor = parseInt(version.split(".")[0]);
const newMajor = parseInt(maybeNewVersion.split(".")[0]);
if (newMajor > currentMajor) {
logger.warn(
`The version of Wrangler you are using is now out-of-date.
Please update to the latest version to prevent critical errors.
Run \`npm install --save-dev wrangler@${newMajor}\` to update to the latest version.
After installation, run Wrangler with \`npx wrangler\`.`
);
}
}
}
var MIN_NODE_VERSION;
var init_wrangler_banner = __esm({
"src/wrangler-banner.ts"() {
init_import_meta_url();
init_source();
init_semiver();
init_strip_ansi();
init_supports_color2();
init_package();
init_logger();
init_update_check();
MIN_NODE_VERSION = "20.0.0";
__name(printWranglerBanner, "printWranglerBanner");
}
});
// src/cloudchamber/helpers/wrap.ts
async function wrap2(fn2) {
return fn2.then((data) => [data, null]).catch((err) => [null, err]);
}
var init_wrap = __esm({
"src/cloudchamber/helpers/wrap.ts"() {
init_import_meta_url();
__name(wrap2, "wrap");
}
});
// src/cloudchamber/common.ts
function parseImageName(value) {
const matches = value.match(imageRe);
if (matches === null) {
return {
err: "Invalid image format: expected NAME:TAG[@DIGEST] or NAME@DIGEST"
};
}
const name2 = matches[1];
const tag = matches[2];
const digest = matches[3] ?? matches[4];
if (tag === "latest") {
return { err: '"latest" tag is not allowed' };
}
return { name: name2, tag, digest };
}
function handleFailure(command2, cb2, scope) {
return async (args) => {
if (!isNonInteractiveOrCI()) {
await printWranglerBanner();
const commandStatus = command2.includes("cloudchamber") ? "alpha" : "open-beta";
logger.warn(constructStatusMessage(command2, commandStatus));
}
const config = readConfig(args);
await fillOpenAPIConfiguration(config, scope);
await cb2(args, config);
};
}
async function getAPIUrl(config, accountId, scope) {
const api = getCloudflareApiBaseUrl(config);
const endpoint = scope === cloudchamberScope ? "cloudchamber" : "containers";
return `${api}/accounts/${accountId}/${endpoint}`;
}
async function promiseSpinner(promise, {
message
} = {
message: "Loading"
}) {
if (isNonInteractiveOrCI()) {
return promise;
}
const { start, stop } = spinner();
start(message);
const t7 = await promise.catch((err) => {
stop();
throw err;
});
stop();
return t7;
}
async function fillOpenAPIConfiguration(config, scope) {
const headers = new Headers();
const accountId = await requireAuth(config);
const auth = requireApiToken();
const scopes = getScopes();
if (scopes !== void 0 && !scopes.includes(scope)) {
logger.error(`You don't have '${scope}' in your list of scopes`);
printScopes(scopes ?? []);
throw new UserError(
`You need '${scope}', try logging in again or creating an appropiate API token`
);
}
addAuthorizationHeaderIfUnspecified(headers, auth);
addUserAgent(headers);
OpenAPI.CREDENTIALS = "omit";
if (OpenAPI.BASE.length === 0) {
const [base, errApiURL] = await wrap2(getAPIUrl(config, accountId, scope));
if (errApiURL) {
throw new UserError("getting the API url: " + errApiURL.message);
}
OpenAPI.BASE = base;
}
OpenAPI.HEADERS = {
...OpenAPI.HEADERS ?? {},
...Object.fromEntries(headers.entries())
};
OpenAPI.LOGGER = logger;
}
function checkEverythingIsSet(object, keys) {
keys.forEach((key) => {
if (object[key] === void 0) {
throw new Error(
`${key} is required but it's not passed as an argument`
);
}
});
return object;
}
function renderDeploymentConfiguration(action, {
image,
location,
instanceType,
vcpu,
memoryMib,
environmentVariables,
labels,
env: env6,
network
}) {
let environmentVariablesText = "[]";
if (environmentVariables !== void 0) {
if (environmentVariables.length !== 0) {
environmentVariablesText = "\n" + environmentVariables.map((ev) => "- " + dim(ev.name + ":" + ev.value)).join("\n").trim();
}
} else if (action === "create") {
environmentVariablesText = `
No environment variables added! You can set some under [${env6 ? "env." + env6 + "." : ""}vars] and via command line`;
}
let labelsText = "[]";
if (labels !== void 0 && labels.length !== 0) {
labelsText = "\n" + labels.map((ev) => "- " + dim(ev.name + ":" + ev.value)).join("\n").trim();
}
const containerInformation = [
["image", image],
["location", idToLocationName(location)],
["environment variables", environmentVariablesText],
["labels", labelsText],
...network === void 0 ? [] : [["IPv4", network.assign_ipv4 === "predefined" ? "yes" : "no"]],
...instanceType === void 0 ? [
["vCPU", `${vcpu}`],
["memory", `${memoryMib} MiB`]
] : [["instance type", `${instanceType}`]]
];
updateStatus(
`You're about to ${action} a container with the following configuration
` + containerInformation.map(([key, text]) => `${brandColor(key)} ${dim(text)}`).join("\n")
);
}
function renderDeploymentMutationError(account, err) {
if (!(err instanceof ApiError)) {
throw new UserError(err.message);
}
if (typeof err.body === "string") {
throw new UserError("There has been an internal error, please try again!");
}
if (!("error" in err.body)) {
throw new UserError(err.message);
}
const errorMessage = err.body.error;
if (!(errorMessage in DeploymentMutationError)) {
throw new UserError(err.message);
}
const details = err.body.details ?? {};
function renderAccountLimits() {
return [
`${space(2)}${brandColor("Maximum VCPU per deployment")} ${account.limits.vcpu_per_deployment}`,
`${space(2)}${brandColor("Maximum total VCPU in your account")} ${account.limits.total_vcpu}`,
`${space(2)}${brandColor("Maximum memory per deployment")} ${account.limits.memory_mib_per_deployment} MiB`,
`${space(2)}${brandColor("Maximum total memory in your account")} ${account.limits.total_memory_mib} MiB`
].join("\n");
}
__name(renderAccountLimits, "renderAccountLimits");
function renderInvalidInputDetails(inputDetails) {
return `${Object.keys(inputDetails).map((key) => `${space(2)}- ${key}: ${inputDetails[key]}`).join("\n")}`;
}
__name(renderInvalidInputDetails, "renderInvalidInputDetails");
const errorEnum = errorMessage;
const errorEnumToErrorMessage = {
["LOCATION_NOT_ALLOWED" /* LOCATION_NOT_ALLOWED */]: () => "The location you have chosen is not allowed, try with another one",
["LOCATION_SURPASSED_BASE_LIMITS" /* LOCATION_SURPASSED_BASE_LIMITS */]: () => "The location you have chosen doesn't allow that deployment configuration due to its limits",
["SURPASSED_BASE_LIMITS" /* SURPASSED_BASE_LIMITS */]: () => "You deployment surpasses the base limits of your account\n" + renderAccountLimits(),
["VALIDATE_INPUT" /* VALIDATE_INPUT */]: () => "Your deployment configuration has invalid inputs\n" + renderInvalidInputDetails(err.body.details),
["SURPASSED_TOTAL_LIMITS" /* SURPASSED_TOTAL_LIMITS */]: () => "You have surpassed the limits of your account\n" + renderAccountLimits(),
["IMAGE_REGISTRY_NOT_CONFIGURED" /* IMAGE_REGISTRY_NOT_CONFIGURED */]: () => "The image registry you are trying to use is not configured. Use the 'wrangler cloudchamber registries configure' command to configure the registry.\n"
};
throw new UserError(
details["reason"] ?? errorEnumToErrorMessage[errorEnum]()
);
}
function sortEnvironmentVariables(environmentVariables) {
environmentVariables.sort((a5, b6) => a5.name.localeCompare(b6.name));
}
function collectEnvironmentVariables(deploymentEnv, config, envArgs) {
const envMap = /* @__PURE__ */ new Map();
if (deploymentEnv !== void 0) {
deploymentEnv.forEach((ev) => envMap.set(ev.name, ev.value));
}
Object.entries(config.vars).forEach(
([name2, value]) => envMap.set(name2, value?.toString() ?? "")
);
if (envArgs !== void 0) {
envArgs.forEach((v7) => {
const [name2, ...value] = v7.split(":");
envMap.set(name2, value.join(":"));
});
}
if (envMap.size === 0) {
return void 0;
}
const env6 = Array.from(envMap).map(
([name2, value]) => ({ name: name2, value })
);
sortEnvironmentVariables(env6);
return env6;
}
async function promptForEnvironmentVariables(environmentVariables, initiallySelected, allowSkipping) {
if (environmentVariables === void 0 || environmentVariables.length == 0) {
return void 0;
}
let options = [
{ label: "Use all of them", value: "all" },
{ label: "Use some", value: "select" },
{ label: "Do not use any", value: "none" }
];
if (allowSkipping) {
options = [{ label: "Do not modify", value: "skip" }].concat(options);
}
const action = await inputPrompt({
question: "You have environment variables defined, what do you want to do for this deployment?",
label: "",
defaultValue: false,
helpText: "",
type: "select",
options
});
if (action === "skip") {
return void 0;
}
if (action === "all") {
return environmentVariables;
}
if (action === "select") {
const selectedNames = await inputPrompt({
question: "Select the environment variables you want to use",
label: "",
defaultValue: initiallySelected,
helpText: "Use the 'space' key to select. Submit with 'enter'",
type: "multiselect",
options: environmentVariables.map((ev) => ({
label: ev.name,
value: ev.name
})),
validate: /* @__PURE__ */ __name((values) => {
if (!Array.isArray(values)) {
return "unknown error";
}
}, "validate")
});
const selectedNamesSet = new Set(selectedNames);
const selectedEnvironmentVariables = [];
for (const ev of environmentVariables) {
if (selectedNamesSet.has(ev.name)) {
selectedEnvironmentVariables.push(ev);
}
}
return selectedEnvironmentVariables;
}
return [];
}
function sortLabels(labels) {
labels.sort((a5, b6) => a5.name.localeCompare(b6.name));
}
function collectLabels(labelArgs) {
const labelMap = /* @__PURE__ */ new Map();
if (labelArgs !== void 0) {
labelArgs.forEach((v7) => {
const [name2, ...value] = v7.split(":");
labelMap.set(name2, value.join(":"));
});
}
if (labelMap.size === 0) {
return void 0;
}
const labels = Array.from(labelMap).map(([name2, value]) => ({
name: name2,
value
}));
sortLabels(labels);
return labels;
}
async function promptForLabels(labels, initiallySelected, allowSkipping) {
if (labels === void 0 || labels.length == 0) {
return void 0;
}
let options = [
{ label: "Use all of them", value: "all" },
{ label: "Use some", value: "select" },
{ label: "Do not use any", value: "none" }
];
if (allowSkipping) {
options = [{ label: "Do not modify", value: "skip" }].concat(options);
}
const action = await inputPrompt({
question: "You have labels defined, what do you want to do for this deployment?",
label: "",
defaultValue: false,
helpText: "",
type: "select",
options
});
if (action === "skip") {
return void 0;
}
if (action === "all") {
return labels;
}
if (action === "select") {
const selectedNames = await inputPrompt({
question: "Select the labels you want to use",
label: "",
defaultValue: initiallySelected,
helpText: "Use the 'space' key to select. Submit with 'enter'",
type: "multiselect",
options: labels.map((label) => ({
label: label.name,
value: label.name
})),
validate: /* @__PURE__ */ __name((values) => {
if (!Array.isArray(values)) {
return "unknown error";
}
}, "validate")
});
const selectedNamesSet = new Set(selectedNames);
const selectedLabels = [];
for (const ev of labels) {
if (selectedNamesSet.has(ev.name)) {
selectedLabels.push(ev);
}
}
return selectedLabels;
}
return [];
}
function resolveMemory(args, config) {
const MiB2 = 1024 * 1024;
const memory = args.memory ?? config.memory;
if (memory !== void 0) {
return Math.round(parseByteSize(memory, 1024) / MiB2);
}
return void 0;
}
var cloudchamberScope, imageRe;
var init_common = __esm({
"src/cloudchamber/common.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_interactive();
init_containers_shared();
init_internal();
init_config2();
init_CommandRegistry();
init_misc_variables();
init_errors();
init_is_interactive();
init_logger();
init_user2();
init_wrangler_banner();
init_parse();
init_wrap();
init_locations();
cloudchamberScope = "cloudchamber:write";
imageRe = (() => {
const alphaNumeric = "[a-z0-9]+";
const separator = "(?:\\.|_|__|-+)";
const port = ":[0-9]+";
const domain2 = `${alphaNumeric}(?:${separator}${alphaNumeric})*`;
const name2 = `(?:${domain2}(?:${port})?/)?(?:${domain2}/)*(?:${domain2})`;
const tag = ":([a-zA-Z0-9_][a-zA-Z0-9._-]{0,127})";
const digest = "@(sha256:[A-Fa-f0-9]+)";
const reference = `(?:${tag}(?:${digest})?|${digest})`;
return new RegExp(`^(${name2})${reference}$`);
})();
__name(parseImageName, "parseImageName");
__name(handleFailure, "handleFailure");
__name(getAPIUrl, "getAPIUrl");
__name(promiseSpinner, "promiseSpinner");
__name(fillOpenAPIConfiguration, "fillOpenAPIConfiguration");
__name(checkEverythingIsSet, "checkEverythingIsSet");
__name(renderDeploymentConfiguration, "renderDeploymentConfiguration");
__name(renderDeploymentMutationError, "renderDeploymentMutationError");
__name(sortEnvironmentVariables, "sortEnvironmentVariables");
__name(collectEnvironmentVariables, "collectEnvironmentVariables");
__name(promptForEnvironmentVariables, "promptForEnvironmentVariables");
__name(sortLabels, "sortLabels");
__name(collectLabels, "collectLabels");
__name(promptForLabels, "promptForLabels");
__name(resolveMemory, "resolveMemory");
}
});
// src/cloudchamber/images/images.ts
function deleteImageYargs(yargs) {
return yargs.positional("image", {
type: "string",
description: "Image and tag to delete, of the form IMAGE:TAG",
demandOption: true
});
}
function listImagesYargs(yargs) {
return yargs.option("filter", {
type: "string",
description: "Regex to filter results"
}).option("json", {
type: "boolean",
description: "Format output as JSON",
default: false
});
}
async function handleDeleteImageCommand(args, config) {
if (!args.image.includes(":")) {
throw new Error("Invalid image format. Expected IMAGE:TAG");
}
const digest = await promiseSpinner(
getCreds().then(async (creds) => {
const accountId = config.account_id || await getAccountId(config);
const url4 = new URL(`https://${getCloudflareContainerRegistry()}`);
const baseUrl = `${url4.protocol}//${url4.host}`;
const [image, tag] = args.image.split(":");
const digest_ = await deleteTag(baseUrl, accountId, image, tag, creds);
const gcUrl = `${baseUrl}/v2/gc/layers`;
const gcResponse = await fetch(gcUrl, {
method: "PUT",
headers: {
Authorization: `Basic ${creds}`,
"Content-Type": "application/json"
}
});
if (!gcResponse.ok) {
throw new Error(
`Failed to delete image ${args.image}: ${gcResponse.status} ${gcResponse.statusText}`
);
}
return digest_;
}),
{ message: `Deleting ${args.image}` }
);
logger.log(`Deleted ${args.image} (${digest})`);
}
async function handleListImagesCommand(args, config) {
const responses = await promiseSpinner(
getCreds().then(async (creds) => {
const repos = await listReposWithTags(creds);
const processed = [];
const accountId = config.account_id || await getAccountId(config);
const accountIdPrefix = new RegExp(`^${accountId}/`);
const filter = new RegExp(args.filter ?? "");
for (const [repo, tags] of Object.entries(repos)) {
const stripped = repo.replace(/^\/+/, "");
if (filter.test(stripped)) {
const name2 = stripped.replace(accountIdPrefix, "");
processed.push({ name: name2, tags });
}
}
return processed;
}),
{ message: "Listing" }
);
await listImages(responses, false, args.json);
}
async function listImages(responses, digests = false, json = false) {
if (!digests) {
responses = responses.map((resp) => {
return {
name: resp.name,
tags: resp.tags.filter((t7) => !t7.startsWith("sha256"))
};
});
}
responses = responses.filter((resp) => {
return resp.tags !== void 0 && resp.tags.length != 0;
});
if (json) {
logger.log(JSON.stringify(responses, null, 2));
} else {
const rows = responses.flatMap((r7) => r7.tags.map((t7) => [r7.name, t7]));
const headers = ["REPOSITORY", "TAG"];
const widths = new Array(headers.length).fill(0);
for (let i5 = 0; i5 < widths.length - 1; i5++) {
widths[i5] = rows.map((r7) => r7[i5].length).reduce((a5, b6) => Math.max(a5, b6), headers[i5].length);
}
logger.log(headers.map((h6, i5) => h6.padEnd(widths[i5], " ")).join(" "));
for (const row of rows) {
logger.log(row.map((v7, i5) => v7.padEnd(widths[i5], " ")).join(" "));
}
}
}
async function listReposWithTags(creds) {
const url4 = new URL(`https://${getCloudflareContainerRegistry()}`);
const catalogUrl = `${url4.protocol}//${url4.host}/v2/_catalog?tags=true`;
const response = await fetch(catalogUrl, {
method: "GET",
headers: {
Authorization: `Basic ${creds}`
}
});
if (!response.ok) {
logger.log(JSON.stringify(response));
throw new Error(
`Failed to fetch repository catalog: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
return data.repositories ?? {};
}
async function deleteTag(baseUrl, accountId, image, tag, creds) {
const manifestAcceptHeader = "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json";
const manifestUrl = `${baseUrl}/v2/${accountId}/${image}/manifests/${tag}`;
const headResponse = await fetch(manifestUrl, {
method: "HEAD",
headers: {
Authorization: `Basic ${creds}`,
Accept: manifestAcceptHeader
}
});
if (!headResponse.ok) {
throw new Error(
`Failed to retrieve info for ${image}:${tag}: ${headResponse.status} ${headResponse.statusText}`
);
}
const digest = headResponse.headers.get("Docker-Content-Digest");
if (!digest) {
throw new Error(`Digest not found for ${image}:${tag}.`);
}
const deleteUrl = `${baseUrl}/v2/${accountId}/${image}/manifests/${tag}`;
const deleteResponse = await fetch(deleteUrl, {
method: "DELETE",
headers: {
Authorization: `Basic ${creds}`,
Accept: manifestAcceptHeader
}
});
if (!deleteResponse.ok) {
throw new Error(
`Failed to delete ${image}:${tag} (digest: ${digest}): ${deleteResponse.status} ${deleteResponse.statusText}`
);
}
return digest;
}
async function getCreds() {
const credentials = await ImageRegistriesService.generateImageRegistryCredentials(
getCloudflareContainerRegistry(),
{
expiration_minutes: 5,
permissions: ["pull", "push"]
}
);
return Buffer.from(`v1:${credentials.password}`).toString("base64");
}
var imagesCommand;
var init_images2 = __esm({
"src/cloudchamber/images/images.ts"() {
init_import_meta_url();
init_containers_shared();
init_logger();
init_user2();
init_common();
imagesCommand = /* @__PURE__ */ __name((yargs, scope) => {
return yargs.command(
["list", "ls"],
"List images in the Cloudflare managed registry",
(args) => listImagesYargs(args),
(args) => handleFailure(
`wrangler containers images list`,
async (_args, config) => {
await handleListImagesCommand(args, config);
},
scope
)(args)
).command(
["delete <image>", "rm <image>"],
"Remove an image from the Cloudflare managed registry",
(args) => deleteImageYargs(args),
(args) => handleFailure(
`wrangler containers images delete`,
async (_args, config) => {
await handleDeleteImageCommand(args, config);
},
scope
)(args)
);
}, "imagesCommand");
__name(deleteImageYargs, "deleteImageYargs");
__name(listImagesYargs, "listImagesYargs");
__name(handleDeleteImageCommand, "handleDeleteImageCommand");
__name(handleListImagesCommand, "handleListImagesCommand");
__name(listImages, "listImages");
__name(listReposWithTags, "listReposWithTags");
__name(deleteTag, "deleteTag");
__name(getCreds, "getCreds");
}
});
// ../cli/args.ts
var processArgument;
var init_args = __esm({
"../cli/args.ts"() {
init_import_meta_url();
init_interactive();
processArgument = /* @__PURE__ */ __name(async (args, name2, promptConfig) => {
const value = args[name2];
const result = await inputPrompt({
...promptConfig,
// Accept the default value if the arg is already set
acceptDefault: promptConfig.acceptDefault ?? value !== void 0,
defaultValue: value ?? promptConfig.defaultValue
});
args[name2] = result;
return result;
}, "processArgument");
}
});
// src/containers/containers.ts
function deleteYargs(args) {
return args.positional("ID", {
describe: "id of the containers to delete",
type: "string",
demandOption: true
});
}
async function deleteCommand(deleteArgs, _config) {
const uuidRegex2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex2.test(deleteArgs.ID)) {
throw new UserError(
`Expected a container ID but got ${deleteArgs.ID}. Use \`wrangler containers list\` to view your containers and corresponding IDs.`
);
}
startSection("Delete your container");
if (!isNonInteractiveOrCI()) {
const yes = await inputPrompt({
question: "Are you sure that you want to delete these containers? The associated DO container will lose access to the containers.",
type: "confirm",
label: ""
});
if (!yes) {
cancel("The operation has been cancelled");
return;
}
}
try {
await ApplicationsService.deleteApplication(deleteArgs.ID);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (err instanceof ApiError) {
if (err.status === 400 || err.status === 404) {
throw new UserError(
`There has been an error deleting the container.
${err.body.error}`
);
}
throw new Error(
`There has been an unknown error deleting the container.
${JSON.stringify(err.body)}`
);
}
throw new Error(
`There has been an internal error deleting your containers.
${err.message}`
);
}
endSection("Your container has been deleted");
}
function infoYargs(args) {
return args.positional("ID", {
describe: "id of the containers to view",
type: "string"
});
}
async function infoCommand(infoArgs, _config) {
if (!infoArgs.ID) {
throw new Error(
"You must provide an ID. Use 'wrangler containers list` to view your containers."
);
}
if (isNonInteractiveOrCI()) {
const application2 = ApplicationsService.getApplication(infoArgs.ID);
logger.json(application2);
return;
}
const [application, err] = await wrap2(
ApplicationsService.getApplication(infoArgs.ID)
);
if (err) {
throw new UserError(
`There has been an internal error requesting your containers.
${err.message}`
);
}
const details = flatDetails(application);
const applicationDetails = {
label: `${application.name} (${application.created_at})`,
details,
value: application.id
};
await inputPrompt({
type: "list",
question: "Container",
options: [applicationDetails],
label: "Exiting"
});
}
function listYargs(args) {
return args;
}
async function listCommand(listArgs, config) {
if (isNonInteractiveOrCI()) {
const applications = await ApplicationsService.listApplications();
logger.json(applications);
return;
}
await listCommandHandle(listArgs, config);
}
function flatDetails(obj, indentLevel = 0) {
const indent = " ".repeat(indentLevel);
return Object.entries(obj).reduce((acc, [key, value]) => {
if (value !== void 0 && value !== null && typeof value === "object" && !Array.isArray(value)) {
acc.push(`${indent}${key}:`);
acc.push(
...flatDetails(value, indentLevel + 1)
);
} else if (value !== void 0) {
acc.push(`${indent}${key}: ${value}`);
}
return acc;
}, []);
}
async function listCommandHandle(_args, _config) {
const keepListIter = true;
while (keepListIter) {
logRaw(gray(shapes.bar));
const { start, stop } = spinner();
start("Loading Containers");
const [applications, err] = await wrap2(
ApplicationsService.listApplications()
);
stop();
if (err) {
throw new UserError(
`There has been an internal error listing your containers.
${err.message}`
);
}
if (applications === void 0 || applications === null || applications.length === 0) {
logRaw(
"No containers found. See https://dash.cloudflare.com/?to=/:account/workers/containers to learn more."
);
return;
}
const applicationDetails = /* @__PURE__ */ __name((a5) => {
const details = flatDetails(a5);
return {
label: `${a5.name} (${a5.created_at})`,
details,
value: a5.id
};
}, "applicationDetails");
const application = await listContainersAndChoose(applications);
let refresh = false;
await inputPrompt({
type: "list",
question: "Containers",
helpText: "Hit enter to return to your containers or 'r' to refresh",
options: [applicationDetails(application)],
label: "going back",
onRefresh: /* @__PURE__ */ __name(async () => {
start("Refreshing application");
const app = await ApplicationsService.getApplication(application.id);
if (refresh) {
return [];
}
stop();
if (app) {
const details = applicationDetails(app);
details.label += ", last refresh: " + (/* @__PURE__ */ new Date()).toLocaleString();
return [details];
}
return app;
}, "onRefresh")
});
refresh = true;
stop();
}
}
async function listContainersAndChoose(applications) {
const getLabels = /* @__PURE__ */ __name((a5) => {
const labels = a5.configuration.labels ?? [];
if (!labels || labels.length == 0) {
return [];
}
const out = labels.map((l6) => ` ${dim(l6.name)}: ${dim(l6.value)}`);
return `Labels:
` + out.join(",\n");
}, "getLabels");
const application = await processArgument({}, "applicationId", {
type: "list",
question: "Your Containers",
helpText: "Get more information by selecting a container with the enter/return key",
options: applications.map((i5) => ({
label: i5.name,
value: i5.id,
details: [
`Id: ${dim(`${i5.id}`)}`,
`Instances: ${dim(`${i5.instances}`)}`,
`Image: ${dim(i5.configuration.image)}`,
...getLabels(i5) ?? []
]
})),
label: "container"
});
return applications.find((a5) => a5.id === application);
}
var init_containers = __esm({
"src/containers/containers.ts"() {
init_import_meta_url();
init_cli();
init_args();
init_colors();
init_interactive();
init_containers_shared();
init_wrap();
init_errors();
init_is_interactive();
init_logger();
__name(deleteYargs, "deleteYargs");
__name(deleteCommand, "deleteCommand");
__name(infoYargs, "infoYargs");
__name(infoCommand, "infoCommand");
__name(listYargs, "listYargs");
__name(listCommand, "listCommand");
__name(flatDetails, "flatDetails");
__name(listCommandHandle, "listCommandHandle");
__name(listContainersAndChoose, "listContainersAndChoose");
}
});
// src/containers/index.ts
var containersScope, containers;
var init_containers2 = __esm({
"src/containers/index.ts"() {
init_import_meta_url();
init_build2();
init_common();
init_images2();
init_containers();
containersScope = "containers:write";
containers = /* @__PURE__ */ __name((yargs, subHelp) => {
return yargs.command(
"build [PATH]",
"Build a container image",
(args) => buildYargs(args),
(args) => handleFailure(
`wrangler containers build`,
buildCommand,
containersScope
)(args)
).command(
"push [TAG]",
"Push a tagged image to a Cloudflare managed registry",
(args) => pushYargs(args),
(args) => handleFailure(
`wrangler containers push`,
pushCommand,
containersScope
)(args)
).command(
"images",
"Perform operations on images in your Cloudflare managed registry",
(args) => imagesCommand(args, containersScope).command(subHelp)
).command(
"info [ID]",
"Get information about a specific container",
(args) => infoYargs(args),
(args) => handleFailure(
`wrangler containers info`,
infoCommand,
containersScope
)(args)
).command(
"list",
"List containers",
(args) => listYargs(args),
(args) => handleFailure(
`wrangler containers list`,
listCommand,
containersScope
)(args)
).command(
"delete [ID]",
"Delete a container",
(args) => deleteYargs(args),
(args) => handleFailure(
`wrangler containers delete`,
deleteCommand,
containersScope
)(args)
);
}, "containers");
}
});
// src/cloudchamber/helpers/diff.ts
function tokenize(value) {
const retLines = [];
const linesAndNewlines = value.split(/(\n|\r\n)/);
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
for (let i5 = 0; i5 < linesAndNewlines.length; i5++) {
const line = linesAndNewlines[i5];
retLines.push(line);
}
return retLines.filter((s5) => s5 !== "");
}
var Diff;
var init_diff = __esm({
"src/cloudchamber/helpers/diff.ts"() {
init_import_meta_url();
init_cli();
init_colors();
Diff = class {
static {
__name(this, "Diff");
}
#results = [];
get changes() {
return this.#results.filter((r7) => r7.added || r7.removed).length;
}
constructor(a5, b6) {
const oldString = tokenize(a5);
const newString = tokenize(b6);
const newLen = newString.length;
const oldLen = oldString.length;
let editLength = 1;
const bestPath = [
{ oldPos: -1, lastComponent: void 0 }
];
if (bestPath[0] === void 0) {
throw new Error("unreachable");
}
let newPos = this.#extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
this.#results = this.#buildValues(
bestPath[0].lastComponent,
newString,
oldString,
false
);
return;
}
let minDiagonalToConsider = -Infinity;
let maxDiagonalToConsider = Infinity;
let done = false;
while (!done) {
for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
let basePath;
const removePath = bestPath[diagonalPath - 1];
const 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 (addPath && (!canRemove || canAdd && (removePath?.oldPos ?? 0) < (addPath?.oldPos ?? 0))) {
basePath = this.#addToPath(addPath, true, false, 0);
} else if (removePath) {
basePath = this.#addToPath(removePath, false, true, 1);
} else {
throw new Error("unreachable");
}
newPos = this.#extractCommon(
basePath,
newString,
oldString,
diagonalPath
);
if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
this.#results = this.#buildValues(
basePath.lastComponent,
newString,
oldString,
false
);
done = true;
break;
}
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++;
}
}
toString(options = {
contextLines: 3
}) {
let output = "";
let state2 = "init";
const context2 = [];
for (const result of this.#results) {
if (result.value === void 0) {
continue;
}
if (result.added || result.removed) {
if (state2 === "diff") {
context2.splice(0, options.contextLines).filter(Boolean).forEach((c6) => {
output += ` ${c6}
`;
});
if (context2.length > options.contextLines) {
output += "\n ...\n\n";
}
}
context2.splice(0, context2.length - options.contextLines);
if (state2 === "init") {
while (context2.length > 0 && context2[0].trim() === "") {
context2.shift();
}
}
context2.filter(Boolean).forEach((c6) => {
output += ` ${c6}
`;
});
context2.length = 0;
for (const l6 of result.value.split("\n")) {
if (l6) {
output += `${result.added ? green("+") : red("-")} ${l6}
`;
}
}
state2 = "diff";
} else {
const lines = result.value.replace(/^\n|\n$/g, "").split("\n");
context2.push(...lines);
}
}
if (state2 === "diff") {
context2.splice(options.contextLines);
while (context2.length > 0 && context2[context2.length - 1].trim() === "") {
context2.pop();
}
context2.filter(Boolean).forEach((c6) => {
output += ` ${c6}
`;
});
}
return output.replace(/\n$/, "");
}
print(options = {
contextLines: 3
}) {
log(this.toString(options));
}
#addToPath(path72, added, removed, oldPosInc) {
const last = path72.lastComponent;
if (last && last.added === added && last.removed === removed) {
return {
oldPos: path72.oldPos + oldPosInc,
lastComponent: {
count: last.count + 1,
added,
removed,
previousComponent: last.previousComponent
}
};
}
return {
oldPos: path72.oldPos + oldPosInc,
lastComponent: {
count: 1,
added,
removed,
previousComponent: last
}
};
}
#extractCommon(basePath, newString, oldString, diagonalPath) {
const newLen = newString.length;
const oldLen = oldString.length;
let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && oldString[oldPos + 1] === newString[newPos + 1]) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.lastComponent = {
count: commonCount,
previousComponent: basePath.lastComponent,
added: false,
removed: false
};
}
basePath.oldPos = oldPos;
return newPos;
}
#buildValues(lastComponent, newString, oldString, useLongestToken) {
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 && useLongestToken) {
let value = newString.slice(newPos, newPos + component.count);
value = value.map((el, i5) => {
const oldValue = oldString[oldPos + i5];
return oldValue.length > el.length ? oldValue : el;
});
component.value = value.join("");
} else {
component.value = newString.slice(newPos, newPos + component.count).join("");
}
newPos += component.count;
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = oldString.slice(oldPos, oldPos + component.count).join("");
oldPos += component.count;
}
}
return components;
}
};
__name(tokenize, "tokenize");
}
});
// src/utils/sortObjectRecursive.ts
function stripUndefined(r7) {
for (const k6 in r7) {
if (r7[k6] === void 0) {
delete r7[k6];
}
}
return r7;
}
function sortObjectKeys(unordered) {
if (Array.isArray(unordered)) {
return unordered;
}
return Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
}
function sortObjectRecursive(object) {
if (typeof object !== "object") {
return object;
}
if (Array.isArray(object)) {
return object.map((obj) => sortObjectRecursive(obj));
}
const objectCopy = { ...object };
for (const [key, value] of Object.entries(object)) {
if (typeof value === "object") {
if (value === null) {
continue;
}
objectCopy[key] = sortObjectRecursive(
value
);
}
}
return sortObjectKeys(objectCopy);
}
var init_sortObjectRecursive = __esm({
"src/utils/sortObjectRecursive.ts"() {
init_import_meta_url();
__name(stripUndefined, "stripUndefined");
__name(sortObjectKeys, "sortObjectKeys");
__name(sortObjectRecursive, "sortObjectRecursive");
}
});
// src/containers/deploy.ts
function mergeDeep2(target, source) {
if (typeof target !== "object" || target === null) {
return source;
}
if (typeof source !== "object" || source === null) {
return target;
}
const result = { ...target };
for (const key of Object.keys(source)) {
const srcVal = source[key];
const tgtVal = target[key];
if (isObject(tgtVal) && isObject(srcVal)) {
result[key] = mergeDeep2(tgtVal, srcVal);
} else {
result[key] = srcVal;
}
}
return result;
}
function isObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function createApplicationToModifyApplication(req) {
return {
configuration: req.configuration,
max_instances: req.max_instances,
constraints: req.constraints,
affinities: req.affinities,
scheduling_policy: req.scheduling_policy,
rollout_active_grace_period: req.rollout_active_grace_period
};
}
function cleanupObservability(observability) {
if (observability === void 0) {
return;
}
if (observability.logging !== void 0 && observability.logs !== void 0) {
delete observability.logging;
}
}
function observabilityToConfiguration(observabilityFromConfig, existingObservabilityConfig) {
const logsAlreadyEnabled = existingObservabilityConfig?.logs?.enabled;
if (observabilityFromConfig) {
return { logs: { enabled: true } };
} else if (logsAlreadyEnabled === void 0) {
return void 0;
} else {
return { logs: { enabled: false } };
}
}
function containerConfigToCreateRequest(accountId, containerApp, imageRef, durableObjectNamespaceId, prevApp) {
return {
name: containerApp.name,
scheduling_policy: containerApp.scheduling_policy,
configuration: {
// De-sugar image name
image: resolveImageName(accountId, imageRef),
// if disk/memory/vcpu is not defined in config, AND instance_type is also not defined, this will already have been defaulted to 'dev'
..."instance_type" in containerApp ? { instance_type: containerApp.instance_type } : {
disk: { size_mb: containerApp.disk_bytes / (1e3 * 1e3) },
memory_mib: containerApp.memory_mib,
vcpu: containerApp.vcpu
},
observability: observabilityToConfiguration(
containerApp.observability.logs_enabled,
prevApp?.configuration.observability
)
},
// deprecated in favour of max_instances
instances: 0,
max_instances: containerApp.max_instances,
constraints: containerApp.constraints,
durable_objects: {
namespace_id: durableObjectNamespaceId
},
rollout_active_grace_period: containerApp.rollout_active_grace_period
};
}
async function apply(args, containerConfig, config) {
if (!config.containers || config.containers.length === 0) {
return;
}
startSection(
"Deploy a container application",
"deploy changes to your application"
);
const existingApplications = await promiseSpinner(
ApplicationsService.listApplications(),
{ message: "Loading applications" }
);
existingApplications.forEach(
(app) => cleanupObservability(app.configuration.observability)
);
const prevApp = existingApplications.find(
(app) => app.name === containerConfig.name
);
const imageRef = "remoteDigest" in args.imageRef ? prevApp?.configuration.image ?? args.imageRef.remoteDigest : args.imageRef.newTag;
log(dim("Container application changes\n"));
const accountId = config.account_id || await getAccountId(config);
const appConfig = containerConfigToCreateRequest(
accountId,
containerConfig,
imageRef,
args.durable_object_namespace_id,
prevApp
);
if (prevApp !== void 0 && prevApp !== null) {
if (!prevApp.durable_objects?.namespace_id) {
throw new FatalError(
"The previous deploy of this container application was not associated with a durable object"
);
}
if (prevApp.durable_objects.namespace_id !== args.durable_object_namespace_id) {
throw new UserError(
`Application "${prevApp.name}" is assigned to durable object ${prevApp.durable_objects.namespace_id}, but a new DO namespace is being assigned to the application,
you should delete the container application and deploy again`,
{
telemetryMessage: "trying to redeploy container to different durable object"
}
);
}
const normalisedPrevApp = sortObjectRecursive(
stripUndefined(
cleanApplicationFromAPI(prevApp, containerConfig, accountId)
)
);
const modifyReq = createApplicationToModifyApplication(appConfig);
const nowContainer = mergeDeep2(
normalisedPrevApp,
sortObjectRecursive(modifyReq)
);
const prev = formatConfigSnippet(
// note this really is a CreateApplicationRequest, not a ContainerApp
// but this function doesn't actually care about the type
{ containers: [normalisedPrevApp] },
config.configPath
);
const now = formatConfigSnippet(
{ containers: [nowContainer] },
config.configPath
);
const diff = new Diff(prev, now);
if (diff.changes === 0) {
updateStatus(`no changes ${brandColor(prevApp.name)}`);
endSection("No changes to be made");
return;
}
updateStatus(`${brandColor.underline("EDIT")} ${prevApp.name}`, false);
newline();
diff.print();
newline();
if (containerConfig.rollout_kind !== "none") {
await doAction({
action: "modify",
application: modifyReq,
id: prevApp.id,
name: prevApp.name,
rollout_step_percentage: containerConfig.rollout_step_percentage,
rollout_kind: containerConfig.rollout_kind == "full_manual" ? CreateApplicationRolloutRequest.kind.FULL_MANUAL : CreateApplicationRolloutRequest.kind.FULL_AUTO
});
} else {
log("Skipping application rollout");
newline();
}
} else {
updateStatus(bold.underline(green.underline("NEW")) + ` ${appConfig.name}`);
const configStr = formatConfigSnippet(
{ containers: [appConfig] },
config.configPath
);
configStr.trimEnd().split("\n").forEach((el) => log(` ${el}`));
newline();
await doAction({
action: "create",
application: appConfig
});
}
newline();
endSection("Applied changes");
}
function formatError(err) {
try {
const maybeError = JSON.parse(err.body.error);
if (maybeError.error !== void 0 && maybeError.details !== void 0 && typeof maybeError.details === "object") {
let message = "";
for (const key in maybeError.details) {
message += `${brandColor(key)} ${maybeError.details[key]}
`;
}
return message;
}
} catch {
}
return JSON.stringify(err.body);
}
function cleanApplicationFromAPI(prev, currentConfig, accountId) {
const cleanedPreviousApp = {
configuration: {
...prev.configuration,
image: resolveImageName(accountId, prev.configuration.image)
},
constraints: prev.constraints,
max_instances: prev.max_instances,
name: prev.name,
scheduling_policy: prev.scheduling_policy,
affinities: prev.affinities,
rollout_active_grace_period: prev.rollout_active_grace_period
};
if ("instance_type" in currentConfig) {
const instance_type = inferInstanceType(cleanedPreviousApp.configuration);
if (!instance_type) {
return prev;
}
cleanedPreviousApp.configuration.instance_type = instance_type;
delete cleanedPreviousApp.configuration.disk;
delete cleanedPreviousApp.configuration.memory;
delete cleanedPreviousApp.configuration.memory_mib;
delete cleanedPreviousApp.configuration.vcpu;
}
return cleanedPreviousApp;
}
var doAction, configRolloutStepsToAPI;
var init_deploy = __esm({
"src/containers/deploy.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_containers_shared();
init_common();
init_diff();
init_instance_type();
init_config2();
init_errors();
init_user2();
init_sortObjectRecursive();
__name(mergeDeep2, "mergeDeep");
__name(isObject, "isObject");
__name(createApplicationToModifyApplication, "createApplicationToModifyApplication");
__name(cleanupObservability, "cleanupObservability");
__name(observabilityToConfiguration, "observabilityToConfiguration");
__name(containerConfigToCreateRequest, "containerConfigToCreateRequest");
__name(apply, "apply");
__name(formatError, "formatError");
doAction = /* @__PURE__ */ __name(async (action) => {
if (action.action === "create") {
let application;
try {
application = await promiseSpinner(
ApplicationsService.createApplication(action.application),
{ message: `Creating "${action.application.name}"` }
);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (!(err instanceof ApiError)) {
throw new FatalError(
`Unexpected error creating application: ${err.message}`
);
}
if (err.status === 400) {
throw new UserError(
`Error creating application due to a misconfiguration:
${formatError(err)}`
);
}
throw new UserError(`Error creating application:
${formatError(err)}`);
}
success(
`Created application ${brandColor(action.application.name)} (Application ID: ${application.id})`,
{
shape: shapes.bar
}
);
}
if (action.action === "modify") {
try {
await promiseSpinner(
ApplicationsService.modifyApplication(action.id, action.application),
{ message: `Modifying ${action.application.name}` }
);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (!(err instanceof ApiError)) {
throw new UserError(
`Unexpected error modifying application "${action.name}": ${err.message}`
);
}
if (err.status === 400) {
throw new UserError(
`Error modifying application "${action.name}" due to a misconfiguration:
${formatError(err)}`
);
}
throw new UserError(
`Error modifying application "${action.name}":
${formatError(err)}`
);
}
try {
await promiseSpinner(
RolloutsService.createApplicationRollout(action.id, {
description: "Progressive update",
strategy: CreateApplicationRolloutRequest.strategy.ROLLING,
target_configuration: action.application.configuration ?? {},
...configRolloutStepsToAPI(action.rollout_step_percentage),
kind: action.rollout_kind
}),
{
message: `rolling out container version ${action.name}`
}
);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (!(err instanceof ApiError)) {
throw new UserError(
`Unexpected error rolling out application "${action.name}":
${err.message}`
);
}
if (err.status === 400) {
throw new UserError(
`Error rolling out application "${action.name}" due to a misconfiguration:
${formatError(err)}`
);
}
throw new UserError(
`Error rolling out application "${action.name}":
${formatError(err)}`
);
}
success(
`Modified application ${brandColor(action.name)} (Application ID: ${action.id})`,
{
shape: shapes.bar
}
);
}
}, "doAction");
__name(cleanApplicationFromAPI, "cleanApplicationFromAPI");
configRolloutStepsToAPI = /* @__PURE__ */ __name((rolloutSteps) => {
if (typeof rolloutSteps === "number") {
return { step_percentage: rolloutSteps };
} else {
const output = [];
let index = 1;
for (const step of rolloutSteps) {
output.push({
step_size: { percentage: step },
description: `Step ${index} of ${rolloutSteps.length} - rollout at ${step}% of instances`
});
index++;
}
return { steps: output };
}
}, "configRolloutStepsToAPI");
}
});
// src/versions/api.ts
async function fetchVersion(complianceConfig, accountId, workerName, versionId, versionCache) {
const cachedVersion = versionCache?.get(versionId);
if (cachedVersion) {
return cachedVersion;
}
const version5 = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${workerName}/versions/${versionId}`
);
versionCache?.set(version5.id, version5);
return version5;
}
async function fetchVersions(complianceConfig, accountId, workerName, versionCache, ...versionIds) {
return Promise.all(
versionIds.map(
(versionId) => fetchVersion(
complianceConfig,
accountId,
workerName,
versionId,
versionCache
)
)
);
}
async function fetchLatestDeployments(complianceConfig, accountId, workerName) {
const { deployments } = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${workerName}/deployments`
);
return deployments;
}
async function fetchLatestDeployment(complianceConfig, accountId, workerName) {
const deployments = await fetchLatestDeployments(
complianceConfig,
accountId,
workerName
);
return deployments.at(0);
}
async function fetchDeploymentVersions(complianceConfig, accountId, workerName, deployment, versionCache) {
if (!deployment) {
return [[], /* @__PURE__ */ new Map()];
}
const versionTraffic = new Map(
deployment.versions.map((v7) => [v7.version_id, v7.percentage])
);
const versions2 = await fetchVersions(
complianceConfig,
accountId,
workerName,
versionCache,
...versionTraffic.keys()
);
return [versions2, versionTraffic];
}
async function fetchDeployableVersions(complianceConfig, accountId, workerName, versionCache) {
const { items: versions2 } = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${workerName}/versions?deployable=true`
);
for (const version5 of versions2) {
versionCache.set(version5.id, version5);
}
return versions2;
}
async function createDeployment(complianceConfig, accountId, workerName, versionTraffic, message, force) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${workerName}/deployments${force ? "?force=true" : ""}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
strategy: "percentage",
versions: Array.from(versionTraffic).map(
([version_id, percentage]) => ({ version_id, percentage })
),
annotations: {
"workers/message": message
}
})
}
);
}
async function patchNonVersionedScriptSettings(complianceConfig, accountId, workerName, settings) {
const res = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${workerName}/script-settings`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings)
}
);
return res;
}
var init_api = __esm({
"src/versions/api.ts"() {
init_import_meta_url();
init_cfetch();
__name(fetchVersion, "fetchVersion");
__name(fetchVersions, "fetchVersions");
__name(fetchLatestDeployments, "fetchLatestDeployments");
__name(fetchLatestDeployment, "fetchLatestDeployment");
__name(fetchDeploymentVersions, "fetchDeploymentVersions");
__name(fetchDeployableVersions, "fetchDeployableVersions");
__name(createDeployment, "createDeployment");
__name(patchNonVersionedScriptSettings, "patchNonVersionedScriptSettings");
}
});
// src/cloudchamber/deploy.ts
async function buildContainer(containerConfig, imageTag, dryRun, pathToDocker) {
const imageFullName = containerConfig.name + ":" + imageTag.split("-")[0];
logger.log("Building image", imageFullName);
return await buildAndMaybePush(
{
tag: imageFullName,
pathToDockerfile: containerConfig.dockerfile,
buildContext: containerConfig.image_build_context,
args: containerConfig.image_vars
},
pathToDocker,
!dryRun,
containerConfig
);
}
async function deployContainers(config, normalisedContainerConfig, { versionId, accountId, scriptName }) {
await fillOpenAPIConfiguration(config, containersScope);
const pathToDocker = getDockerPath();
const version5 = await fetchVersion(config, accountId, scriptName, versionId);
let imageRef;
for (const container of normalisedContainerConfig) {
if ("dockerfile" in container) {
imageRef = await buildContainer(
container,
versionId,
false,
pathToDocker
);
} else {
imageRef = { newTag: container.image_uri };
}
const targetDurableObject = version5.resources.bindings.find(
(durableObject) => durableObject.type === "durable_object_namespace" && durableObject.class_name === container.class_name && // DO cannot be defined in a different script to the container
durableObject.script_name === void 0 && durableObject.namespace_id !== void 0
);
if (!targetDurableObject) {
throw new UserError(
"Could not deploy container application as durable object was not found in list of bindings"
);
}
(0, import_assert3.default)(
targetDurableObject.type === "durable_object_namespace" && targetDurableObject.namespace_id !== void 0
);
await apply(
{
imageRef,
durable_object_namespace_id: targetDurableObject.namespace_id
},
container,
config
);
}
}
var import_assert3;
var init_deploy2 = __esm({
"src/cloudchamber/deploy.ts"() {
init_import_meta_url();
import_assert3 = __toESM(require("assert"));
init_containers2();
init_deploy();
init_misc_variables();
init_errors();
init_logger();
init_api();
init_build2();
init_common();
__name(buildContainer, "buildContainer");
__name(deployContainers, "deployContainers");
}
});
// src/containers/config.ts
var import_node_assert12, import_node_path23, getNormalizedContainerOptions;
var init_config3 = __esm({
"src/containers/config.ts"() {
init_import_meta_url();
import_node_assert12 = __toESM(require("assert"));
import_node_path23 = __toESM(require("path"));
init_containers_shared();
init_errors();
init_user2();
getNormalizedContainerOptions = /* @__PURE__ */ __name(async (config, args) => {
if (!config.containers || config.containers.length === 0) {
return [];
}
const normalizedContainers = [];
for (const container of config.containers) {
(0, import_node_assert12.default)(container.name, "container name should have been set by validation");
const targetDurableObject = config.durable_objects.bindings.find(
(durableObject) => durableObject.class_name === container.class_name
);
if (!targetDurableObject) {
throw new UserError(
`The container class_name ${container.class_name} does not match any durable object class_name defined in your Wrangler config file. Note that the durable object must be defined in the same script as the container.`,
{ telemetryMessage: "no DO defined that matches container class_name" }
);
}
if (targetDurableObject.script_name !== void 0) {
throw new UserError(
`The container ${container.name} is referencing the durable object ${container.class_name}, which appears to be defined on the ${targetDurableObject.script_name} Worker instead (via the 'script_name' field). You cannot configure a container on a Durable Object that is defined in another Worker.`,
{
telemetryMessage: "contaienr class_name refers to an external durable object"
}
);
}
const rolloutStepPercentageFallback = (container.max_instances ?? 0) < 2 ? 100 : [10, 100];
const shared = {
name: container.name,
class_name: container.class_name,
max_instances: container.max_instances ?? 0,
scheduling_policy: container.scheduling_policy ?? "default" /* DEFAULT */,
constraints: {
// if the tier is -1, then we allow all tiers
// Wrangler will default an input value to 1. The API, however, will
// treat an undefined value to mean no constraints on tier (i.e. "all tiers")
tier: container.constraints?.tier === -1 ? void 0 : container.constraints?.tier ?? 1,
regions: container.constraints?.regions?.map(
(region) => region.toUpperCase()
),
cities: container.constraints?.cities?.map(
(city) => city.toLowerCase()
)
},
rollout_step_percentage: args?.containersRollout === "immediate" ? 100 : container.rollout_step_percentage ?? rolloutStepPercentageFallback,
rollout_kind: container.rollout_kind ?? "full_auto",
rollout_active_grace_period: container.rollout_active_grace_period ?? 0,
observability: {
logs_enabled: config.observability?.logs?.enabled ?? config.observability?.enabled === true
}
};
let instanceTypeOrLimits;
const MB2 = 1e3 * 1e3;
if (container.configuration?.disk !== void 0 || container.configuration?.vcpu !== void 0 || container.configuration?.memory_mib !== void 0) {
instanceTypeOrLimits = {
disk_bytes: (container.configuration?.disk?.size_mb ?? 2e3) * MB2,
// defaults to 2GB in bytes
vcpu: container.configuration?.vcpu ?? 0.0625,
memory_mib: container.configuration?.memory_mib ?? 256
};
} else if (typeof container.instance_type === "string" || container.instance_type === void 0) {
instanceTypeOrLimits = {
instance_type: container.instance_type ?? "dev" /* DEV */
};
} else {
instanceTypeOrLimits = {
disk_bytes: (container.instance_type.disk_mb ?? 2e3) * MB2,
vcpu: container.instance_type.vcpu ?? 0.0625,
memory_mib: container.instance_type.memory_mib ?? 256
};
}
const maybeDockerfile = isDockerfile(container.image, config.configPath);
if (maybeDockerfile) {
(0, import_node_assert12.default)(
import_node_path23.default.isAbsolute(container.image),
"Dockerfile path should be absolute"
);
const imageBuildContext = container.image_build_context ?? (0, import_node_path23.dirname)(container.image);
(0, import_node_assert12.default)(
import_node_path23.default.isAbsolute(imageBuildContext),
"resolved image_build_context should be defined"
);
normalizedContainers.push({
...shared,
...instanceTypeOrLimits,
dockerfile: container.image,
image_build_context: imageBuildContext,
image_vars: container.image_vars
});
} else {
const accountId = await getAccountId(config);
normalizedContainers.push({
...shared,
...instanceTypeOrLimits,
image_uri: resolveImageName(accountId, container.image)
// if it is not a dockerfile, it must be an image uri or have thrown an error
});
}
}
return normalizedContainers;
}, "getNormalizedContainerOptions");
}
});
// src/core/create-command.ts
function createCommand(definition) {
return definition;
}
function createNamespace(definition) {
return definition;
}
function createAlias(definition) {
return definition;
}
var init_create_command = __esm({
"src/core/create-command.ts"() {
init_import_meta_url();
__name(createCommand, "createCommand");
__name(createNamespace, "createNamespace");
__name(createAlias, "createAlias");
}
});
// src/utils/getValidBindingName.ts
function getValidBindingName(name2, fallback) {
let bindingName = name2.replace(/[\s-]/g, "_");
bindingName = bindingName.replace(/[^a-zA-Z0-9_]/g, "");
bindingName = bindingName.replace(/_+/g, "_");
if (/^[0-9]/.test(bindingName)) {
bindingName = "_" + bindingName;
}
if (!bindingName.length || /^_+$/.test(bindingName)) {
return fallback;
}
return bindingName;
}
var init_getValidBindingName = __esm({
"src/utils/getValidBindingName.ts"() {
init_import_meta_url();
__name(getValidBindingName, "getValidBindingName");
}
});
// src/d1/constants.ts
var DEFAULT_MIGRATION_PATH, DEFAULT_MIGRATION_TABLE, LOCATION_CHOICES;
var init_constants4 = __esm({
"src/d1/constants.ts"() {
init_import_meta_url();
DEFAULT_MIGRATION_PATH = "./migrations";
DEFAULT_MIGRATION_TABLE = "d1_migrations";
LOCATION_CHOICES = ["weur", "eeur", "apac", "oc", "wnam", "enam"];
}
});
// src/d1/create.ts
async function createD1Database(complianceConfig, accountId, name2, location) {
try {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: name2,
...location && { primary_location_hint: location }
})
}
);
} catch (e7) {
if (e7.code === 7502) {
throw new UserError("A database with that name already exists");
}
throw e7;
}
}
var d1CreateCommand;
var init_create = __esm({
"src/d1/create.ts"() {
init_import_meta_url();
init_esm2();
init_cfetch();
init_config2();
init_create_command();
init_misc_variables();
init_errors();
init_logger();
init_user2();
init_getValidBindingName();
init_constants4();
__name(createD1Database, "createD1Database");
d1CreateCommand = createCommand({
metadata: {
description: "Create D1 database",
status: "stable",
owner: "Product: D1"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the new DB"
},
location: {
type: "string",
choices: [
...LOCATION_CHOICES,
...getD1ExtraLocationChoices()?.split(",") ?? []
],
description: esm_default2`
A hint for the primary location of the new DB. Options:
weur: Western Europe
eeur: Eastern Europe
apac: Asia Pacific
oc: Oceania
wnam: Western North America
enam: Eastern North America
`
}
},
positionalArgs: ["name"],
async handler({ name: name2, location, env: env6 }, { config }) {
const accountId = await requireAuth(config);
const db = await createD1Database(config, accountId, name2, location);
logger.log(
`\u2705 Successfully created DB '${db.name}'${db.created_in_region ? ` in region ${db.created_in_region}` : location ? ` using primary location hint ${location}` : ``}`
);
logger.log("Created your new D1 database.\n");
await updateConfigFile(
(bindingName) => ({
d1_databases: [
{
binding: getValidBindingName(bindingName ?? db.name, "DB"),
database_name: db.name,
database_id: db.uuid
}
]
}),
config.configPath,
env6
);
}
});
}
});
// src/d1/list.ts
var d1ListCommand, listDatabases;
var init_list = __esm({
"src/d1/list.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
d1ListCommand = createCommand({
metadata: {
description: "List D1 databases",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
async handler({ json }, { config }) {
const accountId = await requireAuth(config);
const dbs = await listDatabases(config, accountId);
if (json) {
logger.log(JSON.stringify(dbs, null, 2));
} else {
logger.table(
dbs.map(
(db) => Object.fromEntries(
Object.entries(db).map(([k6, v7]) => [k6, String(v7 ?? "")])
)
)
);
}
}
});
listDatabases = /* @__PURE__ */ __name(async (complianceConfig, accountId, limitCalls = false, pageSize = 10) => {
let page = 1;
const results = [];
while (results.length % pageSize === 0) {
const json = await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database`,
{},
new URLSearchParams({
per_page: pageSize.toString(),
page: page.toString()
})
);
page++;
results.push(...json);
if (limitCalls && page > 3) {
break;
}
if (json.length < pageSize) {
break;
}
}
return results;
}, "listDatabases");
}
});
// src/d1/utils.ts
function getDatabaseInfoFromConfig(config, name2) {
for (const d1Database of config.d1_databases) {
if (d1Database.database_id && (name2 === d1Database.database_name || name2 === d1Database.binding)) {
if (!d1Database.database_name) {
throw new UserError(
`${name2} bindings must have a "database_name" field`
);
}
return {
uuid: d1Database.database_id,
previewDatabaseUuid: d1Database.preview_database_id,
binding: d1Database.binding,
name: d1Database.database_name,
migrationsTableName: d1Database.migrations_table || DEFAULT_MIGRATION_TABLE,
migrationsFolderPath: d1Database.migrations_dir || DEFAULT_MIGRATION_PATH,
internal_env: d1Database.database_internal_env
};
}
}
return null;
}
var getDatabaseByNameOrBinding, getDatabaseInfoFromIdOrName;
var init_utils3 = __esm({
"src/d1/utils.ts"() {
init_import_meta_url();
init_cfetch();
init_errors();
init_constants4();
init_list();
__name(getDatabaseInfoFromConfig, "getDatabaseInfoFromConfig");
getDatabaseByNameOrBinding = /* @__PURE__ */ __name(async (config, accountId, name2) => {
const dbFromConfig = getDatabaseInfoFromConfig(config, name2);
if (dbFromConfig) {
return dbFromConfig;
}
const allDBs = await listDatabases(config, accountId);
const matchingDB = allDBs.find((db) => db.name === name2);
if (!matchingDB) {
throw new UserError(`Couldn't find DB with name '${name2}'`);
}
return matchingDB;
}, "getDatabaseByNameOrBinding");
getDatabaseInfoFromIdOrName = /* @__PURE__ */ __name(async (complianceConfig, accountId, databaseIdOrName) => {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database/${databaseIdOrName}`,
{
headers: {
"Content-Type": "application/json"
}
}
);
}, "getDatabaseInfoFromIdOrName");
}
});
// src/kv/helpers.ts
async function createKVNamespace(complianceConfig, accountId, title) {
const response = await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title
})
}
);
return response.id;
}
async function listKVNamespaces(complianceConfig, accountId, limitCalls = false) {
const pageSize = 100;
let page = 1;
const results = [];
while (results.length % pageSize === 0) {
const json = await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces`,
{},
new import_node_url8.URLSearchParams({
per_page: pageSize.toString(),
order: "title",
direction: "asc",
page: page.toString()
})
);
page++;
results.push(...json);
if (limitCalls) {
break;
}
if (json.length < pageSize) {
break;
}
}
return results;
}
async function listKVNamespaceKeys(complianceConfig, accountId, namespaceId, prefix = "") {
return await fetchListResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
{},
new import_node_url8.URLSearchParams({ prefix })
);
}
async function updateKVNamespace(complianceConfig, accountId, namespaceId, title) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title
})
}
);
}
async function deleteKVNamespace(complianceConfig, accountId, namespaceId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}`,
{ method: "DELETE" }
);
}
function hasProperty2(obj, property) {
return property in obj;
}
function hasTypedProperty(obj, property, type) {
return hasProperty2(obj, property) && typeof obj[property] === type;
}
function hasOptionalTypedProperty(obj, property, type) {
return !hasProperty2(obj, property) || typeof obj[property] === type;
}
function isKVKeyValue(keyValue) {
if (keyValue === null || typeof keyValue !== "object" || !hasTypedProperty(keyValue, "key", "string") || !hasTypedProperty(keyValue, "value", "string") || !hasOptionalTypedProperty(keyValue, "expiration", "number") || !hasOptionalTypedProperty(keyValue, "expiration_ttl", "number") || !hasOptionalTypedProperty(keyValue, "base64", "boolean") || !hasOptionalTypedProperty(keyValue, "metadata", "object")) {
return false;
}
return true;
}
function unexpectedKVKeyValueProps(keyValue) {
const props = Object.keys(keyValue);
return props.filter((prop) => !KeyValueKeys.has(prop));
}
function asFormData(fields) {
const formData = new import_undici4.FormData();
for (const [name2, value] of Object.entries(fields)) {
formData.append(name2, Buffer.isBuffer(value) ? new import_node_buffer2.Blob([value]) : value);
}
return formData;
}
async function putKVKeyValue(complianceConfig, accountId, namespaceId, keyValue) {
let searchParams;
if (keyValue.expiration || keyValue.expiration_ttl) {
searchParams = new import_node_url8.URLSearchParams();
if (keyValue.expiration) {
searchParams.set("expiration", `${keyValue.expiration}`);
}
if (keyValue.expiration_ttl) {
searchParams.set("expiration_ttl", `${keyValue.expiration_ttl}`);
}
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(
keyValue.key
)}`,
{
method: "PUT",
body: keyValue.metadata ? asFormData({
value: keyValue.value,
metadata: JSON.stringify(keyValue.metadata)
}) : keyValue.value
},
searchParams
);
}
async function getKVKeyValue(complianceConfig, accountId, namespaceId, key) {
return await fetchKVGetValue(
complianceConfig,
accountId,
namespaceId,
encodeURIComponent(key)
);
}
async function deleteKVKeyValue(complianceConfig, accountId, namespaceId, key) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(
key
)}`,
{ method: "DELETE" }
);
}
function logBulkProgress(operation, index, total) {
logger.log(
`${operation === "put" ? "Uploaded" : "Deleted"} ${Math.floor(
100 * index / total
)}% (${formatNumber(index)} out of ${formatNumber(total)})`
);
}
async function getKVBulkKeyValue(complianceConfig, accountId, namespaceId, keys) {
const requestPayload = { keys };
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk/get`,
{
method: "POST",
body: JSON.stringify(requestPayload),
headers: { "Content-Type": "application/json" }
}
);
return result.values;
}
async function putKVBulkKeyValue(complianceConfig, accountId, namespaceId, keyValues, quiet = false, abortSignal) {
for (let index = 0; index < keyValues.length; index += BATCH_KEY_MAX) {
if (!quiet && keyValues.length > BATCH_KEY_MAX) {
logBulkProgress("put", index, keyValues.length);
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
{
method: "PUT",
body: JSON.stringify(keyValues.slice(index, index + BATCH_KEY_MAX)),
headers: { "Content-Type": "application/json" }
},
void 0,
abortSignal
);
}
if (!quiet && keyValues.length > BATCH_KEY_MAX) {
logBulkProgress("put", keyValues.length, keyValues.length);
}
}
async function deleteKVBulkKeyValue(complianceConfig, accountId, namespaceId, keys, quiet = false) {
for (let index = 0; index < keys.length; index += BATCH_KEY_MAX) {
if (!quiet && keys.length > BATCH_KEY_MAX) {
logBulkProgress("delete", index, keys.length);
}
await fetchResult(
complianceConfig,
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
{
method: "DELETE",
body: JSON.stringify(keys.slice(index, index + BATCH_KEY_MAX)),
headers: { "Content-Type": "application/json" }
}
);
}
if (!quiet && keys.length > BATCH_KEY_MAX) {
logBulkProgress("delete", keys.length, keys.length);
}
}
function getKVNamespaceId({ preview, binding, "namespace-id": namespaceId }, config) {
if (namespaceId) {
return namespaceId;
}
if (binding && !config) {
throw new UserError("--binding specified, but no config file was found.");
}
if (!config) {
throw new UserError(
"Failed to find a config file.\nEither use --namespace-id to upload directly or create a configuration file with a binding."
);
}
if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
throw new UserError(
"No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
);
}
const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
if (!namespace) {
throw new UserError(
`A namespace with binding name "${binding}" was not found in the configured "kv_namespaces".`
);
}
if (preview && namespace.preview_id) {
namespaceId = namespace.preview_id;
return namespaceId;
} else if (preview) {
throw new UserError(
`No preview ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
);
}
const previewIsDefined = typeof preview !== "undefined";
if (previewIsDefined && namespace.id) {
namespaceId = namespace.id;
return namespaceId;
} else if (previewIsDefined) {
throw new UserError(
`No namespace ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
);
}
const bindingHasOnlyOneId = namespace.id && !namespace.preview_id || !namespace.id && namespace.preview_id;
if (bindingHasOnlyOneId) {
namespaceId = namespace.id || namespace.preview_id;
} else {
throw new UserError(
`${binding} has both a namespace ID and a preview ID. Specify "--preview" or "--preview false" to avoid writing data to the wrong namespace.`
);
}
if (!namespaceId) {
throw new Error(
"Something went wrong trying to determine which namespace to upload to.\nPlease create a github issue with the command you just ran along with your wrangler configuration."
);
}
return namespaceId;
}
async function usingLocalNamespace(persistTo, config, namespaceId, closure) {
const persist = getLocalPersistencePath(persistTo, config);
const defaultPersistRoot = getDefaultPersistRoot(persist);
const mf = new import_miniflare9.Miniflare({
script: 'addEventListener("fetch", (e) => e.respondWith(new Response(null, { status: 404 })))',
defaultPersistRoot,
kvNamespaces: { NAMESPACE: namespaceId }
});
const namespace = await mf.getKVNamespace("NAMESPACE");
try {
return await closure(namespace);
} finally {
await mf.dispose();
}
}
var import_node_buffer2, import_node_url8, import_miniflare9, import_undici4, API_MAX, BATCH_KEY_MAX, BATCH_MAX_ERRORS_WARNINGS, KeyValueKeys, formatNumber;
var init_helpers4 = __esm({
"src/kv/helpers.ts"() {
init_import_meta_url();
import_node_buffer2 = require("buffer");
import_node_url8 = require("url");
import_miniflare9 = require("miniflare");
import_undici4 = __toESM(require_undici());
init_cfetch();
init_get_local_persistence_path();
init_miniflare();
init_errors();
init_logger();
API_MAX = 1e4;
BATCH_KEY_MAX = API_MAX / 10;
BATCH_MAX_ERRORS_WARNINGS = 12;
__name(createKVNamespace, "createKVNamespace");
__name(listKVNamespaces, "listKVNamespaces");
__name(listKVNamespaceKeys, "listKVNamespaceKeys");
__name(updateKVNamespace, "updateKVNamespace");
__name(deleteKVNamespace, "deleteKVNamespace");
KeyValueKeys = /* @__PURE__ */ new Set([
"key",
"value",
"expiration",
"expiration_ttl",
"metadata",
"base64"
]);
__name(hasProperty2, "hasProperty");
__name(hasTypedProperty, "hasTypedProperty");
__name(hasOptionalTypedProperty, "hasOptionalTypedProperty");
__name(isKVKeyValue, "isKVKeyValue");
__name(unexpectedKVKeyValueProps, "unexpectedKVKeyValueProps");
__name(asFormData, "asFormData");
__name(putKVKeyValue, "putKVKeyValue");
__name(getKVKeyValue, "getKVKeyValue");
__name(deleteKVKeyValue, "deleteKVKeyValue");
formatNumber = new Intl.NumberFormat("en-US", {
notation: "standard"
}).format;
__name(logBulkProgress, "logBulkProgress");
__name(getKVBulkKeyValue, "getKVBulkKeyValue");
__name(putKVBulkKeyValue, "putKVBulkKeyValue");
__name(deleteKVBulkKeyValue, "deleteKVBulkKeyValue");
__name(getKVNamespaceId, "getKVNamespaceId");
__name(usingLocalNamespace, "usingLocalNamespace");
}
});
// src/package-manager.ts
async function getPackageManager() {
const [hasYarn, hasNpm, hasPnpm] = await Promise.all([
supportsYarn(),
supportsNpm(),
supportsPnpm()
]);
const userAgent = sniffUserAgent();
if (userAgent === "npm" && hasNpm) {
logger.log("Using npm as package manager.");
return { ...NpmPackageManager };
} else if (userAgent === "pnpm" && hasPnpm) {
logger.log("Using pnpm as package manager.");
return { ...PnpmPackageManager };
} else if (userAgent === "yarn" && hasYarn) {
logger.log("Using yarn as package manager.");
return { ...YarnPackageManager };
}
if (hasNpm) {
logger.log("Using npm as package manager.");
return { ...NpmPackageManager };
} else if (hasYarn) {
logger.log("Using yarn as package manager.");
return { ...YarnPackageManager };
} else if (hasPnpm) {
logger.log("Using pnpm as package manager.");
return { ...PnpmPackageManager };
} else {
throw new UserError(
"Unable to find a package manager. Supported managers are: npm, yarn, and pnpm.",
{
telemetryMessage: true
}
);
}
}
async function supports(name2) {
try {
execaCommandSync(`${name2} --version`, { stdio: "ignore" });
return true;
} catch {
return false;
}
}
function supportsYarn() {
return supports("yarn");
}
function supportsNpm() {
return supports("npm");
}
function supportsPnpm() {
return supports("pnpm");
}
function sniffUserAgent() {
const userAgent = import_node_process10.env.npm_config_user_agent;
if (userAgent === void 0) {
return void 0;
}
if (userAgent.includes("yarn")) {
return "yarn";
}
if (userAgent.includes("pnpm")) {
return "pnpm";
}
if (userAgent.includes("npm")) {
return "npm";
}
}
var import_node_process10, NpmPackageManager, PnpmPackageManager, YarnPackageManager;
var init_package_manager = __esm({
"src/package-manager.ts"() {
init_import_meta_url();
import_node_process10 = require("process");
init_execa();
init_errors();
init_logger();
__name(getPackageManager, "getPackageManager");
NpmPackageManager = {
type: "npm"
};
PnpmPackageManager = {
type: "pnpm"
};
YarnPackageManager = {
type: "yarn"
};
__name(supports, "supports");
__name(supportsYarn, "supportsYarn");
__name(supportsNpm, "supportsNpm");
__name(supportsPnpm, "supportsPnpm");
__name(sniffUserAgent, "sniffUserAgent");
}
});
// src/metrics/helpers.ts
function getWranglerVersion() {
return version;
}
function getPlatform() {
const platform3 = import_node_os7.default.platform();
switch (platform3) {
case "win32":
return "Windows";
case "darwin":
return "Mac OS";
case "linux":
return "Linux";
default:
return `Others: ${platform3}`;
}
}
function getOS() {
return process.platform + ":" + process.arch;
}
function getOSVersion() {
return import_node_os7.default.version();
}
function getNodeVersion() {
const nodeVersion2 = process.versions.node;
return parseInt(nodeVersion2.split(".")[0]);
}
var import_node_os7;
var init_helpers5 = __esm({
"src/metrics/helpers.ts"() {
init_import_meta_url();
import_node_os7 = __toESM(require("os"));
init_package();
__name(getWranglerVersion, "getWranglerVersion");
__name(getPlatform, "getPlatform");
__name(getOS, "getOS");
__name(getOSVersion, "getOSVersion");
__name(getNodeVersion, "getNodeVersion");
}
});
// src/metrics/metrics-config.ts
function getMetricsConfig({
sendMetrics
}) {
const config = readMetricsConfig();
const deviceId = getDeviceId(config);
const sendMetricsEnv = getWranglerSendMetricsFromEnv();
if (sendMetricsEnv !== void 0) {
return {
enabled: sendMetricsEnv,
deviceId
};
}
if (sendMetrics !== void 0) {
return { enabled: sendMetrics, deviceId };
}
const permission = config.permission;
if (permission !== void 0) {
if (new Date(permission.date) >= CURRENT_METRICS_DATE) {
return { enabled: permission.enabled, deviceId };
} else if (permission.enabled) {
logger.log(
"Usage metrics tracking has changed since you last granted permission."
);
}
}
writeMetricsConfig({
...config,
permission: {
enabled: true,
date: /* @__PURE__ */ new Date()
},
deviceId
});
return { enabled: true, deviceId };
}
function writeMetricsConfig(config) {
(0, import_node_fs13.mkdirSync)(import_node_path24.default.dirname(getMetricsConfigPath()), { recursive: true });
(0, import_node_fs13.writeFileSync)(
getMetricsConfigPath(),
JSON.stringify(
config,
(_key, value) => value instanceof Date ? value.toISOString() : value,
" "
)
);
}
function readMetricsConfig() {
try {
const config = (0, import_node_fs13.readFileSync)(getMetricsConfigPath(), "utf8");
return JSON.parse(
config,
(key, value) => key === "date" ? new Date(value) : value
);
} catch {
return {};
}
}
function updateMetricsPermission(enabled) {
const config = readMetricsConfig();
config.permission = {
enabled,
date: /* @__PURE__ */ new Date()
};
writeMetricsConfig(config);
}
function getMetricsConfigPath() {
return import_node_path24.default.resolve(getGlobalWranglerConfigPath(), "metrics.json");
}
function getDeviceId(config) {
const deviceId = config.deviceId ?? (0, import_node_crypto5.randomUUID)();
if (config.deviceId === void 0) {
writeMetricsConfig({ ...config, deviceId });
}
return deviceId;
}
var import_node_crypto5, import_node_fs13, import_node_path24, CURRENT_METRICS_DATE;
var init_metrics_config = __esm({
"src/metrics/metrics-config.ts"() {
init_import_meta_url();
import_node_crypto5 = require("crypto");
import_node_fs13 = require("fs");
import_node_path24 = __toESM(require("path"));
init_misc_variables();
init_global_wrangler_config_path();
init_logger();
CURRENT_METRICS_DATE = new Date(2022, 6, 4);
__name(getMetricsConfig, "getMetricsConfig");
__name(writeMetricsConfig, "writeMetricsConfig");
__name(readMetricsConfig, "readMetricsConfig");
__name(updateMetricsPermission, "updateMetricsPermission");
__name(getMetricsConfigPath, "getMetricsConfigPath");
__name(getDeviceId, "getDeviceId");
}
});
// src/metrics/metrics-dispatcher.ts
function getMetricsDispatcher(options) {
const SPARROW_SOURCE_KEY = "50598e014ed44c739ec8074fdc16057c";
const requests = [];
const wranglerVersion = getWranglerVersion();
const amplitude_session_id = Date.now();
let amplitude_event_id = 0;
const allowList = {
// applies to all commands
// use camelCase version
"*": { format: "*", logLevel: "*" },
"wrangler tail": { status: "*" },
"wrangler types": {
xIncludeRuntime: [".wrangler/types/runtime.d.ts"],
path: ["worker-configuration.d.ts"]
}
};
return {
// TODO: merge two sendEvent functions once all commands use defineCommand and get a global dispatcher
/**
* This doesn't have a session id and is not tied to the command events.
*
* The event should follow these conventions
* - name is of the form `[action] [object]` (lower case)
* - additional properties are camelCased
*/
sendAdhocEvent(name2, properties = {}) {
dispatch({
name: name2,
properties: {
category: "Workers",
wranglerVersion,
os: getOS(),
...properties
}
});
},
/**
* Dispatches `wrangler command started / completed / errored` events
*
* This happens on every command execution. When all commands use defineCommand,
* we should use that to provide the dispatcher on all handlers, and change all
* `sendEvent` calls to use this method.
*/
sendCommandEvent(name2, properties, argv) {
try {
if (properties.command?.startsWith("wrangler login")) {
properties.command = "wrangler login";
}
if (properties.command === "wrangler telemetry disable" || properties.command === "wrangler metrics disable") {
return;
}
if (properties.command === "wrangler deploy" || properties.command === "wrangler dev" || // for testing purposes
properties.command === "wrangler docs") {
printMetricsBanner();
}
const argsUsed = sanitiseUserInput(properties.args ?? {}, argv);
const argsCombination = argsUsed.sort().join(", ");
const commonEventProperties = {
amplitude_session_id,
amplitude_event_id: amplitude_event_id++,
wranglerVersion,
osPlatform: getPlatform(),
osVersion: getOSVersion(),
nodeVersion: getNodeVersion(),
packageManager: sniffUserAgent(),
isFirstUsage: readMetricsConfig().permission === void 0,
configFileType: configFormat(options.configPath),
isCI: CI.isCI(),
isPagesCI: isPagesCI(),
isWorkersCI: isWorkersCI(),
isInteractive: isInteractive2(),
hasAssets: options.hasAssets ?? false,
argsUsed,
argsCombination
};
const allowedArgs = getAllowedArgs(allowList, properties.command ?? "");
properties.args = redactArgValues(properties.args ?? {}, allowedArgs);
dispatch({
name: name2,
properties: {
...commonEventProperties,
...properties
}
});
} catch (err) {
logger.debug("Error sending metrics event", err);
}
},
get requests() {
return requests;
}
};
function dispatch(event) {
const metricsConfig = getMetricsConfig(options);
const body = {
deviceId: metricsConfig.deviceId,
event: event.name,
timestamp: Date.now(),
properties: event.properties
};
if (!metricsConfig.enabled) {
logger.debug(
`Metrics dispatcher: Dispatching disabled - would have sent ${JSON.stringify(
body
)}.`
);
return;
}
if (!SPARROW_SOURCE_KEY) {
logger.debug(
"Metrics dispatcher: Source Key not provided. Be sure to initialize before sending events",
JSON.stringify(body)
);
return;
}
logger.debug(`Metrics dispatcher: Posting data ${JSON.stringify(body)}`);
const request4 = (0, import_undici5.fetch)(`${SPARROW_URL}/api/v1/event`, {
method: "POST",
headers: {
Accept: "*/*",
"Content-Type": "application/json",
"Sparrow-Source-Key": SPARROW_SOURCE_KEY
},
mode: "cors",
keepalive: true,
body: JSON.stringify(body)
}).then((res) => {
if (!res.ok) {
logger.debug(
"Metrics dispatcher: Failed to send request:",
res.statusText
);
}
}).catch((e7) => {
logger.debug(
"Metrics dispatcher: Failed to send request:",
e7.message
);
});
requests.push(request4);
}
__name(dispatch, "dispatch");
function printMetricsBanner() {
const metricsConfig = readMetricsConfig();
if (metricsConfig.permission?.enabled && metricsConfig.permission?.bannerLastShown !== wranglerVersion) {
logger.log(
source_default.gray(
`
Cloudflare collects anonymous telemetry about your usage of Wrangler. Learn more at https://github.com/cloudflare/workers-sdk/tree/main/packages/wrangler/telemetry.md`
)
);
metricsConfig.permission.bannerLastShown = wranglerVersion;
writeMetricsConfig(metricsConfig);
}
}
__name(printMetricsBanner, "printMetricsBanner");
}
var import_undici5, SPARROW_URL, normalise, exclude, sanitiseUserInput, getAllowedArgs, redactArgValues;
var init_metrics_dispatcher = __esm({
"src/metrics/metrics-dispatcher.ts"() {
init_import_meta_url();
init_source();
import_undici5 = __toESM(require_undici());
init_config2();
init_is_interactive();
init_logger();
init_package_manager();
init_is_ci();
init_helpers5();
init_metrics_config();
SPARROW_URL = "https://sparrow.cloudflare.com";
__name(getMetricsDispatcher, "getMetricsDispatcher");
normalise = /* @__PURE__ */ __name((arg) => {
const camelize = /* @__PURE__ */ __name((str) => str.replace(/-./g, (x6) => x6[1].toUpperCase()), "camelize");
return camelize(arg.replace("experimental", "x"));
}, "normalise");
exclude = /* @__PURE__ */ new Set(["$0", "_"]);
sanitiseUserInput = /* @__PURE__ */ __name((argsWithValues, argv) => {
const result = [];
const args = Object.keys(argsWithValues);
for (const arg of args) {
if (Array.isArray(argv) && !argv.some((a5) => a5.includes(arg))) {
continue;
}
if (exclude.has(arg)) {
continue;
}
if (typeof argsWithValues[arg] === "boolean" && argsWithValues[arg] === false) {
continue;
}
const normalisedArg = normalise(arg);
if (result.includes(normalisedArg)) {
continue;
}
result.push(normalisedArg);
}
return result;
}, "sanitiseUserInput");
getAllowedArgs = /* @__PURE__ */ __name((allowList, key) => {
const commandSpecific = allowList[key] ?? [];
return { ...commandSpecific, ...allowList["*"] };
}, "getAllowedArgs");
redactArgValues = /* @__PURE__ */ __name((args, allowedValues) => {
const result = {};
for (let [key, value] of Object.entries(args)) {
key = normalise(key);
if (key === "xIncludeRuntime" && value === "") {
value = ".wrangler/types/runtime.d.ts";
}
const allowedValuesForArg = allowedValues[key] ?? [];
if (exclude.has(key)) {
continue;
}
if (typeof value === "number" || typeof value === "boolean" || allowedValuesForArg.includes(key)) {
result[key] = value;
} else if (
// redact if its a string, unless the value is in the allow list
// * is a special value that allows all values for that arg
typeof value === "string" && !(allowedValuesForArg === "*" || allowedValuesForArg.includes(value))
) {
result[key] = "<REDACTED>";
} else if (Array.isArray(value)) {
result[key] = value.map(
(v7) => (
// redact if its a string, unless the value is in the allow list
// * is a special value that allows all values for that arg
typeof v7 === "string" && !(allowedValuesForArg === "*" || allowedValuesForArg.includes(v7)) ? "<REDACTED>" : v7
)
);
} else {
result[key] = value;
}
}
return result;
}, "redactArgValues");
}
});
// src/metrics/send-event.ts
function sendMetricsEvent(event, ...args) {
try {
const options = args.pop() ?? {};
const properties = args.pop() ?? {};
const metricsDispatcher = getMetricsDispatcher(options);
metricsDispatcher.sendAdhocEvent(event, properties);
} catch (err) {
logger.debug("Error sending metrics event", err);
}
}
var init_send_event = __esm({
"src/metrics/send-event.ts"() {
init_import_meta_url();
init_logger();
init_metrics_dispatcher();
__name(sendMetricsEvent, "sendMetricsEvent");
}
});
// src/metrics/metrics-usage-headers.ts
async function getMetricsUsageHeaders(sendMetrics) {
const metricsEnabled = (await getMetricsConfig({
sendMetrics
})).enabled;
if (metricsEnabled) {
return {
metricsEnabled: "true"
};
} else {
return void 0;
}
}
var init_metrics_usage_headers = __esm({
"src/metrics/metrics-usage-headers.ts"() {
init_import_meta_url();
init_metrics_config();
__name(getMetricsUsageHeaders, "getMetricsUsageHeaders");
}
});
// src/metrics/index.ts
var init_metrics = __esm({
"src/metrics/index.ts"() {
init_import_meta_url();
init_metrics_dispatcher();
init_metrics_config();
init_send_event();
init_metrics_usage_headers();
}
});
// src/utils/isLegacyEnv.ts
function isLegacyEnv(config) {
return config.legacy_env;
}
var init_isLegacyEnv = __esm({
"src/utils/isLegacyEnv.ts"() {
init_import_meta_url();
__name(isLegacyEnv, "isLegacyEnv");
}
});
// src/deployment-bundle/bindings.ts
function getBindings(config, options) {
return {
kv_namespaces: config?.kv_namespaces,
send_email: options?.pages ? void 0 : config?.send_email,
vars: config?.vars,
wasm_modules: options?.pages ? void 0 : config?.wasm_modules,
browser: config?.browser,
ai: config?.ai,
images: config?.images,
version_metadata: config?.version_metadata,
text_blobs: options?.pages ? void 0 : config?.text_blobs,
data_blobs: options?.pages ? void 0 : config?.data_blobs,
durable_objects: config?.durable_objects,
workflows: config?.workflows,
queues: config?.queues.producers?.map((producer) => {
return { binding: producer.binding, queue_name: producer.queue };
}),
r2_buckets: config?.r2_buckets,
d1_databases: config?.d1_databases,
vectorize: config?.vectorize,
hyperdrive: config?.hyperdrive,
secrets_store_secrets: config?.secrets_store_secrets,
services: config?.services,
analytics_engine_datasets: config?.analytics_engine_datasets,
dispatch_namespaces: options?.pages ? void 0 : config?.dispatch_namespaces,
mtls_certificates: config?.mtls_certificates,
pipelines: options?.pages ? void 0 : config?.pipelines,
logfwdr: options?.pages ? void 0 : config?.logfwdr,
assets: options?.pages ? void 0 : config?.assets?.binding ? { binding: config?.assets?.binding } : void 0,
unsafe: options?.pages ? void 0 : {
bindings: config?.unsafe.bindings,
metadata: config?.unsafe.metadata,
capnp: config?.unsafe.capnp
},
unsafe_hello_world: options?.pages ? void 0 : config?.unsafe_hello_world
};
}
async function collectPendingResources(complianceConfig, accountId, scriptName, bindings) {
let settings;
try {
settings = await getSettings(complianceConfig, accountId, scriptName);
} catch {
logger.debug("No settings found");
}
const pendingResources = [];
try {
settings = await getSettings(complianceConfig, accountId, scriptName);
} catch {
logger.debug("No settings found");
}
for (const resourceType of Object.keys(
HANDLERS
)) {
for (const resource of bindings[resourceType] ?? []) {
const h6 = new HANDLERS[resourceType].Handler(
resource,
complianceConfig,
accountId
);
if (await h6.shouldProvision(settings)) {
pendingResources.push({
binding: resource.binding,
resourceType,
handler: h6
});
}
}
}
return pendingResources.sort(
(a5, b6) => HANDLERS[a5.resourceType].sort - HANDLERS[b6.resourceType].sort
);
}
async function provisionBindings(bindings, accountId, scriptName, autoCreate, config) {
const pendingResources = await collectPendingResources(
config,
accountId,
scriptName,
bindings
);
if (pendingResources.length > 0) {
if (!isLegacyEnv(config)) {
throw new UserError(
"Provisioning resources is not supported with a service environment"
);
}
logger.log();
const printable = {};
for (const resource of pendingResources) {
printable[resource.resourceType] ??= [];
printable[resource.resourceType].push({ binding: resource.binding });
}
printBindings(printable, config.tail_consumers, { provisioning: true });
logger.log();
const existingResources = {};
for (const resource of pendingResources) {
existingResources[resource.resourceType] ??= await LOADERS[resource.resourceType](config, accountId);
await runProvisioningFlow(
resource,
existingResources[resource.resourceType],
HANDLERS[resource.resourceType].name,
scriptName,
autoCreate
);
}
const resourceCount = pendingResources.reduce(
(acc, resource) => {
acc[resource.resourceType] ??= 0;
acc[resource.resourceType]++;
return acc;
},
{}
);
logger.log(`\u{1F389} All resources provisioned, continuing with deployment...
`);
sendMetricsEvent("provision resources", resourceCount, {
sendMetrics: config.send_metrics
});
}
}
function getSettings(complianceConfig, accountId, scriptName) {
return fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${scriptName}/settings`
);
}
function printDivider() {
logger.log();
}
async function runProvisioningFlow(item, preExisting, friendlyBindingName, scriptName, autoCreate) {
const NEW_OPTION_VALUE = "__WRANGLER_INTERNAL_NEW";
const SEARCH_OPTION_VALUE = "__WRANGLER_INTERNAL_SEARCH";
const MAX_OPTIONS = 4;
const options = preExisting.slice(0, MAX_OPTIONS - 1);
if (options.length < preExisting.length) {
options.push({
title: "Other (too many to list)",
value: SEARCH_OPTION_VALUE
});
}
const defaultName = `${scriptName}-${item.binding.toLowerCase().replaceAll("_", "-")}`;
logger.log("Provisioning", item.binding, `(${friendlyBindingName})...`);
if (item.handler.name) {
logger.log("Resource name found in config:", item.handler.name);
logger.log(
`\u{1F300} Creating new ${friendlyBindingName} "${item.handler.name}"...`
);
await item.handler.provision(item.handler.name);
} else if (autoCreate) {
logger.log(`\u{1F300} Creating new ${friendlyBindingName} "${defaultName}"...`);
await item.handler.provision(defaultName);
} else {
let action = NEW_OPTION_VALUE;
if (options.length > 0) {
action = await select(
`Would you like to connect an existing ${friendlyBindingName} or create a new one?`,
{
choices: options.concat([
{ title: "Create new", value: NEW_OPTION_VALUE }
]),
defaultOption: options.length,
fallbackOption: options.length
}
);
}
if (action === NEW_OPTION_VALUE) {
const name2 = await prompt(
`Enter a name for your new ${friendlyBindingName}`,
{
defaultValue: defaultName
}
);
logger.log(`\u{1F300} Creating new ${friendlyBindingName} "${name2}"...`);
await item.handler.provision(name2);
} else if (action === SEARCH_OPTION_VALUE) {
let foundResource;
while (foundResource === void 0) {
const input = await prompt(
`Enter the ${HANDLERS[item.resourceType].keyDescription} for an existing ${friendlyBindingName}`
);
foundResource = preExisting.find(
(r7) => r7.title === input || r7.value === input
);
if (foundResource) {
item.handler.connect(foundResource.value);
} else {
logger.log(
`No ${friendlyBindingName} with that ${HANDLERS[item.resourceType].keyDescription} "${input}" found. Please try again.`
);
}
}
} else {
item.handler.connect(action);
}
}
logger.log(`\u2728 ${item.binding} provisioned \u{1F389}`);
printDivider();
}
var import_node_assert13, INHERIT_SYMBOL, ProvisionResourceHandler, R2Handler, KVHandler, D1Handler, HANDLERS, LOADERS;
var init_bindings = __esm({
"src/deployment-bundle/bindings.ts"() {
init_import_meta_url();
import_node_assert13 = __toESM(require("assert"));
init_cfetch();
init_create();
init_list();
init_utils3();
init_dialogs();
init_errors();
init_helpers4();
init_logger();
init_metrics();
init_parse();
init_helpers();
init_isLegacyEnv();
init_print_bindings();
INHERIT_SYMBOL = Symbol.for("inherit_binding");
__name(getBindings, "getBindings");
ProvisionResourceHandler = class {
constructor(type, binding, idField, complianceConfig, accountId) {
this.type = type;
this.binding = binding;
this.idField = idField;
this.complianceConfig = complianceConfig;
this.accountId = accountId;
}
static {
__name(this, "ProvisionResourceHandler");
}
inherit() {
this.binding[this.idField] = INHERIT_SYMBOL;
}
connect(id) {
this.binding[this.idField] = id;
}
async provision(name2) {
const id = await this.create(name2);
this.connect(id);
}
// This binding is fully specified and can't/shouldn't be provisioned
// This is usually when it has an id (e.g. D1 `database_id`)
isFullySpecified() {
return false;
}
// Does this binding need to be provisioned?
// Some bindings are not fully specified, but don't need provisioning
// (e.g. R2 binding, with a bucket_name that already exists)
async isConnectedToExistingResource() {
return false;
}
// Should this resource be provisioned?
async shouldProvision(settings) {
if (!this.isFullySpecified()) {
if (await this.canInherit(settings)) {
this.inherit();
} else {
const connected = await this.isConnectedToExistingResource();
if (connected) {
if (typeof connected === "string") {
this.connect(connected);
}
return false;
}
return true;
}
}
return false;
}
};
R2Handler = class extends ProvisionResourceHandler {
static {
__name(this, "R2Handler");
}
get name() {
return this.binding.bucket_name;
}
async create(name2) {
await createR2Bucket(
this.complianceConfig,
this.accountId,
name2,
void 0,
this.binding.jurisdiction
);
return name2;
}
constructor(binding, complianceConfig, accountId) {
super("r2_bucket", binding, "bucket_name", complianceConfig, accountId);
}
canInherit(settings) {
return !!settings?.bindings.find(
(existing) => existing.type === this.type && existing.name === this.binding.binding && existing.jurisdiction === this.binding.jurisdiction
);
}
async isConnectedToExistingResource() {
(0, import_node_assert13.default)(typeof this.binding.bucket_name !== "symbol");
if (!this.binding.bucket_name) {
return false;
}
try {
await getR2Bucket(
this.complianceConfig,
this.accountId,
this.binding.bucket_name,
this.binding.jurisdiction
);
return true;
} catch (e7) {
if (!(e7 instanceof APIError && e7.code === 10006)) {
throw e7;
}
return false;
}
}
};
KVHandler = class extends ProvisionResourceHandler {
static {
__name(this, "KVHandler");
}
get name() {
return void 0;
}
async create(name2) {
return await createKVNamespace(this.complianceConfig, this.accountId, name2);
}
constructor(binding, complianceConfig, accountId) {
super("kv_namespace", binding, "id", complianceConfig, accountId);
}
canInherit(settings) {
return !!settings?.bindings.find(
(existing) => existing.type === this.type && existing.name === this.binding.binding
);
}
isFullySpecified() {
return !!this.binding.id;
}
};
D1Handler = class extends ProvisionResourceHandler {
static {
__name(this, "D1Handler");
}
get name() {
return this.binding.database_name;
}
async create(name2) {
const db = await createD1Database(
this.complianceConfig,
this.accountId,
name2
);
return db.uuid;
}
constructor(binding, complianceConfig, accountId) {
super("d1", binding, "database_id", complianceConfig, accountId);
}
async canInherit(settings) {
const maybeInherited = settings?.bindings.find(
(existing) => existing.type === this.type && existing.name === this.binding.binding
);
if (maybeInherited) {
if (!this.binding.database_name) {
return true;
}
const dbFromId = await getDatabaseInfoFromIdOrName(
this.complianceConfig,
this.accountId,
maybeInherited.id
);
if (this.binding.database_name === dbFromId.name) {
return true;
}
}
return false;
}
async isConnectedToExistingResource() {
(0, import_node_assert13.default)(typeof this.binding.database_name !== "symbol");
if (!this.binding.database_name) {
return false;
}
try {
const db = await getDatabaseInfoFromIdOrName(
this.complianceConfig,
this.accountId,
this.binding.database_name
);
return db.uuid;
} catch (e7) {
if (!(e7 instanceof APIError && e7.code === 7404)) {
throw e7;
}
return false;
}
}
isFullySpecified() {
return !!this.binding.database_id;
}
};
HANDLERS = {
kv_namespaces: {
Handler: KVHandler,
sort: 0,
name: "KV Namespace",
keyDescription: "title or id"
},
d1_databases: {
Handler: D1Handler,
sort: 1,
name: "D1 Database",
keyDescription: "name or id"
},
r2_buckets: {
Handler: R2Handler,
sort: 2,
name: "R2 Bucket",
keyDescription: "name"
}
};
LOADERS = {
kv_namespaces: /* @__PURE__ */ __name(async (complianceConfig, accountId) => {
const preExistingKV = await listKVNamespaces(
complianceConfig,
accountId,
true
);
return preExistingKV.map((ns) => ({ title: ns.title, value: ns.id }));
}, "kv_namespaces"),
d1_databases: /* @__PURE__ */ __name(async (complianceConfig, accountId) => {
const preExisting = await listDatabases(
complianceConfig,
accountId,
true,
1e3
);
return preExisting.map((db) => ({ title: db.name, value: db.uuid }));
}, "d1_databases"),
r2_buckets: /* @__PURE__ */ __name(async (complianceConfig, accountId) => {
const preExisting = await listR2Buckets(complianceConfig, accountId);
return preExisting.map((bucket) => ({
title: bucket.name,
value: bucket.name
}));
}, "r2_buckets")
};
__name(collectPendingResources, "collectPendingResources");
__name(provisionBindings, "provisionBindings");
__name(getSettings, "getSettings");
__name(printDivider, "printDivider");
__name(runProvisioningFlow, "runProvisioningFlow");
}
});
// src/deployment-bundle/bundle-reporter.ts
async function getSize(modules) {
const gzipSize = (0, import_node_zlib.gzipSync)(
await new import_node_buffer3.Blob(modules.map((file) => file.content)).arrayBuffer()
).byteLength;
const aggregateSize = new import_node_buffer3.Blob(modules.map((file) => file.content)).size;
return { size: aggregateSize, gzipSize };
}
async function printBundleSize(main2, modules) {
const { size, gzipSize } = await getSize([...modules, main2]);
const bundleReport = `${(size / ONE_KIB_BYTES).toFixed(2)} KiB / gzip: ${(gzipSize / ONE_KIB_BYTES).toFixed(2)} KiB`;
const percentage = gzipSize / MAX_GZIP_SIZE_BYTES * 100;
const colorizedReport = percentage > 90 ? source_default.red(bundleReport) : percentage > 70 ? source_default.yellow(bundleReport) : source_default.green(bundleReport);
logger.log(`Total Upload: ${colorizedReport}`);
}
var import_node_buffer3, import_node_zlib, ONE_KIB_BYTES, MAX_GZIP_SIZE_BYTES;
var init_bundle_reporter = __esm({
"src/deployment-bundle/bundle-reporter.ts"() {
init_import_meta_url();
import_node_buffer3 = require("buffer");
import_node_zlib = require("zlib");
init_source();
init_logger();
ONE_KIB_BYTES = 1024;
MAX_GZIP_SIZE_BYTES = 3 * ONE_KIB_BYTES * ONE_KIB_BYTES;
__name(getSize, "getSize");
__name(printBundleSize, "printBundleSize");
}
});
// ../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/lib/command-exists.js
var require_command_exists = __commonJS({
"../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/lib/command-exists.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var exec3 = require("child_process").exec;
var execSync5 = require("child_process").execSync;
var fs24 = require("fs");
var path72 = require("path");
var access4 = fs24.access;
var accessSync = fs24.accessSync;
var constants4 = fs24.constants || fs24;
var isUsingWindows = process.platform == "win32";
var fileNotExists = /* @__PURE__ */ __name(function(commandName, callback) {
access4(
commandName,
constants4.F_OK,
function(err) {
callback(!err);
}
);
}, "fileNotExists");
var fileNotExistsSync = /* @__PURE__ */ __name(function(commandName) {
try {
accessSync(commandName, constants4.F_OK);
return false;
} catch (e7) {
return true;
}
}, "fileNotExistsSync");
var localExecutable = /* @__PURE__ */ __name(function(commandName, callback) {
access4(
commandName,
constants4.F_OK | constants4.X_OK,
function(err) {
callback(null, !err);
}
);
}, "localExecutable");
var localExecutableSync = /* @__PURE__ */ __name(function(commandName) {
try {
accessSync(commandName, constants4.F_OK | constants4.X_OK);
return true;
} catch (e7) {
return false;
}
}, "localExecutableSync");
var commandExistsUnix = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
fileNotExists(commandName, function(isFile) {
if (!isFile) {
var child = exec3(
"command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }",
function(error2, stdout2, stderr2) {
callback(null, !!stdout2);
}
);
return;
}
localExecutable(commandName, callback);
});
}, "commandExistsUnix");
var commandExistsWindows = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
callback(null, false);
return;
}
var child = exec3(
"where " + cleanedCommandName,
function(error2) {
if (error2 !== null) {
callback(null, false);
} else {
callback(null, true);
}
}
);
}, "commandExistsWindows");
var commandExistsUnixSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName) {
if (fileNotExistsSync(commandName)) {
try {
var stdout2 = execSync5(
"command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }"
);
return !!stdout2;
} catch (error2) {
return false;
}
}
return localExecutableSync(commandName);
}, "commandExistsUnixSync");
var commandExistsWindowsSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
return false;
}
try {
var stdout2 = execSync5("where " + cleanedCommandName, { stdio: [] });
return !!stdout2;
} catch (error2) {
return false;
}
}, "commandExistsWindowsSync");
var cleanInput = /* @__PURE__ */ __name(function(s5) {
if (/[^A-Za-z0-9_\/:=-]/.test(s5)) {
s5 = "'" + s5.replace(/'/g, "'\\''") + "'";
s5 = s5.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
}
return s5;
}, "cleanInput");
if (isUsingWindows) {
cleanInput = /* @__PURE__ */ __name(function(s5) {
var isPathName = /[\\]/.test(s5);
if (isPathName) {
var dirname18 = '"' + path72.dirname(s5) + '"';
var basename7 = '"' + path72.basename(s5) + '"';
return dirname18 + ":" + basename7;
}
return '"' + s5 + '"';
}, "cleanInput");
}
module3.exports = /* @__PURE__ */ __name(function commandExists(commandName, callback) {
var cleanedCommandName = cleanInput(commandName);
if (!callback && typeof Promise !== "undefined") {
return new Promise(function(resolve25, reject) {
commandExists(commandName, function(error2, output) {
if (output) {
resolve25(commandName);
} else {
reject(error2);
}
});
});
}
if (isUsingWindows) {
commandExistsWindows(commandName, cleanedCommandName, callback);
} else {
commandExistsUnix(commandName, cleanedCommandName, callback);
}
}, "commandExists");
module3.exports.sync = function(commandName) {
var cleanedCommandName = cleanInput(commandName);
if (isUsingWindows) {
return commandExistsWindowsSync(commandName, cleanedCommandName);
} else {
return commandExistsUnixSync(commandName, cleanedCommandName);
}
};
}
});
// ../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/index.js
var require_command_exists2 = __commonJS({
"../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/index.js"(exports2, module3) {
init_import_meta_url();
module3.exports = require_command_exists();
}
});
// src/deployment-bundle/capnp.ts
function handleUnsafeCapnp(capnp) {
if (capnp.compiled_schema) {
return (0, import_node_fs14.readFileSync)((0, import_node_path25.resolve)(capnp.compiled_schema));
}
const { base_path, source_schemas } = capnp;
const capnpSchemas = (source_schemas ?? []).map(
(x6) => (0, import_node_path25.resolve)(base_path, x6)
);
if (!(0, import_command_exists.sync)("capnp")) {
throw new UserError(
"The capnp compiler is required to upload capnp schemas, but is not present."
);
}
const srcPrefix = (0, import_node_path25.resolve)(base_path ?? ".");
const capnpProcess = (0, import_node_child_process3.spawnSync)(
"capnp",
["compile", "-o-", `--src-prefix=${srcPrefix}`, ...capnpSchemas],
// This number was chosen arbitrarily. If you get ENOBUFS because your compiled schema is still
// too large, then we may need to bump this again or figure out another approach.
// https://github.com/cloudflare/workers-sdk/pull/10217
{ maxBuffer: 3 * 1024 * 1024 }
);
if (capnpProcess.error) {
throw capnpProcess.error;
}
if (capnpProcess.stderr.length) {
throw new Error(capnpProcess.stderr.toString());
}
return capnpProcess.stdout;
}
var import_node_child_process3, import_node_fs14, import_node_path25, import_command_exists;
var init_capnp = __esm({
"src/deployment-bundle/capnp.ts"() {
init_import_meta_url();
import_node_child_process3 = require("child_process");
import_node_fs14 = require("fs");
import_node_path25 = require("path");
import_command_exists = __toESM(require_command_exists2());
init_errors();
__name(handleUnsafeCapnp, "handleUnsafeCapnp");
}
});
// src/deployment-bundle/create-worker-upload-form.ts
function toMimeType(type) {
const mimeType = moduleTypeMimeType[type];
if (mimeType === void 0) {
throw new TypeError("Unsupported module: " + type);
}
return mimeType;
}
function fromMimeType(mimeType) {
const moduleType = Object.keys(moduleTypeMimeType).find(
(type) => moduleTypeMimeType[type] === mimeType
);
if (moduleType === void 0) {
throw new TypeError("Unsupported mime type: " + mimeType);
}
return moduleType;
}
function createWorkerUploadForm(worker) {
const formData = new import_undici6.FormData();
const {
main: main2,
sourceMaps,
bindings,
rawBindings,
migrations,
compatibility_date,
compatibility_flags,
keepVars,
keepSecrets,
keepBindings,
logpush,
placement,
tail_consumers,
limits,
annotations,
keep_assets,
assets,
observability
} = worker;
const assetConfig = {
html_handling: assets?.assetConfig?.html_handling,
not_found_handling: assets?.assetConfig?.not_found_handling,
run_worker_first: assets?.run_worker_first,
_redirects: assets?._redirects,
_headers: assets?._headers
};
if (assets && !assets.routerConfig.has_user_worker) {
formData.set(
"metadata",
JSON.stringify({
assets: {
jwt: assets.jwt,
config: assetConfig
},
...annotations && { annotations },
...compatibility_date && { compatibility_date },
...compatibility_flags && { compatibility_flags }
})
);
return formData;
}
let { modules } = worker;
const metadataBindings = rawBindings ?? [];
Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
if (typeof value === "string") {
metadataBindings.push({ name: key, type: "plain_text", text: value });
} else {
metadataBindings.push({ name: key, type: "json", json: value });
}
});
bindings.kv_namespaces?.forEach(({ id, binding, raw }) => {
if (id === void 0) {
throw new UserError(`${binding} bindings must have an "id" field`);
}
if (id === INHERIT_SYMBOL) {
metadataBindings.push({
name: binding,
type: "inherit"
});
} else {
metadataBindings.push({
name: binding,
type: "kv_namespace",
namespace_id: id,
raw
});
}
});
bindings.send_email?.forEach((emailBinding) => {
const destination_address = "destination_address" in emailBinding ? emailBinding.destination_address : void 0;
const allowed_destination_addresses = "allowed_destination_addresses" in emailBinding ? emailBinding.allowed_destination_addresses : void 0;
metadataBindings.push({
name: emailBinding.name,
type: "send_email",
destination_address,
allowed_destination_addresses
});
});
bindings.durable_objects?.bindings.forEach(
({ name: name2, class_name, script_name, environment }) => {
metadataBindings.push({
name: name2,
type: "durable_object_namespace",
class_name,
...script_name && { script_name },
...environment && { environment }
});
}
);
bindings.workflows?.forEach(
({ binding, name: name2, class_name, script_name, raw }) => {
metadataBindings.push({
type: "workflow",
name: binding,
workflow_name: name2,
class_name,
script_name,
raw
});
}
);
bindings.queues?.forEach(({ binding, queue_name, delivery_delay, raw }) => {
metadataBindings.push({
type: "queue",
name: binding,
queue_name,
delivery_delay,
raw
});
});
bindings.r2_buckets?.forEach(
({ binding, bucket_name, jurisdiction, raw }) => {
if (bucket_name === void 0) {
throw new UserError(
`${binding} bindings must have a "bucket_name" field`
);
}
if (bucket_name === INHERIT_SYMBOL) {
metadataBindings.push({
name: binding,
type: "inherit"
});
} else {
metadataBindings.push({
name: binding,
type: "r2_bucket",
bucket_name,
jurisdiction,
raw
});
}
}
);
bindings.d1_databases?.forEach(
({ binding, database_id, database_internal_env, raw }) => {
if (database_id === void 0) {
throw new UserError(
`${binding} bindings must have a "database_id" field`
);
}
if (database_id === INHERIT_SYMBOL) {
metadataBindings.push({
name: binding,
type: "inherit"
});
} else {
metadataBindings.push({
name: binding,
type: "d1",
id: database_id,
internalEnv: database_internal_env,
raw
});
}
}
);
bindings.vectorize?.forEach(({ binding, index_name, raw }) => {
metadataBindings.push({
name: binding,
type: "vectorize",
index_name,
raw
});
});
bindings.hyperdrive?.forEach(({ binding, id }) => {
metadataBindings.push({
name: binding,
type: "hyperdrive",
id
});
});
bindings.secrets_store_secrets?.forEach(
({ binding, store_id, secret_name }) => {
metadataBindings.push({
name: binding,
type: "secrets_store_secret",
store_id,
secret_name
});
}
);
bindings.unsafe_hello_world?.forEach(({ binding, enable_timer }) => {
metadataBindings.push({
name: binding,
type: "unsafe_hello_world",
enable_timer
});
});
bindings.services?.forEach(
({ binding, service, environment, entrypoint, props }) => {
metadataBindings.push({
name: binding,
type: "service",
service,
...environment && { environment },
...entrypoint && { entrypoint },
...props && { props }
});
}
);
bindings.analytics_engine_datasets?.forEach(({ binding, dataset }) => {
metadataBindings.push({
name: binding,
type: "analytics_engine",
dataset
});
});
bindings.dispatch_namespaces?.forEach(({ binding, namespace, outbound }) => {
metadataBindings.push({
name: binding,
type: "dispatch_namespace",
namespace,
...outbound && {
outbound: {
worker: {
service: outbound.service,
environment: outbound.environment
},
params: outbound.parameters?.map((p6) => ({ name: p6 }))
}
}
});
});
bindings.mtls_certificates?.forEach(({ binding, certificate_id }) => {
metadataBindings.push({
name: binding,
type: "mtls_certificate",
certificate_id
});
});
bindings.pipelines?.forEach(({ binding, pipeline }) => {
metadataBindings.push({
name: binding,
type: "pipelines",
pipeline
});
});
bindings.logfwdr?.bindings.forEach(({ name: name2, destination }) => {
metadataBindings.push({
name: name2,
type: "logfwdr",
destination
});
});
for (const [name2, source] of Object.entries(bindings.wasm_modules || {})) {
metadataBindings.push({
name: name2,
type: "wasm_module",
part: name2
});
formData.set(
name2,
new File(
[typeof source === "string" ? (0, import_node_fs15.readFileSync)(source) : source],
typeof source === "string" ? source : name2,
{
type: "application/wasm"
}
)
);
}
if (bindings.browser !== void 0) {
metadataBindings.push({
name: bindings.browser.binding,
type: "browser",
raw: bindings.browser.raw
});
}
if (bindings.ai !== void 0) {
metadataBindings.push({
name: bindings.ai.binding,
staging: bindings.ai.staging,
type: "ai",
raw: bindings.ai.raw
});
}
if (bindings.images !== void 0) {
metadataBindings.push({
name: bindings.images.binding,
type: "images",
raw: bindings.images.raw
});
}
if (bindings.version_metadata !== void 0) {
metadataBindings.push({
name: bindings.version_metadata.binding,
type: "version_metadata"
});
}
if (bindings.assets !== void 0) {
metadataBindings.push({
name: bindings.assets.binding,
type: "assets"
});
}
for (const [name2, filePath] of Object.entries(bindings.text_blobs || {})) {
metadataBindings.push({
name: name2,
type: "text_blob",
part: name2
});
if (name2 !== "__STATIC_CONTENT_MANIFEST") {
formData.set(
name2,
new File([(0, import_node_fs15.readFileSync)(filePath)], filePath, {
type: "text/plain"
})
);
}
}
for (const [name2, source] of Object.entries(bindings.data_blobs || {})) {
metadataBindings.push({
name: name2,
type: "data_blob",
part: name2
});
formData.set(
name2,
new File(
[typeof source === "string" ? (0, import_node_fs15.readFileSync)(source) : source],
typeof source === "string" ? source : name2,
{
type: "application/octet-stream"
}
)
);
}
const manifestModuleName = "__STATIC_CONTENT_MANIFEST";
const hasManifest = modules?.some(({ name: name2 }) => name2 === manifestModuleName);
if (hasManifest && main2.type === "esm") {
(0, import_node_assert14.default)(modules !== void 0);
const subDirs = new Set(
modules.map((module3) => import_node_path26.default.posix.dirname(module3.name))
);
for (const subDir of subDirs) {
if (subDir === ".") {
continue;
}
const relativePath = import_node_path26.default.posix.relative(subDir, manifestModuleName);
const filePath = import_node_path26.default.posix.join(subDir, manifestModuleName);
modules.push({
name: filePath,
filePath,
content: `export { default } from ${JSON.stringify(relativePath)};`,
type: "esm"
});
}
}
if (main2.type === "commonjs") {
for (const module3 of Object.values([...modules || []])) {
if (module3.name === "__STATIC_CONTENT_MANIFEST") {
formData.set(
module3.name,
new File([module3.content], module3.name, {
type: "text/plain"
})
);
modules = modules?.filter((m6) => m6 !== module3);
} else if (module3.type === "compiled-wasm" || module3.type === "text" || module3.type === "buffer") {
const name2 = module3.name.replace(/[^a-zA-Z0-9_$]/g, "_");
metadataBindings.push({
name: name2,
type: module3.type === "compiled-wasm" ? "wasm_module" : module3.type === "text" ? "text_blob" : "data_blob",
part: name2
});
formData.set(
name2,
new File([module3.content], module3.name, {
type: module3.type === "compiled-wasm" ? "application/wasm" : module3.type === "text" ? "text/plain" : "application/octet-stream"
})
);
modules = modules?.filter((m6) => m6 !== module3);
}
}
}
if (bindings.unsafe?.bindings) {
metadataBindings.push(...bindings.unsafe.bindings);
}
let capnpSchemaOutputFile;
if (bindings.unsafe?.capnp) {
const capnpOutput = handleUnsafeCapnp(bindings.unsafe.capnp);
capnpSchemaOutputFile = `./capnp-${Date.now()}.compiled`;
formData.set(
capnpSchemaOutputFile,
new File([capnpOutput], capnpSchemaOutputFile, {
type: "application/octet-stream"
})
);
}
let keep_bindings = void 0;
if (keepVars) {
keep_bindings ??= [];
keep_bindings.push("plain_text", "json");
}
if (keepSecrets) {
keep_bindings ??= [];
keep_bindings.push("secret_text", "secret_key");
}
if (keepBindings) {
keep_bindings ??= [];
keep_bindings.push(...keepBindings);
}
const metadata = {
...main2.type !== "commonjs" ? { main_module: main2.name } : { body_part: main2.name },
bindings: metadataBindings,
containers: worker.containers === void 0 ? void 0 : worker.containers.map((c6) => ({ class_name: c6.class_name })),
...compatibility_date && { compatibility_date },
...compatibility_flags && {
compatibility_flags
},
...migrations && { migrations },
capnp_schema: capnpSchemaOutputFile,
...keep_bindings && { keep_bindings },
...logpush !== void 0 && { logpush },
...placement && { placement },
...tail_consumers && { tail_consumers },
...limits && { limits },
...annotations && { annotations },
...keep_assets !== void 0 && { keep_assets },
...assets && {
assets: {
jwt: assets.jwt,
config: assetConfig
}
},
...observability && { observability }
};
if (bindings.unsafe?.metadata !== void 0) {
for (const key of Object.keys(bindings.unsafe.metadata)) {
metadata[key] = bindings.unsafe.metadata[key];
}
}
formData.set("metadata", JSON.stringify(metadata));
if (main2.type === "commonjs" && modules && modules.length > 0) {
throw new TypeError(
"More than one module can only be specified when type = 'esm'"
);
}
for (const module3 of [main2].concat(modules || [])) {
formData.set(
module3.name,
new File([module3.content], module3.name, {
type: toMimeType(module3.type ?? main2.type ?? "esm")
})
);
}
for (const sourceMap of sourceMaps || []) {
formData.set(
sourceMap.name,
new File([sourceMap.content], sourceMap.name, {
type: "application/source-map"
})
);
}
return formData;
}
var import_node_assert14, import_node_fs15, import_node_path26, import_undici6, moduleTypeMimeType;
var init_create_worker_upload_form = __esm({
"src/deployment-bundle/create-worker-upload-form.ts"() {
init_import_meta_url();
import_node_assert14 = __toESM(require("assert"));
import_node_fs15 = require("fs");
import_node_path26 = __toESM(require("path"));
import_undici6 = __toESM(require_undici());
init_errors();
init_bindings();
init_capnp();
moduleTypeMimeType = {
esm: "application/javascript+module",
commonjs: "application/javascript",
"compiled-wasm": "application/wasm",
buffer: "application/octet-stream",
text: "text/plain",
python: "text/x-python",
"python-requirement": "text/x-python-requirement"
};
__name(toMimeType, "toMimeType");
__name(fromMimeType, "fromMimeType");
__name(createWorkerUploadForm, "createWorkerUploadForm");
}
});
// src/deployment-bundle/node-compat.ts
function validateNodeCompatMode(compatibilityDateStr = "2000-01-01", compatibilityFlags, {
noBundle = void 0
}) {
const {
mode,
hasNodejsCompatFlag,
hasNodejsCompatV2Flag,
hasExperimentalNodejsCompatV2Flag
} = (0, import_miniflare11.getNodeCompat)(compatibilityDateStr, compatibilityFlags);
if (hasExperimentalNodejsCompatV2Flag) {
throw new UserError(
"The `experimental:` prefix on `nodejs_compat_v2` is no longer valid. Please remove it and try again."
);
}
if (hasNodejsCompatFlag && hasNodejsCompatV2Flag) {
throw new UserError(
"The `nodejs_compat` and `nodejs_compat_v2` compatibility flags cannot be used in together. Please select just one."
);
}
if (noBundle && hasNodejsCompatV2Flag) {
logger.warn(
"`nodejs_compat_v2` compatibility flag and `--no-bundle` can't be used together. If you want to polyfill Node.js built-ins and disable Wrangler's bundling, please polyfill as part of your own bundling process."
);
}
return mode;
}
var import_miniflare11;
var init_node_compat = __esm({
"src/deployment-bundle/node-compat.ts"() {
init_import_meta_url();
import_miniflare11 = require("miniflare");
init_errors();
init_logger();
__name(validateNodeCompatMode, "validateNodeCompatMode");
}
});
// src/durable.ts
async function getMigrationsToUpload(scriptName, props) {
const { config, accountId } = props;
(0, import_node_assert15.default)(accountId, "Missing accountId");
let migrations;
if (config.migrations.length > 0) {
let script;
if (props.dispatchNamespace) {
try {
const scriptData = await fetchResult(
config,
`/accounts/${accountId}/workers/dispatch/namespaces/${props.dispatchNamespace}/scripts/${scriptName}`
);
script = scriptData.script;
} catch (err) {
suppressNotFoundError(err);
}
} else {
if (!props.legacyEnv) {
try {
if (props.env) {
const scriptData = await fetchResult(
config,
`/accounts/${accountId}/workers/services/${scriptName}/environments/${props.env}`
);
script = scriptData.script;
} else {
const scriptData = await fetchResult(config, `/accounts/${accountId}/workers/services/${scriptName}`);
script = scriptData.default_environment.script;
}
} catch (err) {
suppressNotFoundError(err);
}
} else {
const scripts = await fetchResult(
config,
`/accounts/${accountId}/workers/scripts`
);
script = scripts.find(({ id }) => id === scriptName);
}
}
if (script?.migration_tag) {
const scriptMigrationTag = script.migration_tag;
const foundIndex = config.migrations.findIndex(
(migration) => migration.tag === scriptMigrationTag
);
if (foundIndex === -1) {
logger.warn(
`The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in your ${configFileName(config.configPath)} file. You may have already deleted it. Applying all available migrations to the script...`
);
migrations = {
old_tag: script.migration_tag,
new_tag: config.migrations[config.migrations.length - 1].tag,
steps: config.migrations.map(({ tag: _tag, ...rest }) => rest)
};
} else {
if (foundIndex !== config.migrations.length - 1) {
migrations = {
old_tag: script.migration_tag,
new_tag: config.migrations[config.migrations.length - 1].tag,
steps: config.migrations.slice(foundIndex + 1).map(({ tag: _tag, ...rest }) => rest)
};
}
}
} else {
migrations = {
new_tag: config.migrations[config.migrations.length - 1].tag,
steps: config.migrations.map(({ tag: _tag, ...rest }) => rest)
};
}
}
return migrations;
}
var import_node_assert15, suppressNotFoundError;
var init_durable = __esm({
"src/durable.ts"() {
init_import_meta_url();
import_node_assert15 = __toESM(require("assert"));
init_cfetch();
init_config2();
init_logger();
__name(getMigrationsToUpload, "getMigrationsToUpload");
suppressNotFoundError = /* @__PURE__ */ __name((err) => {
if (![
10090,
// corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
10092
// workers.api.error.environment_not_found, so the script wasn't published to this environment yet
].includes(err.code)) {
throw err;
}
}, "suppressNotFoundError");
}
});
// src/utils/compatibility-date.ts
function getDevCompatibilityDate(config, compatibilityDate = config.compatibility_date) {
const miniflareEntry = require.resolve("miniflare");
const miniflareRequire = import_node_module3.default.createRequire(miniflareEntry);
const miniflareWorkerd = miniflareRequire("workerd");
const workerdDate = miniflareWorkerd.compatibilityDate;
if (config.configPath !== void 0 && compatibilityDate === void 0) {
logger.warn(
`No compatibility_date was specified. Using the installed Workers runtime's latest supported date: ${workerdDate}.
\u276F\u276F Add one to your ${configFileName(config.configPath)} file: compatibility_date = "${workerdDate}", or
\u276F\u276F Pass it in your terminal: wrangler dev [<SCRIPT>] --compatibility-date=${workerdDate}
See https://developers.cloudflare.com/workers/platform/compatibility-dates/ for more information.`
);
}
return compatibilityDate ?? workerdDate;
}
function formatCompatibilityDate(date) {
return date.toISOString().slice(0, 10);
}
var import_node_module3;
var init_compatibility_date = __esm({
"src/utils/compatibility-date.ts"() {
init_import_meta_url();
import_node_module3 = __toESM(require("module"));
init_config2();
init_logger();
__name(getDevCompatibilityDate, "getDevCompatibilityDate");
__name(formatCompatibilityDate, "formatCompatibilityDate");
}
});
// src/utils/create-batches.ts
function* createBatches(array, size) {
for (let i5 = 0; i5 < array.length; i5 += size) {
yield array.slice(i5, i5 + size);
}
}
var init_create_batches = __esm({
"src/utils/create-batches.ts"() {
init_import_meta_url();
__name(createBatches, "createBatches");
}
});
// ../../node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/quote.js
var require_quote = __commonJS({
"../../node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/quote.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = /* @__PURE__ */ __name(function quote2(xs) {
return xs.map(function(s5) {
if (s5 && typeof s5 === "object") {
return s5.op.replace(/(.)/g, "\\$1");
}
if (/["\s]/.test(s5) && !/'/.test(s5)) {
return "'" + s5.replace(/(['\\])/g, "\\$1") + "'";
}
if (/["'\s]/.test(s5)) {
return '"' + s5.replace(/(["\\$`!])/g, "\\$1") + '"';
}
return String(s5).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
}).join(" ");
}, "quote");
}
});
// ../../node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/parse.js
var require_parse4 = __commonJS({
"../../node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/parse.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var CONTROL = "(?:" + [
"\\|\\|",
"\\&\\&",
";;",
"\\|\\&",
"\\<\\(",
"\\<\\<\\<",
">>",
">\\&",
"<\\&",
"[&;()|<>]"
].join("|") + ")";
var controlRE = new RegExp("^" + CONTROL + "$");
var META = "|&;()<> \\t";
var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
var hash = /^#$/;
var SQ = "'";
var DQ = '"';
var DS = "$";
var TOKEN = "";
var mult = 4294967296;
for (i5 = 0; i5 < 4; i5++) {
TOKEN += (mult * Math.random()).toString(16);
}
var i5;
var startsWithToken = new RegExp("^" + TOKEN);
function matchAll(s5, r7) {
var origIndex = r7.lastIndex;
var matches = [];
var matchObj;
while (matchObj = r7.exec(s5)) {
matches.push(matchObj);
if (r7.lastIndex === matchObj.index) {
r7.lastIndex += 1;
}
}
r7.lastIndex = origIndex;
return matches;
}
__name(matchAll, "matchAll");
function getVar(env6, pre, key) {
var r7 = typeof env6 === "function" ? env6(key) : env6[key];
if (typeof r7 === "undefined" && key != "") {
r7 = "";
} else if (typeof r7 === "undefined") {
r7 = "$";
}
if (typeof r7 === "object") {
return pre + TOKEN + JSON.stringify(r7) + TOKEN;
}
return pre + r7;
}
__name(getVar, "getVar");
function parseInternal(string, env6, opts) {
if (!opts) {
opts = {};
}
var BS = opts.escape || "\\";
var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
var chunker = new RegExp([
"(" + CONTROL + ")",
// control chars
"(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
].join("|"), "g");
var matches = matchAll(string, chunker);
if (matches.length === 0) {
return [];
}
if (!env6) {
env6 = {};
}
var commented = false;
return matches.map(function(match2) {
var s5 = match2[0];
if (!s5 || commented) {
return void 0;
}
if (controlRE.test(s5)) {
return { op: s5 };
}
var quote2 = false;
var esc = false;
var out = "";
var isGlob = false;
var i6;
function parseEnvVar() {
i6 += 1;
var varend;
var varname;
var char = s5.charAt(i6);
if (char === "{") {
i6 += 1;
if (s5.charAt(i6) === "}") {
throw new Error("Bad substitution: " + s5.slice(i6 - 2, i6 + 1));
}
varend = s5.indexOf("}", i6);
if (varend < 0) {
throw new Error("Bad substitution: " + s5.slice(i6));
}
varname = s5.slice(i6, varend);
i6 = varend;
} else if (/[*@#?$!_-]/.test(char)) {
varname = char;
i6 += 1;
} else {
var slicedFromI = s5.slice(i6);
varend = slicedFromI.match(/[^\w\d_]/);
if (!varend) {
varname = slicedFromI;
i6 = s5.length;
} else {
varname = slicedFromI.slice(0, varend.index);
i6 += varend.index - 1;
}
}
return getVar(env6, "", varname);
}
__name(parseEnvVar, "parseEnvVar");
for (i6 = 0; i6 < s5.length; i6++) {
var c6 = s5.charAt(i6);
isGlob = isGlob || !quote2 && (c6 === "*" || c6 === "?");
if (esc) {
out += c6;
esc = false;
} else if (quote2) {
if (c6 === quote2) {
quote2 = false;
} else if (quote2 == SQ) {
out += c6;
} else {
if (c6 === BS) {
i6 += 1;
c6 = s5.charAt(i6);
if (c6 === DQ || c6 === BS || c6 === DS) {
out += c6;
} else {
out += BS + c6;
}
} else if (c6 === DS) {
out += parseEnvVar();
} else {
out += c6;
}
}
} else if (c6 === DQ || c6 === SQ) {
quote2 = c6;
} else if (controlRE.test(c6)) {
return { op: s5 };
} else if (hash.test(c6)) {
commented = true;
var commentObj = { comment: string.slice(match2.index + i6 + 1) };
if (out.length) {
return [out, commentObj];
}
return [commentObj];
} else if (c6 === BS) {
esc = true;
} else if (c6 === DS) {
out += parseEnvVar();
} else {
out += c6;
}
}
if (isGlob) {
return { op: "glob", pattern: out };
}
return out;
}).reduce(function(prev, arg) {
return typeof arg === "undefined" ? prev : prev.concat(arg);
}, []);
}
__name(parseInternal, "parseInternal");
module3.exports = /* @__PURE__ */ __name(function parse7(s5, env6, opts) {
var mapped = parseInternal(s5, env6, opts);
if (typeof env6 !== "function") {
return mapped;
}
return mapped.reduce(function(acc, s6) {
if (typeof s6 === "object") {
return acc.concat(s6);
}
var xs = s6.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
if (xs.length === 1) {
return acc.concat(xs[0]);
}
return acc.concat(xs.filter(Boolean).map(function(x6) {
if (startsWithToken.test(x6)) {
return JSON.parse(x6.split(TOKEN)[1]);
}
return x6;
}));
}, []);
}, "parse");
}
});
// ../../node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/index.js
var require_shell_quote = __commonJS({
"../../node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/index.js"(exports2) {
"use strict";
init_import_meta_url();
exports2.quote = require_quote();
exports2.parse = require_parse4();
}
});
// src/utils/shell-quote.ts
function parse4(cmd, env6) {
if (process.platform === "win32") {
cmd = cmd.replaceAll("\\", "\\\\");
}
const entries = import_shell_quote.default.parse(cmd, env6);
const argv = [];
for (const entry of entries) {
if (typeof entry === "string") {
argv.push(entry);
continue;
}
if ("comment" in entry) {
continue;
}
if (entry.op === "glob") {
argv.push(entry.pattern);
continue;
}
throw new Error(
`Only simple commands are supported, please don't use the "${entry.op}" operator in "${cmd}".`
);
}
return argv;
}
var import_shell_quote, quote;
var init_shell_quote = __esm({
"src/utils/shell-quote.ts"() {
init_import_meta_url();
import_shell_quote = __toESM(require_shell_quote());
quote = /* @__PURE__ */ __name(function(args) {
const stringArgs = args.map((arg) => String(arg));
return import_shell_quote.default.quote(stringArgs);
}, "quote");
__name(parse4, "parse");
}
});
// src/init.ts
function isNpm(packageManager) {
return packageManager.type === "npm";
}
async function downloadWorkerConfig(accountId, workerName, entrypoint, serviceEnvironment) {
const [
bindings,
routes,
customDomains,
workersDev,
serviceEnvMetadata,
cronTriggers
] = await Promise.all([
fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${workerName}/environments/${serviceEnvironment}/bindings`
),
fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${workerName}/environments/${serviceEnvironment}/routes?show_zonename=true`
),
fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/domains/records?page=0&per_page=5&service=${workerName}&environment=${serviceEnvironment}`
),
fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${workerName}/environments/${serviceEnvironment}/subdomain`
),
fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${workerName}/environments/${serviceEnvironment}`
),
fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/scripts/${workerName}/schedules`
)
]).catch((e7) => {
throw new Error(
`Error Occurred ${e7}: Unable to fetch bindings, routes, or services metadata from the dashboard. Please try again later.`
);
});
const mappedBindings = await mapBindings(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
accountId,
bindings
);
const durableObjectClassNames = bindings.filter((binding) => binding.type === "durable_object_namespace").map(
(durableObject) => durableObject.class_name
);
const allRoutes = [
...routes.map(
(r7) => ({ pattern: r7.pattern, zone_name: r7.zone_name })
),
...customDomains.map(
(c6) => ({
pattern: c6.hostname,
zone_name: c6.zone_name,
custom_domain: true
})
)
];
return {
name: workerName,
main: entrypoint,
workers_dev: workersDev.enabled,
compatibility_date: serviceEnvMetadata.script.compatibility_date ?? formatCompatibilityDate(/* @__PURE__ */ new Date()),
compatibility_flags: serviceEnvMetadata.script.compatibility_flags,
...allRoutes.length ? { routes: allRoutes } : {},
placement: serviceEnvMetadata.script.placement_mode === "smart" ? { mode: "smart" } : void 0,
limits: serviceEnvMetadata.script.limits,
...durableObjectClassNames.length ? {
migrations: [
{
tag: serviceEnvMetadata.script.migration_tag,
new_classes: durableObjectClassNames
}
]
} : {},
...cronTriggers.schedules.length ? {
triggers: {
crons: cronTriggers.schedules.map((scheduled) => scheduled.cron)
}
} : {},
tail_consumers: serviceEnvMetadata.script.tail_consumers ?? void 0,
observability: serviceEnvMetadata.script.observability,
...mappedBindings
};
}
async function mapBindings(complianceConfig, accountId, bindings) {
const d1BindingsWithInfo = {};
await Promise.all(
bindings.filter((binding) => binding.type === "d1").map(async (binding) => {
const dbInfo = await getDatabaseInfoFromIdOrName(
complianceConfig,
accountId,
binding.id
);
d1BindingsWithInfo[binding.id] = dbInfo;
})
);
return bindings.filter((binding) => binding.type !== "secret_text").reduce((configObj, binding) => {
switch (binding.type) {
case "plain_text":
{
configObj.vars = {
...configObj.vars ?? {},
[binding.name]: binding.text
};
}
break;
case "json":
{
configObj.vars = {
...configObj.vars ?? {},
name: binding.name,
json: binding.json
};
}
break;
case "kv_namespace":
{
configObj.kv_namespaces = [
...configObj.kv_namespaces ?? [],
{ id: binding.namespace_id, binding: binding.name }
];
}
break;
case "durable_object_namespace":
{
configObj.durable_objects = {
bindings: [
...configObj.durable_objects?.bindings ?? [],
{
name: binding.name,
class_name: binding.class_name,
script_name: binding.script_name,
environment: binding.environment
}
]
};
}
break;
case "d1":
{
configObj.d1_databases = [
...configObj.d1_databases ?? [],
{
binding: binding.name,
database_id: binding.id,
database_name: d1BindingsWithInfo[binding.id].name
}
];
}
break;
case "browser":
{
configObj.browser = {
binding: binding.name
};
}
break;
case "ai":
{
configObj.ai = {
binding: binding.name
};
}
break;
case "images":
{
configObj.images = {
binding: binding.name
};
}
break;
case "r2_bucket":
{
configObj.r2_buckets = [
...configObj.r2_buckets ?? [],
{
binding: binding.name,
bucket_name: binding.bucket_name,
jurisdiction: binding.jurisdiction
}
];
}
break;
case "secrets_store_secret":
{
configObj.secrets_store_secrets = [
...configObj.secrets_store_secrets ?? [],
{
binding: binding.name,
store_id: binding.store_id,
secret_name: binding.secret_name
}
];
}
break;
case "unsafe_hello_world": {
configObj.unsafe_hello_world = [
...configObj.unsafe_hello_world ?? [],
{
binding: binding.name,
enable_timer: binding.enable_timer
}
];
break;
}
case "service":
{
configObj.services = [
...configObj.services ?? [],
{
binding: binding.name,
service: binding.service,
environment: binding.environment,
entrypoint: binding.entrypoint
}
];
}
break;
case "analytics_engine":
{
configObj.analytics_engine_datasets = [
...configObj.analytics_engine_datasets ?? [],
{ binding: binding.name, dataset: binding.dataset }
];
}
break;
case "dispatch_namespace":
{
configObj.dispatch_namespaces = [
...configObj.dispatch_namespaces ?? [],
{
binding: binding.name,
namespace: binding.namespace,
...binding.outbound && {
outbound: {
service: binding.outbound.worker.service,
environment: binding.outbound.worker.environment,
parameters: binding.outbound.params?.map((p6) => p6.name) ?? []
}
}
}
];
}
break;
case "logfwdr":
{
configObj.logfwdr = {
bindings: [
...configObj.logfwdr?.bindings ?? [],
{ name: binding.name, destination: binding.destination }
]
};
}
break;
case "wasm_module":
{
configObj.wasm_modules = {
...configObj.wasm_modules ?? {},
[binding.name]: binding.part
};
}
break;
case "text_blob":
{
configObj.text_blobs = {
...configObj.text_blobs ?? {},
[binding.name]: binding.part
};
}
break;
case "data_blob":
{
configObj.data_blobs = {
...configObj.data_blobs ?? {},
[binding.name]: binding.part
};
}
break;
case "secret_text":
break;
case "version_metadata": {
{
configObj.version_metadata = {
binding: binding.name
};
}
break;
}
case "send_email": {
configObj.send_email = [
...configObj.send_email ?? [],
{
name: binding.name,
destination_address: binding.destination_address,
allowed_destination_addresses: binding.allowed_destination_addresses
}
];
break;
}
case "queue":
configObj.queues ??= { producers: [] };
configObj.queues.producers = [
...configObj.queues.producers ?? [],
{
binding: binding.name,
queue: binding.queue_name,
delivery_delay: binding.delivery_delay
}
];
break;
case "vectorize":
configObj.vectorize = [
...configObj.vectorize ?? [],
{
binding: binding.name,
index_name: binding.index_name
}
];
break;
case "hyperdrive":
configObj.hyperdrive = [
...configObj.hyperdrive ?? [],
{
binding: binding.name,
id: binding.id
}
];
break;
case "mtls_certificate":
configObj.mtls_certificates = [
...configObj.mtls_certificates ?? [],
{
binding: binding.name,
certificate_id: binding.certificate_id
}
];
break;
case "pipelines":
configObj.pipelines = [
...configObj.pipelines ?? [],
{
binding: binding.name,
pipeline: binding.pipeline
}
];
break;
case "assets":
throw new FatalError(
"`wrangler init --from-dash` is not yet supported for Workers with Assets"
);
case "inherit":
configObj.unsafe = {
bindings: [...configObj.unsafe?.bindings ?? [], binding],
metadata: configObj.unsafe?.metadata ?? void 0
};
break;
case "workflow":
{
configObj.workflows = [
...configObj.workflows ?? [],
{
binding: binding.name,
name: binding.workflow_name,
class_name: binding.class_name,
script_name: binding.script_name
}
];
}
break;
default: {
configObj.unsafe = {
bindings: [...configObj.unsafe?.bindings ?? [], binding],
metadata: configObj.unsafe?.metadata ?? void 0
};
assertNever(binding);
}
}
return configObj;
}, {});
}
async function downloadWorker(accountId, workerName) {
const serviceMetadata = await fetchResult(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${workerName}`
);
const defaultEnvironment = serviceMetadata.default_environment.environment;
const { entrypoint, modules } = await fetchWorkerDefinitionFromDash(
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${workerName}/environments/${defaultEnvironment}/content/v2`
);
const config = await downloadWorkerConfig(
accountId,
workerName,
entrypoint,
defaultEnvironment
);
return {
modules,
config
};
}
var import_promises9, import_node_path27, import_toml5, init;
var init_init = __esm({
"src/init.ts"() {
init_import_meta_url();
import_promises9 = require("fs/promises");
import_node_path27 = __toESM(require("path"));
import_toml5 = __toESM(require_toml());
init_execa();
init_utils2();
init_cfetch();
init_internal();
init_create_command();
init_utils3();
init_misc_variables();
init_errors();
init_logger();
init_metrics_config();
init_package_manager();
init_user2();
init_compatibility_date();
init_create_batches();
init_shell_quote();
init = createCommand({
metadata: {
description: "\u{1F4E5} Initialize a basic Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
args: {
name: {
describe: "The name of your worker",
type: "string"
},
yes: {
describe: 'Answer "yes" to any prompts for new projects',
type: "boolean",
alias: "y"
},
"from-dash": {
describe: "The name of the Worker you wish to download from the Cloudflare dashboard for local development.",
type: "string",
requiresArg: true
},
"delegate-c3": {
describe: "Delegate to Create Cloudflare CLI (C3)",
type: "boolean",
hidden: true,
default: true,
alias: "c3"
}
},
behaviour: {
provideConfig: false
},
positionalArgs: ["name"],
async handler(args) {
const yesFlag = args.yes ?? false;
const packageManager = await getPackageManager();
const name2 = args.fromDash ?? args.name;
const c3Arguments = [
...parse4(getC3CommandFromEnv()),
...name2 ? [name2] : [],
...yesFlag && isNpm(packageManager) ? ["-y"] : [],
// --yes arg for npx
...isNpm(packageManager) ? ["--"] : [],
...args.fromDash ? ["--existing-script", args.fromDash] : [],
...yesFlag ? ["--wrangler-defaults"] : []
];
const replacementC3Command = `\`${packageManager.type} ${c3Arguments.join(
" "
)}\``;
if (args.fromDash && !args.delegateC3) {
const accountId = await requireAuth({});
try {
await fetchResult(
// `wrangler init` is not run from within a Workers project, so there will be no config file to define the compliance region.
COMPLIANCE_REGION_CONFIG_UNKNOWN,
`/accounts/${accountId}/workers/services/${args.fromDash}`
);
} catch (err) {
if (err.code === 10090) {
throw new UserError(
"wrangler couldn't find a Worker with that name in your account.\nRun `wrangler whoami` to confirm you're logged into the correct account.",
{
telemetryMessage: true
}
);
}
throw err;
}
const creationDir = import_node_path27.default.join(process.cwd(), args.fromDash);
await (0, import_promises9.mkdir)(creationDir, { recursive: true });
const { modules, config } = await downloadWorker(
accountId,
args.fromDash
);
await (0, import_promises9.mkdir)(import_node_path27.default.join(creationDir, "./src"), {
recursive: true
});
config.main = `src/${config.main}`;
config.name = args.fromDash;
for (const files of createBatches(modules, 10)) {
await Promise.all(
files.map(async (file) => {
const filepath = import_node_path27.default.join(creationDir, `./src/${file.name}`);
const directory = (0, import_node_path27.dirname)(filepath);
await (0, import_promises9.mkdir)(directory, { recursive: true });
await (0, import_promises9.writeFile)(filepath, file.stream());
})
);
}
await (0, import_promises9.writeFile)(
import_node_path27.default.join(creationDir, "wrangler.toml"),
import_toml5.default.stringify(config)
);
} else {
logger.log(`\u{1F300} Running ${replacementC3Command}...`);
const metricsConfig = readMetricsConfig();
await execa(packageManager.type, c3Arguments, {
stdio: "inherit",
...metricsConfig.permission?.enabled === false && {
env: { CREATE_CLOUDFLARE_TELEMETRY_DISABLED: "1" }
}
});
}
}
});
__name(isNpm, "isNpm");
__name(downloadWorkerConfig, "downloadWorkerConfig");
__name(mapBindings, "mapBindings");
__name(downloadWorker, "downloadWorker");
}
});
// ../../node_modules/.pnpm/xxhash-wasm@1.0.1/node_modules/xxhash-wasm/esm/xxhash-wasm.js
async function e() {
const { instance: { exports: { mem: e7, xxh32: n6, xxh64: r7, init32: i5, update32: o5, digest32: h6, init64: s5, update64: u5, digest64: g6 } } } = await WebAssembly.instantiate(t);
let a5 = new Uint8Array(e7.buffer);
function c6(t7, n7) {
if (e7.buffer.byteLength < t7 + n7) {
const r8 = Math.ceil((t7 + n7 - e7.buffer.byteLength) / 65536);
e7.grow(r8), a5 = new Uint8Array(e7.buffer);
}
}
__name(c6, "c");
function l6(t7, e8, n7, r8, i6, o6) {
c6(t7);
const h7 = new Uint8Array(t7);
return a5.set(h7), n7(0, e8), h7.set(a5.slice(0, t7)), { update(e9) {
let n8;
return a5.set(h7), "string" == typeof e9 ? (c6(3 * e9.length, t7), n8 = b6.encodeInto(e9, a5.subarray(t7)).written) : (c6(e9.byteLength, t7), a5.set(e9, t7), n8 = e9.byteLength), r8(0, t7, n8), h7.set(a5.slice(0, t7)), this;
}, digest: /* @__PURE__ */ __name(() => (a5.set(h7), o6(i6(0))), "digest") };
}
__name(l6, "l");
function d6(t7) {
return t7 >>> 0;
}
__name(d6, "d");
const f6 = 2n ** 64n - 1n;
function y4(t7) {
return t7 & f6;
}
__name(y4, "y");
const b6 = new TextEncoder(), w6 = 0n;
function p6(t7) {
let e8 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return c6(3 * t7.length, 0), d6(n6(0, b6.encodeInto(t7, a5).written, e8));
}
__name(p6, "p");
function v7(t7) {
let e8 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : w6;
return c6(3 * t7.length, 0), y4(r7(0, b6.encodeInto(t7, a5).written, e8));
}
__name(v7, "v");
return { h32: p6, h32ToString(t7) {
return p6(t7, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0).toString(16).padStart(8, "0");
}, h32Raw(t7) {
let e8 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return c6(t7.byteLength, 0), a5.set(t7), d6(n6(0, t7.byteLength, e8));
}, create32() {
return l6(48, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0, i5, o5, h6, d6);
}, h64: v7, h64ToString(t7) {
return v7(t7, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : w6).toString(16).padStart(16, "0");
}, h64Raw(t7) {
let e8 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : w6;
return c6(t7.byteLength, 0), a5.set(t7), y4(r7(0, t7.byteLength, e8));
}, create64() {
return l6(88, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : w6, s5, u5, g6, y4);
} };
}
var t;
var init_xxhash_wasm = __esm({
"../../node_modules/.pnpm/xxhash-wasm@1.0.1/node_modules/xxhash-wasm/esm/xxhash-wasm.js"() {
init_import_meta_url();
t = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 48, 8, 96, 3, 127, 127, 127, 0, 96, 3, 127, 127, 127, 1, 127, 96, 2, 127, 127, 0, 96, 2, 127, 126, 0, 96, 1, 127, 1, 127, 96, 1, 127, 1, 126, 96, 3, 127, 127, 126, 1, 126, 96, 3, 126, 127, 127, 1, 126, 3, 11, 10, 1, 1, 2, 0, 4, 6, 7, 3, 0, 5, 5, 3, 1, 0, 1, 7, 85, 9, 3, 109, 101, 109, 2, 0, 5, 120, 120, 104, 51, 50, 0, 0, 6, 105, 110, 105, 116, 51, 50, 0, 2, 8, 117, 112, 100, 97, 116, 101, 51, 50, 0, 3, 8, 100, 105, 103, 101, 115, 116, 51, 50, 0, 4, 5, 120, 120, 104, 54, 52, 0, 5, 6, 105, 110, 105, 116, 54, 52, 0, 7, 8, 117, 112, 100, 97, 116, 101, 54, 52, 0, 8, 8, 100, 105, 103, 101, 115, 116, 54, 52, 0, 9, 10, 211, 23, 10, 242, 1, 1, 4, 127, 32, 0, 32, 1, 106, 33, 3, 32, 1, 65, 16, 79, 4, 127, 32, 3, 65, 16, 107, 33, 6, 32, 2, 65, 168, 136, 141, 161, 2, 106, 33, 3, 32, 2, 65, 247, 148, 175, 175, 120, 106, 33, 4, 32, 2, 65, 177, 243, 221, 241, 121, 107, 33, 5, 3, 64, 32, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 3, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 3, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 4, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 2, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 5, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 5, 32, 0, 65, 4, 106, 34, 0, 32, 6, 77, 13, 0, 11, 32, 2, 65, 12, 119, 32, 5, 65, 18, 119, 106, 32, 4, 65, 7, 119, 106, 32, 3, 65, 1, 119, 106, 5, 32, 2, 65, 177, 207, 217, 178, 1, 106, 11, 32, 1, 106, 32, 0, 32, 1, 65, 15, 113, 16, 1, 11, 146, 1, 0, 32, 1, 32, 2, 106, 33, 2, 3, 64, 32, 1, 65, 4, 106, 32, 2, 75, 69, 4, 64, 32, 1, 40, 2, 0, 65, 189, 220, 202, 149, 124, 108, 32, 0, 106, 65, 17, 119, 65, 175, 214, 211, 190, 2, 108, 33, 0, 32, 1, 65, 4, 106, 33, 1, 12, 1, 11, 11, 3, 64, 32, 1, 32, 2, 79, 69, 4, 64, 32, 1, 45, 0, 0, 65, 177, 207, 217, 178, 1, 108, 32, 0, 106, 65, 11, 119, 65, 177, 243, 221, 241, 121, 108, 33, 0, 32, 1, 65, 1, 106, 33, 1, 12, 1, 11, 11, 32, 0, 65, 15, 118, 32, 0, 115, 65, 247, 148, 175, 175, 120, 108, 34, 0, 32, 0, 65, 13, 118, 115, 65, 189, 220, 202, 149, 124, 108, 34, 0, 32, 0, 65, 16, 118, 115, 11, 63, 0, 32, 0, 65, 8, 106, 32, 1, 65, 168, 136, 141, 161, 2, 106, 54, 2, 0, 32, 0, 65, 12, 106, 32, 1, 65, 247, 148, 175, 175, 120, 106, 54, 2, 0, 32, 0, 65, 16, 106, 32, 1, 54, 2, 0, 32, 0, 65, 20, 106, 32, 1, 65, 177, 243, 221, 241, 121, 107, 54, 2, 0, 11, 211, 4, 1, 6, 127, 32, 1, 32, 2, 106, 33, 6, 32, 0, 65, 24, 106, 33, 5, 32, 0, 65, 40, 106, 40, 2, 0, 33, 3, 32, 0, 32, 0, 40, 2, 0, 32, 2, 106, 54, 2, 0, 32, 0, 65, 4, 106, 34, 4, 32, 4, 40, 2, 0, 32, 2, 65, 16, 79, 32, 0, 40, 2, 0, 65, 16, 79, 114, 114, 54, 2, 0, 32, 2, 32, 3, 106, 65, 16, 73, 4, 64, 32, 3, 32, 5, 106, 32, 1, 32, 2, 252, 10, 0, 0, 32, 0, 65, 40, 106, 32, 2, 32, 3, 106, 54, 2, 0, 15, 11, 32, 3, 4, 64, 32, 3, 32, 5, 106, 32, 1, 65, 16, 32, 3, 107, 34, 2, 252, 10, 0, 0, 32, 0, 65, 8, 106, 34, 3, 40, 2, 0, 32, 5, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 12, 106, 34, 3, 40, 2, 0, 32, 5, 65, 4, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 16, 106, 34, 3, 40, 2, 0, 32, 5, 65, 8, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 20, 106, 34, 3, 40, 2, 0, 32, 5, 65, 12, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 40, 106, 65, 0, 54, 2, 0, 32, 1, 32, 2, 106, 33, 1, 11, 32, 1, 32, 6, 65, 16, 107, 77, 4, 64, 32, 6, 65, 16, 107, 33, 8, 32, 0, 65, 8, 106, 40, 2, 0, 33, 2, 32, 0, 65, 12, 106, 40, 2, 0, 33, 3, 32, 0, 65, 16, 106, 40, 2, 0, 33, 4, 32, 0, 65, 20, 106, 40, 2, 0, 33, 7, 3, 64, 32, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 2, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 3, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 3, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 4, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 7, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 7, 32, 1, 65, 4, 106, 34, 1, 32, 8, 77, 13, 0, 11, 32, 0, 65, 8, 106, 32, 2, 54, 2, 0, 32, 0, 65, 12, 106, 32, 3, 54, 2, 0, 32, 0, 65, 16, 106, 32, 4, 54, 2, 0, 32, 0, 65, 20, 106, 32, 7, 54, 2, 0, 11, 32, 1, 32, 6, 73, 4, 64, 32, 5, 32, 1, 32, 6, 32, 1, 107, 34, 1, 252, 10, 0, 0, 32, 0, 65, 40, 106, 32, 1, 54, 2, 0, 11, 11, 97, 1, 1, 127, 32, 0, 65, 16, 106, 40, 2, 0, 33, 1, 32, 0, 65, 4, 106, 40, 2, 0, 4, 127, 32, 1, 65, 12, 119, 32, 0, 65, 20, 106, 40, 2, 0, 65, 18, 119, 106, 32, 0, 65, 12, 106, 40, 2, 0, 65, 7, 119, 106, 32, 0, 65, 8, 106, 40, 2, 0, 65, 1, 119, 106, 5, 32, 1, 65, 177, 207, 217, 178, 1, 106, 11, 32, 0, 40, 2, 0, 106, 32, 0, 65, 24, 106, 32, 0, 65, 40, 106, 40, 2, 0, 16, 1, 11, 157, 4, 2, 1, 127, 3, 126, 32, 0, 32, 1, 106, 33, 3, 32, 1, 65, 32, 79, 4, 126, 32, 3, 65, 32, 107, 33, 3, 32, 2, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 124, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 33, 4, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 33, 5, 32, 2, 66, 0, 124, 33, 6, 32, 2, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 125, 33, 2, 3, 64, 32, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 4, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 4, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 5, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 5, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 6, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 2, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 0, 65, 8, 106, 34, 0, 32, 3, 77, 13, 0, 11, 32, 6, 66, 12, 137, 32, 2, 66, 18, 137, 124, 32, 5, 66, 7, 137, 124, 32, 4, 66, 1, 137, 124, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 6, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 5, 32, 2, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 1, 173, 124, 32, 0, 32, 1, 65, 31, 113, 16, 6, 11, 137, 2, 0, 32, 1, 32, 2, 106, 33, 2, 3, 64, 32, 1, 65, 8, 106, 32, 2, 77, 4, 64, 32, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 32, 0, 133, 66, 27, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 33, 0, 32, 1, 65, 8, 106, 33, 1, 12, 1, 11, 11, 32, 1, 65, 4, 106, 32, 2, 77, 4, 64, 32, 1, 53, 2, 0, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 32, 0, 133, 66, 23, 137, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 124, 33, 0, 32, 1, 65, 4, 106, 33, 1, 11, 3, 64, 32, 1, 32, 2, 73, 4, 64, 32, 1, 49, 0, 0, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 126, 32, 0, 133, 66, 11, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 0, 32, 1, 65, 1, 106, 33, 1, 12, 1, 11, 11, 32, 0, 66, 33, 136, 32, 0, 133, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 34, 0, 32, 0, 66, 29, 136, 133, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 126, 34, 0, 32, 0, 66, 32, 136, 133, 11, 88, 0, 32, 0, 65, 8, 106, 32, 1, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 124, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 55, 3, 0, 32, 0, 65, 16, 106, 32, 1, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 55, 3, 0, 32, 0, 65, 24, 106, 32, 1, 55, 3, 0, 32, 0, 65, 32, 106, 32, 1, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 125, 55, 3, 0, 11, 132, 5, 2, 3, 127, 4, 126, 32, 1, 32, 2, 106, 33, 5, 32, 0, 65, 40, 106, 33, 4, 32, 0, 65, 200, 0, 106, 40, 2, 0, 33, 3, 32, 0, 32, 0, 41, 3, 0, 32, 2, 173, 124, 55, 3, 0, 32, 2, 32, 3, 106, 65, 32, 73, 4, 64, 32, 3, 32, 4, 106, 32, 1, 32, 2, 252, 10, 0, 0, 32, 0, 65, 200, 0, 106, 32, 2, 32, 3, 106, 54, 2, 0, 15, 11, 32, 3, 4, 64, 32, 3, 32, 4, 106, 32, 1, 65, 32, 32, 3, 107, 34, 2, 252, 10, 0, 0, 32, 0, 65, 8, 106, 34, 3, 41, 3, 0, 32, 4, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 16, 106, 34, 3, 41, 3, 0, 32, 4, 65, 8, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 24, 106, 34, 3, 41, 3, 0, 32, 4, 65, 16, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 32, 106, 34, 3, 41, 3, 0, 32, 4, 65, 24, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 200, 0, 106, 65, 0, 54, 2, 0, 32, 1, 32, 2, 106, 33, 1, 11, 32, 1, 65, 32, 106, 32, 5, 77, 4, 64, 32, 5, 65, 32, 107, 33, 2, 32, 0, 65, 8, 106, 41, 3, 0, 33, 6, 32, 0, 65, 16, 106, 41, 3, 0, 33, 7, 32, 0, 65, 24, 106, 41, 3, 0, 33, 8, 32, 0, 65, 32, 106, 41, 3, 0, 33, 9, 3, 64, 32, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 6, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 7, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 7, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 8, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 8, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 9, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 9, 32, 1, 65, 8, 106, 34, 1, 32, 2, 77, 13, 0, 11, 32, 0, 65, 8, 106, 32, 6, 55, 3, 0, 32, 0, 65, 16, 106, 32, 7, 55, 3, 0, 32, 0, 65, 24, 106, 32, 8, 55, 3, 0, 32, 0, 65, 32, 106, 32, 9, 55, 3, 0, 11, 32, 1, 32, 5, 73, 4, 64, 32, 4, 32, 1, 32, 5, 32, 1, 107, 34, 1, 252, 10, 0, 0, 32, 0, 65, 200, 0, 106, 32, 1, 54, 2, 0, 11, 11, 200, 2, 1, 5, 126, 32, 0, 65, 24, 106, 41, 3, 0, 33, 1, 32, 0, 41, 3, 0, 34, 2, 66, 32, 90, 4, 126, 32, 0, 65, 8, 106, 41, 3, 0, 34, 3, 66, 1, 137, 32, 0, 65, 16, 106, 41, 3, 0, 34, 4, 66, 7, 137, 124, 32, 1, 66, 12, 137, 32, 0, 65, 32, 106, 41, 3, 0, 34, 5, 66, 18, 137, 124, 124, 32, 3, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 1, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 5, 32, 1, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 2, 124, 32, 0, 65, 40, 106, 32, 2, 66, 31, 131, 167, 16, 6, 11]);
__name(e, "e");
}
});
// src/sites.ts
async function* getFilesInFolder(dirPath) {
const files = await (0, import_promises10.readdir)(dirPath, { withFileTypes: true });
for (const file of files) {
if (ALWAYS_IGNORE.has(file.name)) {
continue;
}
if (file.name.startsWith(".") && !HIDDEN_FILES_TO_INCLUDE.has(file.name)) {
continue;
}
if (file.isDirectory()) {
yield* await getFilesInFolder(path30.join(dirPath, file.name));
} else {
yield path30.join(dirPath, file.name);
}
}
}
function hashFileContent(hasher, content) {
return hasher.h64ToString(content).substring(0, 10);
}
function hashAsset(hasher, filePath, content) {
const extName = path30.extname(filePath) || "";
const baseName = path30.basename(filePath, extName);
const directory = path30.dirname(filePath);
const hash = hashFileContent(hasher, content);
return urlSafe(path30.join(directory, `${baseName}.${hash}${extName}`));
}
async function createKVNamespaceIfNotAlreadyExisting(complianceConfig, title, accountId) {
const namespaces = await listKVNamespaces(complianceConfig, accountId);
const found = namespaces.find((ns) => ns.title === title);
if (found) {
return { created: false, id: found.id };
}
const id = await createKVNamespace(complianceConfig, accountId, title);
logger.log(`\u{1F300} Created namespace for Workers Site "${title}"`);
return {
created: true,
id
};
}
function pluralise(count) {
return count === 1 ? "" : "s";
}
async function syncWorkersSite(complianceConfig, accountId, scriptName, siteAssets, preview, dryRun, oldAssetTTL) {
if (siteAssets === void 0) {
return { manifest: void 0, namespace: void 0 };
}
if (dryRun) {
logger.log("(Note: doing a dry run, not uploading or deleting anything.)");
return { manifest: void 0, namespace: void 0 };
}
(0, import_node_assert16.default)(accountId, "Missing accountId");
const title = `__${scriptName}-workers_sites_assets${preview ? "_preview" : ""}`;
const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
complianceConfig,
title,
accountId
);
logger.info("Fetching list of already uploaded assets...");
const namespaceKeysResponse = await listKVNamespaceKeys(
complianceConfig,
accountId,
namespace
);
const namespaceKeyInfoMap = new Map(namespaceKeysResponse.map((x6) => [x6.name, x6]));
const namespaceKeys = new Set(namespaceKeysResponse.map((x6) => x6.name));
const assetDirectory = path30.join(
siteAssets.baseDirectory,
siteAssets.assetDirectory
);
const include = createPatternMatcher(siteAssets.includePatterns, false);
const exclude2 = createPatternMatcher(siteAssets.excludePatterns, true);
const hasher = await e();
const manifest = {};
const uploadBuckets = [];
let uploadBucket = [];
let uploadBucketSize = 0;
let uploadCount = 0;
let skipCount = 0;
let diffCount = 0;
function logDiff(line) {
const level = logger.loggerLevel;
if (LOGGER_LEVELS[level] >= LOGGER_LEVELS.debug) {
logger.debug(line);
} else if (diffCount < MAX_DIFF_LINES) {
logger.info(line);
} else if (diffCount === MAX_DIFF_LINES) {
const msg = " (truncating changed assets log, set `WRANGLER_LOG=debug` environment variable to see full diff)";
logger.info(source_default.dim(msg));
}
diffCount++;
}
__name(logDiff, "logDiff");
logger.info("Building list of assets to upload...");
for await (const absAssetFile of getFilesInFolder(assetDirectory)) {
const assetFile = path30.relative(assetDirectory, absAssetFile);
if (!include(assetFile) || exclude2(assetFile)) {
continue;
}
const content = await (0, import_promises10.readFile)(absAssetFile, "base64");
const assetSize = Buffer.byteLength(content);
await validateAssetSize(absAssetFile, assetFile);
const assetKey = hashAsset(hasher, assetFile, content);
validateAssetKey(assetKey);
if (!namespaceKeys.has(assetKey)) {
logDiff(
source_default.green(` + ${assetKey} (uploading new version of ${assetFile})`)
);
if (uploadBucketSize + assetSize > MAX_BUCKET_SIZE2 || uploadBucket.length + 1 > MAX_BUCKET_KEYS) {
uploadBuckets.push(uploadBucket);
uploadBucketSize = 0;
uploadBucket = [];
}
uploadBucketSize += assetSize;
uploadBucket.push([absAssetFile, assetKey]);
uploadCount++;
} else {
logDiff(source_default.dim(` = ${assetKey} (already uploaded ${assetFile})`));
skipCount++;
}
namespaceKeys.delete(assetKey);
const manifestKey = urlSafe(path30.relative(assetDirectory, absAssetFile));
manifest[manifestKey] = assetKey;
}
if (uploadBucket.length > 0) {
uploadBuckets.push(uploadBucket);
}
for (const key of namespaceKeys) {
logDiff(
source_default.red(` - ${key} (${oldAssetTTL ? "expiring" : "removing"} as stale)`)
);
}
if (uploadCount > 0) {
const s5 = pluralise(uploadCount);
logger.info(`Uploading ${formatNumber(uploadCount)} new asset${s5}...`);
}
if (skipCount > 0) {
const s5 = pluralise(skipCount);
logger.info(
`Skipped uploading ${formatNumber(skipCount)} existing asset${s5}.`
);
}
let uploadedCount = 0;
const controller = new AbortController();
const uploaders = Array.from(Array(MAX_BATCH_OPERATIONS)).map(async () => {
while (!controller.signal.aborted) {
const nextBucket = uploadBuckets.shift();
if (nextBucket === void 0) {
break;
}
const bucket = [];
for (const [absAssetFile, assetKey] of nextBucket) {
bucket.push({
key: assetKey,
value: await (0, import_promises10.readFile)(absAssetFile, "base64"),
base64: true
});
if (controller.signal.aborted) {
break;
}
}
try {
await putKVBulkKeyValue(
complianceConfig,
accountId,
namespace,
bucket,
/* quiet */
true,
controller.signal
);
} catch (e7) {
if (typeof e7 === "object" && e7 !== null && "name" in e7 && e7.name === "AbortError") {
break;
}
throw e7;
}
if (controller.signal.aborted) {
break;
}
uploadedCount += nextBucket.length;
const percent = Math.floor(100 * uploadedCount / uploadCount);
logger.info(
`Uploaded ${percent}% [${formatNumber(
uploadedCount
)} out of ${formatNumber(uploadCount)}]`
);
}
});
try {
await Promise.all(uploaders);
} catch (e7) {
logger.info(`Upload failed, aborting...`);
controller.abort();
throw e7;
}
const deleteCount = namespaceKeys.size;
if (deleteCount > 0) {
const s5 = pluralise(deleteCount);
logger.info(
`${oldAssetTTL ? "Expiring" : "Removing"} ${formatNumber(
deleteCount
)} stale asset${s5}...`
);
if (!oldAssetTTL) {
await deleteKVBulkKeyValue(
complianceConfig,
accountId,
namespace,
Array.from(namespaceKeys)
);
} else {
for (const namespaceKey of namespaceKeys) {
const expiration = namespaceKeyInfoMap.get(namespaceKey)?.expiration;
logger.info(
` - ${namespaceKey} ${expiration ? `(already expiring at ${expiration})` : ""}`
);
if (expiration) {
continue;
}
const currentValue = await getKVKeyValue(
complianceConfig,
accountId,
namespace,
namespaceKey
);
await putKVKeyValue(complianceConfig, accountId, namespace, {
key: namespaceKey,
value: Buffer.from(currentValue),
expiration_ttl: oldAssetTTL
});
}
}
}
logger.log("\u2197\uFE0F Done syncing assets");
return { manifest, namespace };
}
async function validateAssetSize(absFilePath, relativeFilePath) {
const { size } = await (0, import_promises10.stat)(absFilePath);
if (size > 25 * 1024 * 1024) {
throw new UserError(
`File ${relativeFilePath} is too big, it should be under 25 MiB. See https://developers.cloudflare.com/workers/platform/limits#kv-limits`
);
}
}
function validateAssetKey(assetKey) {
if (assetKey.length > 512) {
throw new UserError(
`The asset path key "${assetKey}" exceeds the maximum key size limit of 512. See https://developers.cloudflare.com/workers/platform/limits#kv-limits",`
);
}
}
function urlSafe(filePath) {
return filePath.replace(/\\/g, "/");
}
function getSiteAssetPaths(config, assetDirectory, includePatterns = config.site?.include ?? [], excludePatterns = config.site?.exclude ?? []) {
const baseDirectory = assetDirectory ? process.cwd() : path30.resolve(path30.dirname(config.configPath ?? "wrangler.toml"));
assetDirectory ??= config.site?.bucket;
if (assetDirectory) {
return {
baseDirectory,
assetDirectory,
includePatterns,
excludePatterns
};
} else {
return void 0;
}
}
var import_node_assert16, import_promises10, path30, ALWAYS_IGNORE, HIDDEN_FILES_TO_INCLUDE, MAX_DIFF_LINES, MAX_BUCKET_SIZE2, MAX_BUCKET_KEYS, MAX_BATCH_OPERATIONS;
var init_sites = __esm({
"src/sites.ts"() {
init_import_meta_url();
import_node_assert16 = __toESM(require("assert"));
import_promises10 = require("fs/promises");
path30 = __toESM(require("path"));
init_workers_shared();
init_source();
init_xxhash_wasm();
init_errors();
init_helpers4();
init_logger();
ALWAYS_IGNORE = /* @__PURE__ */ new Set(["node_modules"]);
HIDDEN_FILES_TO_INCLUDE = /* @__PURE__ */ new Set([
".well-known"
// See https://datatracker.ietf.org/doc/html/rfc8615
]);
__name(getFilesInFolder, "getFilesInFolder");
__name(hashFileContent, "hashFileContent");
__name(hashAsset, "hashAsset");
__name(createKVNamespaceIfNotAlreadyExisting, "createKVNamespaceIfNotAlreadyExisting");
MAX_DIFF_LINES = 100;
MAX_BUCKET_SIZE2 = 98 * 1e3 * 1e3;
MAX_BUCKET_KEYS = BATCH_KEY_MAX;
MAX_BATCH_OPERATIONS = 5;
__name(pluralise, "pluralise");
__name(syncWorkersSite, "syncWorkersSite");
__name(validateAssetSize, "validateAssetSize");
__name(validateAssetKey, "validateAssetKey");
__name(urlSafe, "urlSafe");
__name(getSiteAssetPaths, "getSiteAssetPaths");
}
});
// src/routes.ts
async function getWorkersDevSubdomain(complianceConfig, accountId, configPath) {
try {
const { subdomain } = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/subdomain`
);
return `${subdomain}${getComplianceRegionSubdomain(complianceConfig)}.workers.dev`;
} catch (e7) {
const error2 = e7;
if (typeof error2 === "object" && !!error2 && error2.code === 10007) {
logger.warn(
"You need to register a workers.dev subdomain before publishing to workers.dev"
);
const wantsToRegister = await confirm(
"Would you like to register a workers.dev subdomain now?",
{ fallbackValue: false }
);
if (!wantsToRegister) {
const solutionMessage = `You can either deploy your worker to one or more routes by specifying them in your ${configFileName(configPath)} file, or register a workers.dev subdomain here:`;
const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
throw new UserError(`${solutionMessage}
${onboardingLink}`);
}
return await registerSubdomain(complianceConfig, accountId, configPath);
} else {
throw e7;
}
}
}
async function registerSubdomain(complianceConfig, accountId, configPath) {
let subdomain;
while (subdomain === void 0) {
const potentialName = await prompt(
"What would you like your workers.dev subdomain to be? It will be accessible at https://<subdomain>.workers.dev"
);
if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(potentialName)) {
logger.warn(
`${potentialName} is invalid, please choose another subdomain.`
);
continue;
}
try {
await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/subdomains/${potentialName}`
);
} catch (err) {
const subdomainAvailabilityCheckError = err;
if (typeof subdomainAvailabilityCheckError === "object" && !!subdomainAvailabilityCheckError) {
if (subdomainAvailabilityCheckError.code === 10032) {
} else if (subdomainAvailabilityCheckError.code === 10031) {
logger.error(
"Subdomain is unavailable, please try a different subdomain"
);
continue;
} else {
logger.error("An unexpected error occurred, please try again.");
continue;
}
}
}
const ok = await confirm(
`Creating a workers.dev subdomain for your account at ${source_default.blue(
source_default.underline(
`https://${potentialName}${getComplianceRegionSubdomain(complianceConfig)}.workers.dev`
)
)}. Ok to proceed?`
);
if (!ok) {
const solutionMessage = `You can either deploy your worker to one or more routes by specifying them in your ${configFileName(configPath)} file, or register a workers.dev subdomain here:`;
const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
throw new UserError(`${solutionMessage}
${onboardingLink}`);
}
try {
const result = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/subdomain`,
{
method: "PUT",
body: JSON.stringify({ subdomain: potentialName })
}
);
subdomain = result.subdomain;
} catch (err) {
const subdomainCreationError = err;
if (typeof subdomainCreationError === "object" && !!subdomainCreationError && subdomainCreationError.code !== void 0) {
switch (subdomainCreationError.code) {
case 10031:
logger.error(
"Subdomain is unavailable, please try a different subdomain."
);
break;
default:
logger.error("An unexpected error occurred, please try again.");
break;
}
}
}
}
logger.log("Success! It may take a few minutes for DNS records to update.");
logger.log(
`Visit ${source_default.blue(
source_default.underline(
`https://dash.cloudflare.com/${accountId}/workers/subdomain`
)
)} to edit your workers.dev subdomain`
);
return `${subdomain}${getComplianceRegionSubdomain(complianceConfig)}.workers.dev`;
}
var init_routes = __esm({
"src/routes.ts"() {
init_import_meta_url();
init_source();
init_cfetch();
init_config2();
init_dialogs();
init_misc_variables();
init_errors();
init_logger();
__name(getWorkersDevSubdomain, "getWorkersDevSubdomain");
__name(registerSubdomain, "registerSubdomain");
}
});
// src/utils/retry.ts
async function retryOnAPIFailure(action, backoff = 0, attempts = MAX_ATTEMPTS) {
try {
return await action();
} catch (err) {
if (err instanceof APIError) {
if (!err.isRetryable()) {
throw err;
}
} else if (!(err instanceof TypeError)) {
throw err;
}
logger.info(source_default.dim(`Retrying API call after error...`));
logger.debug(err);
if (attempts <= 1) {
throw err;
}
await (0, import_promises11.setTimeout)(backoff);
return retryOnAPIFailure(
action,
backoff + (MAX_ATTEMPTS - attempts) * 1e3,
attempts - 1
);
}
}
var import_promises11, MAX_ATTEMPTS;
var init_retry = __esm({
"src/utils/retry.ts"() {
init_import_meta_url();
import_promises11 = require("timers/promises");
init_source();
init_logger();
init_parse();
MAX_ATTEMPTS = 3;
__name(retryOnAPIFailure, "retryOnAPIFailure");
}
});
// src/zones.ts
function getHostFromRoute(route) {
let host;
if (typeof route === "string") {
host = getHostFromUrl(route);
} else if (typeof route === "object") {
host = getHostFromUrl(route.pattern);
if (host === void 0 && "zone_name" in route) {
host = getHostFromUrl(route.zone_name);
}
}
return host;
}
async function getZoneForRoute(complianceConfig, from, zoneIdCache = /* @__PURE__ */ new Map()) {
const { route, accountId } = from;
const host = getHostFromRoute(route);
let id;
if (typeof route === "object" && "zone_id" in route) {
id = route.zone_id;
} else if (typeof route === "object" && "zone_name" in route) {
id = await getZoneIdFromHost(
complianceConfig,
{
host: route.zone_name,
accountId
},
zoneIdCache
);
} else if (host) {
id = await getZoneIdFromHost(
complianceConfig,
{ host, accountId },
zoneIdCache
);
}
return id && host ? { id, host } : void 0;
}
function getHostFromUrl(urlLike) {
if (urlLike.startsWith("*/") || urlLike.startsWith("http://*/") || urlLike.startsWith("https://*/")) {
return void 0;
}
urlLike = urlLike.replace(/\*(\.)?/g, "");
if (!(urlLike.startsWith("http://") || urlLike.startsWith("https://"))) {
urlLike = "http://" + urlLike;
}
try {
return new URL(urlLike).host;
} catch {
return void 0;
}
}
async function getZoneIdForPreview(complianceConfig, from) {
const zoneIdCache = /* @__PURE__ */ new Map();
const { host, routes, accountId } = from;
let zoneId;
if (host) {
zoneId = await getZoneIdFromHost(
complianceConfig,
{ host, accountId },
zoneIdCache
);
}
if (!zoneId && routes) {
const firstRoute = routes[0];
const zone = await getZoneForRoute(
complianceConfig,
{
route: firstRoute,
accountId
},
zoneIdCache
);
if (zone) {
zoneId = zone.id;
}
}
return zoneId;
}
async function getZoneIdFromHost(complianceConfig, from, zoneIdCache) {
const hostPieces = from.host.split(".");
while (hostPieces.length > 1) {
const cacheKey = `${from.accountId}:${hostPieces.join(".")}`;
if (!zoneIdCache.has(cacheKey)) {
zoneIdCache.set(
cacheKey,
retryOnAPIFailure(
() => fetchListResult(
complianceConfig,
`/zones`,
{},
new URLSearchParams({
name: hostPieces.join("."),
"account.id": from.accountId
})
)
).then((zones) => zones[0]?.id ?? null)
);
}
const cachedZone = await zoneIdCache.get(cacheKey);
if (cachedZone) {
return cachedZone;
}
hostPieces.shift();
}
throw new UserError(
`Could not find zone for \`${from.host}\`. Make sure the domain is set up to be proxied by Cloudflare.
For more details, refer to https://developers.cloudflare.com/workers/configuration/routing/routes/#set-up-a-route`
);
}
async function getRoutesForZone(complianceConfig, zone) {
const routes = await fetchListResult(
complianceConfig,
`/zones/${zone}/workers/routes`
);
return routes;
}
function distanceBetween(a5, b6, cache6 = /* @__PURE__ */ new Map()) {
if (cache6.has(`${a5}|${b6}`)) {
return cache6.get(`${a5}|${b6}`);
}
let result;
if (b6 == "") {
result = a5.length;
} else if (a5 == "") {
result = b6.length;
} else if (a5[0] === b6[0]) {
result = distanceBetween(a5.slice(1), b6.slice(1), cache6);
} else {
result = 1 + Math.min(
distanceBetween(a5.slice(1), b6, cache6),
distanceBetween(a5, b6.slice(1), cache6),
distanceBetween(a5.slice(1), b6.slice(1), cache6)
);
}
cache6.set(`${a5}|${b6}`, result);
return result;
}
function findClosestRoute(providedRoute, assignedRoutes) {
return assignedRoutes.sort((a5, b6) => {
const distanceA = distanceBetween(providedRoute, a5.pattern);
const distanceB = distanceBetween(providedRoute, b6.pattern);
return distanceA - distanceB;
});
}
async function getWorkerForZone(complianceConfig, from, configPath) {
const { worker, accountId } = from;
const zone = await getZoneForRoute(complianceConfig, {
route: worker,
accountId
});
if (!zone) {
throw new UserError(
`The route '${worker}' is not part of one of your zones. Either add this zone from the Cloudflare dashboard, or try using a route within one of your existing zones.`
);
}
const routes = await getRoutesForZone(complianceConfig, zone.id);
const scriptName = routes.find((route) => route.pattern === worker)?.script;
if (!scriptName) {
const closestRoute = findClosestRoute(worker, routes)?.[0];
if (!closestRoute) {
throw new UserError(
`The route '${worker}' has no workers assigned. You can assign a worker to it from your ${configFileName(configPath)} file or the Cloudflare dashboard`
);
} else {
throw new UserError(
`The route '${worker}' has no workers assigned. Did you mean to tail the route '${closestRoute.pattern}'?`
);
}
}
return scriptName;
}
var init_zones = __esm({
"src/zones.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_errors();
init_retry();
__name(getHostFromRoute, "getHostFromRoute");
__name(getZoneForRoute, "getZoneForRoute");
__name(getHostFromUrl, "getHostFromUrl");
__name(getZoneIdForPreview, "getZoneIdForPreview");
__name(getZoneIdFromHost, "getZoneIdFromHost");
__name(getRoutesForZone, "getRoutesForZone");
__name(distanceBetween, "distanceBetween");
__name(findClosestRoute, "findClosestRoute");
__name(getWorkerForZone, "getWorkerForZone");
}
});
// src/triggers/deploy.ts
async function triggersDeploy(props) {
const { config, accountId, name: scriptName } = props;
const schedules = props.triggers || config.triggers?.crons;
const routes = props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
const routesOnly = [];
const customDomainsOnly = [];
validateRoutes3(routes, props.assetsOptions);
for (const route of routes) {
if (typeof route !== "string" && route.custom_domain) {
customDomainsOnly.push(route);
} else {
routesOnly.push(route);
}
}
const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
if (!scriptName) {
throw new UserError(
'You need to provide a name when uploading a Worker Version. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const envName = props.env ?? "production";
const start = Date.now();
const notProd = Boolean(!props.legacyEnv && props.env);
const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
const workerUrl = notProd ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}` : `/accounts/${accountId}/workers/scripts/${scriptName}`;
const {
enabled: available_on_subdomain,
previews_enabled: previews_available_on_subdomain
} = await fetchResult(config, `${workerUrl}/subdomain`);
if (!props.dryRun) {
await ensureQueuesExistByConfig(config);
}
if (props.dryRun) {
logger.log(`--dry-run: exiting now.`);
return;
}
if (!accountId) {
throw new UserError("Missing accountId", { telemetryMessage: true });
}
const uploadMs = Date.now() - start;
const deployments = [];
const deploymentInSync = deployToWorkersDev === available_on_subdomain;
const previewsInSync = config.preview_urls === previews_available_on_subdomain;
if (deployToWorkersDev) {
const userSubdomain = await getWorkersDevSubdomain(
config,
accountId,
config.configPath
);
const deploymentURL = props.legacyEnv || !props.env ? `${scriptName}.${userSubdomain}` : `${envName}.${scriptName}.${userSubdomain}`;
if (deploymentInSync && previewsInSync) {
deployments.push(Promise.resolve([deploymentURL]));
} else {
deployments.push(
fetchResult(config, `${workerUrl}/subdomain`, {
method: "POST",
body: JSON.stringify({
enabled: true,
previews_enabled: config.preview_urls
}),
headers: {
"Content-Type": "application/json"
}
}).then(() => [deploymentURL])
);
}
}
if (!deployToWorkersDev && (!deploymentInSync || !previewsInSync)) {
await fetchResult(config, `${workerUrl}/subdomain`, {
method: "POST",
body: JSON.stringify({
enabled: false,
previews_enabled: config.preview_urls
}),
headers: {
"Content-Type": "application/json"
}
});
}
if (!deployToWorkersDev && deploymentInSync && routes.length !== 0) {
const routesWithOtherBindings = {};
const queue = new PQueue({ concurrency: 10 });
const queuePromises = [];
const zoneRoutesCache = /* @__PURE__ */ new Map();
const zoneIdCache = /* @__PURE__ */ new Map();
for (const route of routes) {
queuePromises.push(
queue.add(async () => {
const zone = await getZoneForRoute(
config,
{ route, accountId },
zoneIdCache
);
if (!zone) {
return;
}
const routePattern = typeof route === "string" ? route : route.pattern;
let routesInZone = zoneRoutesCache.get(zone.id);
if (!routesInZone) {
routesInZone = retryOnAPIFailure(
() => fetchListResult(config, `/zones/${zone.id}/workers/routes`)
);
zoneRoutesCache.set(zone.id, routesInZone);
}
(await routesInZone).forEach(({ script, pattern }) => {
if (pattern === routePattern && script !== scriptName) {
if (!(script in routesWithOtherBindings)) {
routesWithOtherBindings[script] = [];
}
routesWithOtherBindings[script].push(pattern);
}
});
})
);
}
await Promise.all(queuePromises);
if (Object.keys(routesWithOtherBindings).length > 0) {
let errorMessage = "Can't deploy routes that are assigned to another worker.\n";
for (const worker in routesWithOtherBindings) {
const assignedRoutes = routesWithOtherBindings[worker];
errorMessage += `"${worker}" is already assigned to routes:
${assignedRoutes.map(
(r7) => ` - ${source_default.underline(r7)}
`
)}`;
}
const resolution = "Unassign other workers from the routes you want to deploy to, and then try again.";
const dashHref = source_default.blue.underline(
`https://dash.cloudflare.com/${accountId}/workers/overview`
);
const dashLink = `Visit ${dashHref} to unassign a worker from a route.`;
throw new UserError(`${errorMessage}
${resolution}
${dashLink}`);
}
}
if (routesOnly.length > 0) {
deployments.push(
publishRoutes(config, routesOnly, {
workerUrl,
scriptName,
notProd,
accountId
}).then(() => {
if (routesOnly.length > 10) {
return routesOnly.slice(0, 9).map((route) => renderRoute(route)).concat([`...and ${routesOnly.length - 10} more routes`]);
}
return routesOnly.map((route) => renderRoute(route));
})
);
}
if (customDomainsOnly.length > 0) {
deployments.push(
publishCustomDomains(config, workerUrl, accountId, customDomainsOnly)
);
}
if (schedules) {
deployments.push(
fetchResult(config, `${workerUrl}/schedules`, {
// Note: PUT will override previous schedules on this script.
method: "PUT",
body: JSON.stringify(schedules.map((cron) => ({ cron }))),
headers: {
"Content-Type": "application/json"
}
}).then(() => schedules.map((trigger) => `schedule: ${trigger}`))
);
}
if (config.queues.producers && config.queues.producers.length) {
deployments.push(
...config.queues.producers.map(
(producer) => Promise.resolve([`Producer for ${producer.queue}`])
)
);
}
if (config.queues.consumers && config.queues.consumers.length) {
const updateConsumers = await updateQueueConsumers(scriptName, config);
deployments.push(...updateConsumers);
}
if (config.workflows?.length) {
for (const workflow of config.workflows) {
if (workflow.script_name !== void 0 && workflow.script_name !== scriptName) {
continue;
}
deployments.push(
fetchResult(
config,
`/accounts/${accountId}/workflows/${workflow.name}`,
{
method: "PUT",
body: JSON.stringify({
script_name: scriptName,
class_name: workflow.class_name
}),
headers: {
"Content-Type": "application/json"
}
}
).then(() => [`workflow: ${workflow.name}`])
);
}
}
const targets = await Promise.all(deployments);
const deployMs = Date.now() - start - uploadMs;
if (deployments.length > 0) {
logger.log(`Deployed ${workerName} triggers`, formatTime(deployMs));
const flatTargets = targets.flat().map(
// Append protocol only on workers.dev domains
(target) => (target.endsWith("workers.dev") ? "https://" : "") + target
);
for (const target of flatTargets) {
logger.log(" ", target);
}
return flatTargets;
} else {
logger.log("No deploy targets for", workerName, formatTime(deployMs));
}
}
var init_deploy3 = __esm({
"src/triggers/deploy.ts"() {
init_import_meta_url();
init_source();
init_dist2();
init_cfetch();
init_deploy8();
init_errors();
init_logger();
init_client2();
init_routes();
init_retry();
init_zones();
__name(triggersDeploy, "triggersDeploy");
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/stream.js
var require_stream = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/stream.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Duplex: Duplex2 } = require("stream");
function emitClose(stream2) {
stream2.emit("close");
}
__name(emitClose, "emitClose");
function duplexOnEnd() {
if (!this.destroyed && this._writableState.finished) {
this.destroy();
}
}
__name(duplexOnEnd, "duplexOnEnd");
function duplexOnError(err) {
this.removeListener("error", duplexOnError);
this.destroy();
if (this.listenerCount("error") === 0) {
this.emit("error", err);
}
}
__name(duplexOnError, "duplexOnError");
function createWebSocketStream2(ws, options) {
let terminateOnDestroy = true;
const duplex = new Duplex2({
...options,
autoDestroy: false,
emitClose: false,
objectMode: false,
writableObjectMode: false
});
ws.on("message", /* @__PURE__ */ __name(function message(msg, isBinary) {
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
if (!duplex.push(data)) ws.pause();
}, "message"));
ws.once("error", /* @__PURE__ */ __name(function error2(err) {
if (duplex.destroyed) return;
terminateOnDestroy = false;
duplex.destroy(err);
}, "error"));
ws.once("close", /* @__PURE__ */ __name(function close2() {
if (duplex.destroyed) return;
duplex.push(null);
}, "close"));
duplex._destroy = function(err, callback) {
if (ws.readyState === ws.CLOSED) {
callback(err);
process.nextTick(emitClose, duplex);
return;
}
let called = false;
ws.once("error", /* @__PURE__ */ __name(function error2(err2) {
called = true;
callback(err2);
}, "error"));
ws.once("close", /* @__PURE__ */ __name(function close2() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
}, "close"));
if (terminateOnDestroy) ws.terminate();
};
duplex._final = function(callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once("open", /* @__PURE__ */ __name(function open4() {
duplex._final(callback);
}, "open"));
return;
}
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
callback();
if (duplex._readableState.endEmitted) duplex.destroy();
} else {
ws._socket.once("finish", /* @__PURE__ */ __name(function finish() {
callback();
}, "finish"));
ws.close();
}
};
duplex._read = function() {
if (ws.isPaused) ws.resume();
};
duplex._write = function(chunk, encoding, callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once("open", /* @__PURE__ */ __name(function open4() {
duplex._write(chunk, encoding, callback);
}, "open"));
return;
}
ws.send(chunk, callback);
};
duplex.on("end", duplexOnEnd);
duplex.on("error", duplexOnError);
return duplex;
}
__name(createWebSocketStream2, "createWebSocketStream");
module3.exports = createWebSocketStream2;
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/constants.js
var require_constants6 = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/constants.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
var hasBlob = typeof Blob !== "undefined";
if (hasBlob) BINARY_TYPES.push("blob");
module3.exports = {
BINARY_TYPES,
EMPTY_BUFFER: Buffer.alloc(0),
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
hasBlob,
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
kListener: Symbol("kListener"),
kStatusCode: Symbol("status-code"),
kWebSocket: Symbol("websocket"),
NOOP: /* @__PURE__ */ __name(() => {
}, "NOOP")
};
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/buffer-util.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { EMPTY_BUFFER } = require_constants6();
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 i5 = 0; i5 < list.length; i5++) {
const buf = list[i5];
target.set(buf, offset);
offset += buf.length;
}
if (offset < totalLength) {
return new FastBuffer(target.buffer, target.byteOffset, offset);
}
return target;
}
__name(concat, "concat");
function _mask(source, mask, output, offset, length) {
for (let i5 = 0; i5 < length; i5++) {
output[offset + i5] = source[i5] ^ mask[i5 & 3];
}
}
__name(_mask, "_mask");
function _unmask(buffer, mask) {
for (let i5 = 0; i5 < buffer.length; i5++) {
buffer[i5] ^= mask[i5 & 3];
}
}
__name(_unmask, "_unmask");
function toArrayBuffer(buf) {
if (buf.length === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
__name(toArrayBuffer, "toArrayBuffer");
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;
}
__name(toBuffer, "toBuffer");
module3.exports = {
concat,
mask: _mask,
toArrayBuffer,
toBuffer,
unmask: _unmask
};
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil = require("bufferutil");
module3.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);
};
module3.exports.unmask = function(buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil.unmask(buffer, mask);
};
} catch (e7) {
}
}
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/limiter.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var kDone = Symbol("kDone");
var kRun = Symbol("kRun");
var Limiter = class {
static {
__name(this, "Limiter");
}
/**
* 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]);
}
}
};
module3.exports = Limiter;
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate2 = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/permessage-deflate.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var zlib2 = require("zlib");
var bufferUtil = require_buffer_util();
var Limiter = require_limiter();
var { kStatusCode } = require_constants6();
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 {
static {
__name(this, "PerMessageDeflate");
}
/**
* 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" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
this._inflate = zlib2.createInflateRaw({
...this._options.zlibInflateOptions,
windowBits
});
this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
this._inflate.on("error", inflateOnError);
this._inflate.on("data", inflateOnData);
}
this._inflate[kCallback] = callback;
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
const 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" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
this._deflate = zlib2.createDeflateRaw({
...this._options.zlibDeflateOptions,
windowBits
});
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
this._deflate.on("data", deflateOnData);
}
this._deflate[kCallback] = callback;
this._deflate.write(data);
this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
return;
}
let data2 = bufferUtil.concat(
this._deflate[kBuffers],
this._deflate[kTotalLength]
);
if (fin) {
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
}
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
}
callback(null, data2);
});
}
};
module3.exports = PerMessageDeflate;
function deflateOnData(chunk) {
this[kBuffers].push(chunk);
this[kTotalLength] += chunk.length;
}
__name(deflateOnData, "deflateOnData");
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();
}
__name(inflateOnData, "inflateOnData");
function inflateOnError(err) {
this[kPerMessageDeflate]._inflate = null;
err[kStatusCode] = 1007;
this[kCallback](err);
}
__name(inflateOnError, "inflateOnError");
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/validation.js
var require_validation = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/validation.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { isUtf8 } = require("buffer");
var { hasBlob } = require_constants6();
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;
}
__name(isValidStatusCode, "isValidStatusCode");
function _isValidUTF8(buf) {
const len = buf.length;
let i5 = 0;
while (i5 < len) {
if ((buf[i5] & 128) === 0) {
i5++;
} else if ((buf[i5] & 224) === 192) {
if (i5 + 1 === len || (buf[i5 + 1] & 192) !== 128 || (buf[i5] & 254) === 192) {
return false;
}
i5 += 2;
} else if ((buf[i5] & 240) === 224) {
if (i5 + 2 >= len || (buf[i5 + 1] & 192) !== 128 || (buf[i5 + 2] & 192) !== 128 || buf[i5] === 224 && (buf[i5 + 1] & 224) === 128 || // Overlong
buf[i5] === 237 && (buf[i5 + 1] & 224) === 160) {
return false;
}
i5 += 3;
} else if ((buf[i5] & 248) === 240) {
if (i5 + 3 >= len || (buf[i5 + 1] & 192) !== 128 || (buf[i5 + 2] & 192) !== 128 || (buf[i5 + 3] & 192) !== 128 || buf[i5] === 240 && (buf[i5 + 1] & 240) === 128 || // Overlong
buf[i5] === 244 && buf[i5 + 1] > 143 || buf[i5] > 244) {
return false;
}
i5 += 4;
} else {
return false;
}
}
return true;
}
__name(_isValidUTF8, "_isValidUTF8");
function isBlob3(value) {
return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
}
__name(isBlob3, "isBlob");
module3.exports = {
isBlob: isBlob3,
isValidStatusCode,
isValidUTF8: _isValidUTF8,
tokenChars
};
if (isUtf8) {
module3.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");
module3.exports.isValidUTF8 = function(buf) {
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
};
} catch (e7) {
}
}
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/receiver.js
var require_receiver2 = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/receiver.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Writable: Writable5 } = require("stream");
var PerMessageDeflate = require_permessage_deflate2();
var {
BINARY_TYPES,
EMPTY_BUFFER,
kStatusCode,
kWebSocket
} = require_constants6();
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 Writable5 {
static {
__name(this, "Receiver");
}
/**
* 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, cb2) {
if (this._opcode === 8 && this._state == GET_INFO) return cb2();
this._bufferedBytes += chunk.length;
this._buffers.push(chunk);
this.startLoop(cb2);
}
/**
* Consumes `n` bytes from the buffered data.
*
* @param {Number} n The number of bytes to consume
* @return {Buffer} The consumed bytes
* @private
*/
consume(n6) {
this._bufferedBytes -= n6;
if (n6 === this._buffers[0].length) return this._buffers.shift();
if (n6 < this._buffers[0].length) {
const buf = this._buffers[0];
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n6,
buf.length - n6
);
return new FastBuffer(buf.buffer, buf.byteOffset, n6);
}
const dst = Buffer.allocUnsafe(n6);
do {
const buf = this._buffers[0];
const offset = dst.length - n6;
if (n6 >= buf.length) {
dst.set(this._buffers.shift(), offset);
} else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n6), offset);
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n6,
buf.length - n6
);
}
n6 -= buf.length;
} while (n6 > 0);
return dst;
}
/**
* Starts the parsing loop.
*
* @param {Function} cb Callback
* @private
*/
startLoop(cb2) {
this._loop = true;
do {
switch (this._state) {
case GET_INFO:
this.getInfo(cb2);
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16(cb2);
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64(cb2);
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData(cb2);
break;
case INFLATING:
case DEFER_EVENT:
this._loop = false;
return;
}
} while (this._loop);
if (!this._errored) cb2();
}
/**
* Reads the first two bytes of a frame.
*
* @param {Function} cb Callback
* @private
*/
getInfo(cb2) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
const buf = this.consume(2);
if ((buf[0] & 48) !== 0) {
const error2 = this.createError(
RangeError,
"RSV2 and RSV3 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_2_3"
);
cb2(error2);
return;
}
const compressed = (buf[0] & 64) === 64;
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
const error2 = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb2(error2);
return;
}
this._fin = (buf[0] & 128) === 128;
this._opcode = buf[0] & 15;
this._payloadLength = buf[1] & 127;
if (this._opcode === 0) {
if (compressed) {
const error2 = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb2(error2);
return;
}
if (!this._fragmented) {
const error2 = this.createError(
RangeError,
"invalid opcode 0",
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb2(error2);
return;
}
this._opcode = this._fragmented;
} else if (this._opcode === 1 || this._opcode === 2) {
if (this._fragmented) {
const error2 = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb2(error2);
return;
}
this._compressed = compressed;
} else if (this._opcode > 7 && this._opcode < 11) {
if (!this._fin) {
const error2 = this.createError(
RangeError,
"FIN must be set",
true,
1002,
"WS_ERR_EXPECTED_FIN"
);
cb2(error2);
return;
}
if (compressed) {
const error2 = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb2(error2);
return;
}
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
const error2 = this.createError(
RangeError,
`invalid payload length ${this._payloadLength}`,
true,
1002,
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
);
cb2(error2);
return;
}
} else {
const error2 = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb2(error2);
return;
}
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 128) === 128;
if (this._isServer) {
if (!this._masked) {
const error2 = this.createError(
RangeError,
"MASK must be set",
true,
1002,
"WS_ERR_EXPECTED_MASK"
);
cb2(error2);
return;
}
} else if (this._masked) {
const error2 = this.createError(
RangeError,
"MASK must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_MASK"
);
cb2(error2);
return;
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else this.haveLength(cb2);
}
/**
* Gets extended payload length (7+16).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength16(cb2) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
this._payloadLength = this.consume(2).readUInt16BE(0);
this.haveLength(cb2);
}
/**
* Gets extended payload length (7+64).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength64(cb2) {
if (this._bufferedBytes < 8) {
this._loop = false;
return;
}
const buf = this.consume(8);
const num = buf.readUInt32BE(0);
if (num > Math.pow(2, 53 - 32) - 1) {
const error2 = this.createError(
RangeError,
"Unsupported WebSocket frame: payload length > 2^53 - 1",
false,
1009,
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
);
cb2(error2);
return;
}
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
this.haveLength(cb2);
}
/**
* Payload length has been read.
*
* @param {Function} cb Callback
* @private
*/
haveLength(cb2) {
if (this._payloadLength && this._opcode < 8) {
this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
const error2 = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb2(error2);
return;
}
}
if (this._masked) this._state = GET_MASK;
else this._state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask() {
if (this._bufferedBytes < 4) {
this._loop = false;
return;
}
this._mask = this.consume(4);
this._state = GET_DATA;
}
/**
* Reads data bytes.
*
* @param {Function} cb Callback
* @private
*/
getData(cb2) {
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, cb2);
return;
}
if (this._compressed) {
this._state = INFLATING;
this.decompress(data, cb2);
return;
}
if (data.length) {
this._messageLength = this._totalPayloadLength;
this._fragments.push(data);
}
this.dataMessage(cb2);
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @param {Function} cb Callback
* @private
*/
decompress(data, cb2) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
if (err) return cb2(err);
if (buf.length) {
this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
const error2 = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb2(error2);
return;
}
this._fragments.push(buf);
}
this.dataMessage(cb2);
if (this._state === GET_INFO) this.startLoop(cb2);
});
}
/**
* Handles a data message.
*
* @param {Function} cb Callback
* @private
*/
dataMessage(cb2) {
if (!this._fin) {
this._state = GET_INFO;
return;
}
const messageLength = this._messageLength;
const fragments = this._fragments;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragmented = 0;
this._fragments = [];
if (this._opcode === 2) {
let data;
if (this._binaryType === "nodebuffer") {
data = concat(fragments, messageLength);
} else if (this._binaryType === "arraybuffer") {
data = toArrayBuffer(concat(fragments, messageLength));
} else if (this._binaryType === "blob") {
data = new Blob(fragments);
} else {
data = fragments;
}
if (this._allowSynchronousEvents) {
this.emit("message", data, true);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", data, true);
this._state = GET_INFO;
this.startLoop(cb2);
});
}
} else {
const buf = concat(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error2 = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb2(error2);
return;
}
if (this._state === INFLATING || this._allowSynchronousEvents) {
this.emit("message", buf, false);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", buf, false);
this._state = GET_INFO;
this.startLoop(cb2);
});
}
}
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @return {(Error|RangeError|undefined)} A possible error
* @private
*/
controlMessage(data, cb2) {
if (this._opcode === 8) {
if (data.length === 0) {
this._loop = false;
this.emit("conclude", 1005, EMPTY_BUFFER);
this.end();
} else {
const code = data.readUInt16BE(0);
if (!isValidStatusCode(code)) {
const error2 = this.createError(
RangeError,
`invalid status code ${code}`,
true,
1002,
"WS_ERR_INVALID_CLOSE_CODE"
);
cb2(error2);
return;
}
const buf = new FastBuffer(
data.buffer,
data.byteOffset + 2,
data.length - 2
);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error2 = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb2(error2);
return;
}
this._loop = false;
this.emit("conclude", code, buf);
this.end();
}
this._state = GET_INFO;
return;
}
if (this._allowSynchronousEvents) {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
this.startLoop(cb2);
});
}
}
/**
* 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;
}
};
module3.exports = Receiver2;
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/sender.js
var require_sender2 = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/sender.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { Duplex: Duplex2 } = require("stream");
var { randomFillSync } = require("crypto");
var PerMessageDeflate = require_permessage_deflate2();
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants6();
var { isBlob: isBlob3, isValidStatusCode } = require_validation();
var { mask: applyMask, toBuffer } = require_buffer_util();
var kByteLength = Symbol("kByteLength");
var maskBuffer = Buffer.alloc(4);
var RANDOM_POOL_SIZE = 8 * 1024;
var randomPool;
var randomPoolPointer = RANDOM_POOL_SIZE;
var DEFAULT = 0;
var DEFLATING = 1;
var GET_BLOB_DATA = 2;
var Sender2 = class _Sender {
static {
__name(this, "Sender");
}
/**
* Creates a Sender instance.
*
* @param {Duplex} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/
constructor(socket, extensions, generateMask) {
this._extensions = extensions || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket;
this._firstFragment = true;
this._compress = false;
this._bufferedBytes = 0;
this._queue = [];
this._state = DEFAULT;
this.onerror = NOOP;
this[kWebSocket] = void 0;
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {(Buffer|String)} data The data to frame
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @return {(Buffer|String)[]} The framed data
* @public
*/
static frame(data, options) {
let mask;
let merge = false;
let offset = 2;
let skipMasking = false;
if (options.mask) {
mask = options.maskBuffer || maskBuffer;
if (options.generateMask) {
options.generateMask(mask);
} else {
if (randomPoolPointer === RANDOM_POOL_SIZE) {
if (randomPool === void 0) {
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}
mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
offset = 6;
}
let dataLength;
if (typeof data === "string") {
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
dataLength = options[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge = options.mask && options.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset += 8;
payloadLength = 127;
} else if (dataLength > 125) {
offset += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
target[0] = options.fin ? options.opcode | 128 : options.opcode;
if (options.rsv1) target[0] |= 64;
target[1] = payloadLength;
if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2);
} else if (payloadLength === 127) {
target[2] = target[3] = 0;
target.writeUIntBE(dataLength, 4, 6);
}
if (!options.mask) return [target, data];
target[1] |= 128;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge) {
applyMask(data, mask, target, offset, dataLength);
return [target];
}
applyMask(data, mask, data, 0, dataLength);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {Number} [code] The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
* @param {Function} [cb] Callback
* @public
*/
close(code, data, mask, cb2) {
let buf;
if (code === void 0) {
buf = EMPTY_BUFFER;
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
throw new TypeError("First argument must be a valid error code number");
} else if (data === void 0 || !data.length) {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError("The message must not be greater than 123 bytes");
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
if (typeof data === "string") {
buf.write(data, 2);
} else {
buf.set(data, 2);
}
}
const options = {
[kByteLength]: buf.length,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 8,
readOnly: false,
rsv1: false
};
if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, buf, false, options, cb2]);
} else {
this.sendFrame(_Sender.frame(buf, options), cb2);
}
}
/**
* 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, cb2) {
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob3(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 9,
readOnly,
rsv1: false
};
if (isBlob3(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb2]);
} else {
this.getBlobData(data, false, options, cb2);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb2]);
} else {
this.sendFrame(_Sender.frame(data, options), cb2);
}
}
/**
* 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, cb2) {
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob3(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 10,
readOnly,
rsv1: false
};
if (isBlob3(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb2]);
} else {
this.getBlobData(data, false, options, cb2);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb2]);
} else {
this.sendFrame(_Sender.frame(data, options), cb2);
}
}
/**
* 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, cb2) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
let opcode = options.binary ? 2 : 1;
let rsv1 = options.compress;
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob3(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (this._firstFragment) {
this._firstFragment = false;
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
rsv1 = byteLength >= perMessageDeflate._threshold;
}
this._compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options.fin) this._firstFragment = true;
const opts = {
[kByteLength]: byteLength,
fin: options.fin,
generateMask: this._generateMask,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1
};
if (isBlob3(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, this._compress, opts, cb2]);
} else {
this.getBlobData(data, this._compress, opts, cb2);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, this._compress, opts, cb2]);
} else {
this.dispatch(data, this._compress, opts, cb2);
}
}
/**
* Gets the contents of a blob as binary data.
*
* @param {Blob} blob The blob
* @param {Boolean} [compress=false] Specifies whether or not to compress
* the data
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
getBlobData(blob, compress, options, cb2) {
this._bufferedBytes += options[kByteLength];
this._state = GET_BLOB_DATA;
blob.arrayBuffer().then((arrayBuffer2) => {
if (this._socket.destroyed) {
const err = new Error(
"The socket was closed while the blob was being read"
);
process.nextTick(callCallbacks, this, err, cb2);
return;
}
this._bufferedBytes -= options[kByteLength];
const data = toBuffer(arrayBuffer2);
if (!compress) {
this._state = DEFAULT;
this.sendFrame(_Sender.frame(data, options), cb2);
this.dequeue();
} else {
this.dispatch(data, compress, options, cb2);
}
}).catch((err) => {
process.nextTick(onError, this, err, cb2);
});
}
/**
* 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, cb2) {
if (!compress) {
this.sendFrame(_Sender.frame(data, options), cb2);
return;
}
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
this._bufferedBytes += options[kByteLength];
this._state = DEFLATING;
perMessageDeflate.compress(data, options.fin, (_4, buf) => {
if (this._socket.destroyed) {
const err = new Error(
"The socket was closed while data was being compressed"
);
callCallbacks(this, err, cb2);
return;
}
this._bufferedBytes -= options[kByteLength];
this._state = DEFAULT;
options.readOnly = false;
this.sendFrame(_Sender.frame(buf, options), cb2);
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (this._state === DEFAULT && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength];
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[3][kByteLength];
this._queue.push(params);
}
/**
* Sends a frame.
*
* @param {Buffer[]} list The frame to send
* @param {Function} [cb] Callback
* @private
*/
sendFrame(list, cb2) {
if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]);
this._socket.write(list[1], cb2);
this._socket.uncork();
} else {
this._socket.write(list[0], cb2);
}
}
};
module3.exports = Sender2;
function callCallbacks(sender, err, cb2) {
if (typeof cb2 === "function") cb2(err);
for (let i5 = 0; i5 < sender._queue.length; i5++) {
const params = sender._queue[i5];
const callback = params[params.length - 1];
if (typeof callback === "function") callback(err);
}
}
__name(callCallbacks, "callCallbacks");
function onError(sender, err, cb2) {
callCallbacks(sender, err, cb2);
sender.onerror(err);
}
__name(onError, "onError");
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/event-target.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { kForOnEventAttribute, kListener } = require_constants6();
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 {
static {
__name(this, "Event");
}
/**
* 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 {
static {
__name(this, "CloseEvent");
}
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === void 0 ? 0 : options.code;
this[kReason] = options.reason === void 0 ? "" : options.reason;
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
};
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
var ErrorEvent = class extends Event2 {
static {
__name(this, "ErrorEvent");
}
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === void 0 ? null : options.error;
this[kMessage] = options.message === void 0 ? "" : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
};
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
var MessageEvent = class extends Event2 {
static {
__name(this, "MessageEvent");
}
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);
this[kData] = options.data === void 0 ? null : options.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
};
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
var 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 = /* @__PURE__ */ __name(function onMessage(data, isBinary) {
const event = new MessageEvent("message", {
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
}, "onMessage");
} else if (type === "close") {
wrapper = /* @__PURE__ */ __name(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);
}, "onClose");
} else if (type === "error") {
wrapper = /* @__PURE__ */ __name(function onError(error2) {
const event = new ErrorEvent("error", {
error: error2,
message: error2.message
});
event[kTarget] = this;
callListener(handler, this, event);
}, "onError");
} else if (type === "open") {
wrapper = /* @__PURE__ */ __name(function onOpen() {
const event = new Event2("open");
event[kTarget] = this;
callListener(handler, this, event);
}, "onOpen");
} 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;
}
}
}
};
module3.exports = {
CloseEvent,
ErrorEvent,
Event: Event2,
EventTarget: EventTarget2,
MessageEvent
};
function callListener(listener, thisArg, event) {
if (typeof listener === "object" && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}
__name(callListener, "callListener");
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/extension.js
var require_extension = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/extension.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { tokenChars } = require_validation();
function push(dest, name2, elem) {
if (dest[name2] === void 0) dest[name2] = [elem];
else dest[name2].push(elem);
}
__name(push, "push");
function parse7(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 i5 = 0;
for (; i5 < header.length; i5++) {
code = header.charCodeAt(i5);
if (extensionName === void 0) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i5;
} else if (i5 !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i5;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
if (end === -1) end = i5;
const name2 = header.slice(start, end);
if (code === 44) {
push(offers, name2, params);
params = /* @__PURE__ */ Object.create(null);
} else {
extensionName = name2;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
} else if (paramName === void 0) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i5;
} else if (code === 32 || code === 9) {
if (end === -1 && start !== -1) end = i5;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
if (end === -1) end = i5;
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, i5);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
} else {
if (isEscaping) {
if (tokenChars[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
if (start === -1) start = i5;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars[code] === 1) {
if (start === -1) start = i5;
} else if (code === 34 && start !== -1) {
inQuotes = false;
end = i5;
} else if (code === 92) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
} else if (code === 34 && header.charCodeAt(i5 - 1) === 61) {
inQuotes = true;
} else if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i5;
} else if (start !== -1 && (code === 32 || code === 9)) {
if (end === -1) end = i5;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
if (end === -1) end = i5;
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 ${i5}`);
}
}
}
if (start === -1 || inQuotes || code === 32 || code === 9) {
throw new SyntaxError("Unexpected end of input");
}
if (end === -1) end = i5;
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;
}
__name(parse7, "parse");
function format9(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((k6) => {
let values = params[k6];
if (!Array.isArray(values)) values = [values];
return values.map((v7) => v7 === true ? k6 : `${k6}=${v7}`).join("; ");
})
).join("; ");
}).join(", ");
}).join(", ");
}
__name(format9, "format");
module3.exports = { format: format9, parse: parse7 };
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/websocket.js
var require_websocket2 = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/websocket.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var EventEmitter5 = require("events");
var https2 = require("https");
var http5 = require("http");
var net2 = require("net");
var tls = require("tls");
var { randomBytes: randomBytes2, createHash: createHash8 } = require("crypto");
var { Duplex: Duplex2, Readable: Readable8 } = require("stream");
var { URL: URL7 } = require("url");
var PerMessageDeflate = require_permessage_deflate2();
var Receiver2 = require_receiver2();
var Sender2 = require_sender2();
var { isBlob: isBlob3 } = require_validation();
var {
BINARY_TYPES,
EMPTY_BUFFER,
GUID,
kForOnEventAttribute,
kListener,
kStatusCode,
kWebSocket,
NOOP
} = require_constants6();
var {
EventTarget: { addEventListener, removeEventListener }
} = require_event_target();
var { format: format9, parse: parse7 } = 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 EventEmitter5 {
static {
__name(this, "WebSocket");
}
/**
* Create a new `WebSocket`.
*
* @param {(String|URL)} address The URL to which to connect
* @param {(String|String[])} [protocols] The subprotocols
* @param {Object} [options] Connection options
*/
constructor(address, protocols, options) {
super();
this._binaryType = BINARY_TYPES[0];
this._closeCode = 1006;
this._closeFrameReceived = false;
this._closeFrameSent = false;
this._closeMessage = EMPTY_BUFFER;
this._closeTimer = null;
this._errorEmitted = false;
this._extensions = {};
this._paused = false;
this._protocol = "";
this._readyState = _WebSocket.CONNECTING;
this._receiver = null;
this._sender = null;
this._socket = null;
if (address !== null) {
this._bufferedAmount = 0;
this._isServer = false;
this._redirects = 0;
if (protocols === void 0) {
protocols = [];
} else if (!Array.isArray(protocols)) {
if (typeof protocols === "object" && protocols !== null) {
options = protocols;
protocols = [];
} else {
protocols = [protocols];
}
}
initAsClient(this, address, protocols, options);
} else {
this._autoPong = options.autoPong;
this._isServer = true;
}
}
/**
* For historical reasons, the custom "nodebuffer" type is used by the default
* instead of "blob".
*
* @type {String}
*/
get binaryType() {
return this._binaryType;
}
set binaryType(type) {
if (!BINARY_TYPES.includes(type)) return;
this._binaryType = type;
if (this._receiver) this._receiver._binaryType = type;
}
/**
* @type {Number}
*/
get bufferedAmount() {
if (!this._socket) return this._bufferedAmount;
return this._socket._writableState.length + this._sender._bufferedBytes;
}
/**
* @type {String}
*/
get extensions() {
return Object.keys(this._extensions).join();
}
/**
* @type {Boolean}
*/
get isPaused() {
return this._paused;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onclose() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onerror() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onopen() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onmessage() {
return null;
}
/**
* @type {String}
*/
get protocol() {
return this._protocol;
}
/**
* @type {Number}
*/
get readyState() {
return this._readyState;
}
/**
* @type {String}
*/
get url() {
return this._url;
}
/**
* Set up the socket and the internal resources.
*
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Object} options Options object
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Number} [options.maxPayload=0] The maximum allowed message size
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @private
*/
setSocket(socket, head, options) {
const receiver = new Receiver2({
allowSynchronousEvents: options.allowSynchronousEvents,
binaryType: this.binaryType,
extensions: this._extensions,
isServer: this._isServer,
maxPayload: options.maxPayload,
skipUTF8Validation: options.skipUTF8Validation
});
const sender = new Sender2(socket, this._extensions, options.generateMask);
this._receiver = receiver;
this._sender = sender;
this._socket = socket;
receiver[kWebSocket] = this;
sender[kWebSocket] = this;
socket[kWebSocket] = this;
receiver.on("conclude", receiverOnConclude);
receiver.on("drain", receiverOnDrain);
receiver.on("error", receiverOnError);
receiver.on("message", receiverOnMessage);
receiver.on("ping", receiverOnPing);
receiver.on("pong", receiverOnPong);
sender.onerror = senderOnError;
if (socket.setTimeout) socket.setTimeout(0);
if (socket.setNoDelay) socket.setNoDelay();
if (head.length > 0) socket.unshift(head);
socket.on("close", socketOnClose);
socket.on("data", socketOnData);
socket.on("end", socketOnEnd);
socket.on("error", socketOnError);
this._readyState = _WebSocket.OPEN;
this.emit("open");
}
/**
* Emit the `'close'` event.
*
* @private
*/
emitClose() {
if (!this._socket) {
this._readyState = _WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
return;
}
if (this._extensions[PerMessageDeflate.extensionName]) {
this._extensions[PerMessageDeflate.extensionName].cleanup();
}
this._receiver.removeAllListeners();
this._readyState = _WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
}
/**
* Start a closing handshake.
*
* +----------+ +-----------+ +----------+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
* | +----------+ +-----------+ +----------+ |
* +----------+ +-----------+ |
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
* +----------+ +-----------+ |
* | | | +---+ |
* +------------------------+-->|fin| - - - -
* | +---+ | +---+
* - - - - -|fin|<---------------------+
* +---+
*
* @param {Number} [code] Status code explaining why the connection is closing
* @param {(String|Buffer)} [data] The reason why the connection is
* closing
* @public
*/
close(code, data) {
if (this.readyState === _WebSocket.CLOSED) return;
if (this.readyState === _WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake(this, this._req, msg);
return;
}
if (this.readyState === _WebSocket.CLOSING) {
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
this._socket.end();
}
return;
}
this._readyState = _WebSocket.CLOSING;
this._sender.close(code, data, !this._isServer, (err) => {
if (err) return;
this._closeFrameSent = true;
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
this._socket.end();
}
});
setCloseTimer(this);
}
/**
* Pause the socket.
*
* @public
*/
pause() {
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
return;
}
this._paused = true;
this._socket.pause();
}
/**
* Send a ping.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the ping is sent
* @public
*/
ping(data, mask, cb2) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb2 = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb2 = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb2);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.ping(data || EMPTY_BUFFER, mask, cb2);
}
/**
* 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, cb2) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb2 = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb2 = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb2);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.pong(data || EMPTY_BUFFER, mask, cb2);
}
/**
* 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, cb2) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof options === "function") {
cb2 = options;
options = {};
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb2);
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, cb2);
}
/**
* 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;
module3.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 URL7) {
parsedUrl = address;
} else {
try {
parsedUrl = new URL7(address);
} catch (e7) {
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 = randomBytes2(16).toString("base64");
const request4 = isSecure ? https2.request : http5.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"] = format9({
[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 = request4(opts);
if (websocket._redirects) {
websocket.emit("redirect", websocket.url, req);
}
} else {
req = websocket._req = request4(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 URL7(location, address);
} catch (e7) {
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 = createHash8("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 = parse7(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();
}
}
__name(initAsClient, "initAsClient");
function emitErrorAndClose(websocket, err) {
websocket._readyState = WebSocket2.CLOSING;
websocket._errorEmitted = true;
websocket.emit("error", err);
websocket.emitClose();
}
__name(emitErrorAndClose, "emitErrorAndClose");
function netConnect(options) {
options.path = options.socketPath;
return net2.connect(options);
}
__name(netConnect, "netConnect");
function tlsConnect(options) {
options.path = void 0;
if (!options.servername && options.servername !== "") {
options.servername = net2.isIP(options.host) ? "" : options.host;
}
return tls.connect(options);
}
__name(tlsConnect, "tlsConnect");
function abortHandshake(websocket, stream2, message) {
websocket._readyState = WebSocket2.CLOSING;
const err = new Error(message);
Error.captureStackTrace(err, abortHandshake);
if (stream2.setHeader) {
stream2[kAborted] = true;
stream2.abort();
if (stream2.socket && !stream2.socket.destroyed) {
stream2.socket.destroy();
}
process.nextTick(emitErrorAndClose, websocket, err);
} else {
stream2.destroy(err);
stream2.once("error", websocket.emit.bind(websocket, "error"));
stream2.once("close", websocket.emitClose.bind(websocket));
}
}
__name(abortHandshake, "abortHandshake");
function sendAfterClose(websocket, data, cb2) {
if (data) {
const length = isBlob3(data) ? data.size : toBuffer(data).length;
if (websocket._socket) websocket._sender._bufferedBytes += length;
else websocket._bufferedAmount += length;
}
if (cb2) {
const err = new Error(
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
);
process.nextTick(cb2, err);
}
}
__name(sendAfterClose, "sendAfterClose");
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);
}
__name(receiverOnConclude, "receiverOnConclude");
function receiverOnDrain() {
const websocket = this[kWebSocket];
if (!websocket.isPaused) websocket._socket.resume();
}
__name(receiverOnDrain, "receiverOnDrain");
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]);
}
if (!websocket._errorEmitted) {
websocket._errorEmitted = true;
websocket.emit("error", err);
}
}
__name(receiverOnError, "receiverOnError");
function receiverOnFinish() {
this[kWebSocket].emitClose();
}
__name(receiverOnFinish, "receiverOnFinish");
function receiverOnMessage(data, isBinary) {
this[kWebSocket].emit("message", data, isBinary);
}
__name(receiverOnMessage, "receiverOnMessage");
function receiverOnPing(data) {
const websocket = this[kWebSocket];
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
websocket.emit("ping", data);
}
__name(receiverOnPing, "receiverOnPing");
function receiverOnPong(data) {
this[kWebSocket].emit("pong", data);
}
__name(receiverOnPong, "receiverOnPong");
function resume(stream2) {
stream2.resume();
}
__name(resume, "resume");
function senderOnError(err) {
const websocket = this[kWebSocket];
if (websocket.readyState === WebSocket2.CLOSED) return;
if (websocket.readyState === WebSocket2.OPEN) {
websocket._readyState = WebSocket2.CLOSING;
setCloseTimer(websocket);
}
this._socket.end();
if (!websocket._errorEmitted) {
websocket._errorEmitted = true;
websocket.emit("error", err);
}
}
__name(senderOnError, "senderOnError");
function setCloseTimer(websocket) {
websocket._closeTimer = setTimeout(
websocket._socket.destroy.bind(websocket._socket),
closeTimeout
);
}
__name(setCloseTimer, "setCloseTimer");
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);
}
}
__name(socketOnClose, "socketOnClose");
function socketOnData(chunk) {
if (!this[kWebSocket]._receiver.write(chunk)) {
this.pause();
}
}
__name(socketOnData, "socketOnData");
function socketOnEnd() {
const websocket = this[kWebSocket];
websocket._readyState = WebSocket2.CLOSING;
websocket._receiver.end();
this.end();
}
__name(socketOnEnd, "socketOnEnd");
function socketOnError() {
const websocket = this[kWebSocket];
this.removeListener("error", socketOnError);
this.on("error", NOOP);
if (websocket) {
websocket._readyState = WebSocket2.CLOSING;
this.destroy();
}
}
__name(socketOnError, "socketOnError");
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/subprotocol.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var { tokenChars } = require_validation();
function parse7(header) {
const protocols = /* @__PURE__ */ new Set();
let start = -1;
let end = -1;
let i5 = 0;
for (i5; i5 < header.length; i5++) {
const code = header.charCodeAt(i5);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i5;
} else if (i5 !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i5;
} else if (code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i5}`);
}
if (end === -1) end = i5;
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 ${i5}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError("Unexpected end of input");
}
const protocol = header.slice(start, i5);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
return protocols;
}
__name(parse7, "parse");
module3.exports = { parse: parse7 };
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/lib/websocket-server.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var EventEmitter5 = require("events");
var http5 = require("http");
var { Duplex: Duplex2 } = require("stream");
var { createHash: createHash8 } = require("crypto");
var extension = require_extension();
var PerMessageDeflate = require_permessage_deflate2();
var subprotocol = require_subprotocol();
var WebSocket2 = require_websocket2();
var { GUID, kWebSocket } = require_constants6();
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
var RUNNING = 0;
var CLOSING = 1;
var CLOSED = 2;
var WebSocketServer2 = class extends EventEmitter5 {
static {
__name(this, "WebSocketServer");
}
/**
* 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 = http5.createServer((req, res) => {
const body = http5.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: /* @__PURE__ */ __name((req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection);
}, "upgrade")
});
}
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(cb2) {
if (this._state === CLOSED) {
if (cb2) {
this.once("close", () => {
cb2(new Error("The server is not running"));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb2) this.once("close", cb2);
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, cb2) {
socket.on("error", socketOnError);
const key = req.headers["sec-websocket-key"];
const upgrade = req.headers.upgrade;
const version5 = +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 (version5 !== 8 && version5 !== 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[`${version5 === 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,
cb2
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb2);
}
/**
* 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, cb2) {
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 = createHash8("sha1").update(key + GUID).digest("base64");
const headers = [
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, void 0, this.options);
if (protocols.size) {
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value}`);
ws._extensions = extensions;
}
this.emit("headers", headers, req);
socket.write(headers.concat("\r\n").join("\r\n"));
socket.removeListener("error", socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on("close", () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb2(ws, req);
}
};
module3.exports = WebSocketServer2;
function addListeners(server, map2) {
for (const event of Object.keys(map2)) server.on(event, map2[event]);
return /* @__PURE__ */ __name(function removeListeners() {
for (const event of Object.keys(map2)) {
server.removeListener(event, map2[event]);
}
}, "removeListeners");
}
__name(addListeners, "addListeners");
function emitClose(server) {
server._state = CLOSED;
server.emit("close");
}
__name(emitClose, "emitClose");
function socketOnError() {
this.destroy();
}
__name(socketOnError, "socketOnError");
function abortHandshake(socket, code, message, headers) {
message = message || http5.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} ${http5.STATUS_CODES[code]}\r
` + Object.keys(headers).map((h6) => `${h6}: ${headers[h6]}`).join("\r\n") + "\r\n\r\n" + message
);
}
__name(abortHandshake, "abortHandshake");
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);
}
}
__name(abortHandshakeOrEmitwsClientError, "abortHandshakeOrEmitwsClientError");
}
});
// ../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/wrapper.mjs
var import_stream3, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
var init_wrapper = __esm({
"../../node_modules/.pnpm/ws@8.18.0/node_modules/ws/wrapper.mjs"() {
init_import_meta_url();
import_stream3 = __toESM(require_stream(), 1);
import_receiver = __toESM(require_receiver2(), 1);
import_sender = __toESM(require_sender2(), 1);
import_websocket = __toESM(require_websocket2(), 1);
import_websocket_server = __toESM(require_websocket_server(), 1);
wrapper_default = import_websocket.default;
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/typings/common-types.js
function assertNotStrictEqual(actual, expected, shim3, message) {
shim3.assert.notStrictEqual(actual, expected, message);
}
function assertSingleKey(actual, shim3) {
shim3.assert.strictEqual(typeof actual, "string");
}
function objectKeys(object) {
return Object.keys(object);
}
var init_common_types = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/typings/common-types.js"() {
init_import_meta_url();
__name(assertNotStrictEqual, "assertNotStrictEqual");
__name(assertSingleKey, "assertSingleKey");
__name(objectKeys, "objectKeys");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/is-promise.js
function isPromise(maybePromise) {
return !!maybePromise && !!maybePromise.then && typeof maybePromise.then === "function";
}
var init_is_promise = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/is-promise.js"() {
init_import_meta_url();
__name(isPromise, "isPromise");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/parse-command.js
function parseCommand2(cmd) {
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, " ");
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
const bregex = /\.*[\][<>]/g;
const firstCommand = splitCommand.shift();
if (!firstCommand)
throw new Error(`No command found in: ${cmd}`);
const parsedCommand = {
cmd: firstCommand.replace(bregex, ""),
demanded: [],
optional: []
};
splitCommand.forEach((cmd2, i5) => {
let variadic = false;
cmd2 = cmd2.replace(/\s/g, "");
if (/\.+[\]>]/.test(cmd2) && i5 === splitCommand.length - 1)
variadic = true;
if (/^\[/.test(cmd2)) {
parsedCommand.optional.push({
cmd: cmd2.replace(bregex, "").split("|"),
variadic
});
} else {
parsedCommand.demanded.push({
cmd: cmd2.replace(bregex, "").split("|"),
variadic
});
}
});
return parsedCommand;
}
var init_parse_command = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/parse-command.js"() {
init_import_meta_url();
__name(parseCommand2, "parseCommand");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/argsert.js
function argsert(arg1, arg2, arg3) {
function parseArgs() {
return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
parseCommand2(`cmd ${arg1}`),
arg2,
arg3
];
}
__name(parseArgs, "parseArgs");
try {
let position = 0;
const [parsed, callerArguments, _length] = parseArgs();
const args = [].slice.call(callerArguments);
while (args.length && args[args.length - 1] === void 0)
args.pop();
const length = _length || args.length;
if (length < parsed.demanded.length) {
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
}
const totalCommands = parsed.demanded.length + parsed.optional.length;
if (length > totalCommands) {
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
}
parsed.demanded.forEach((demanded) => {
const arg = args.shift();
const observedType = guessType(arg);
const matchingTypes = demanded.cmd.filter((type) => type === observedType || type === "*");
if (matchingTypes.length === 0)
argumentTypeError(observedType, demanded.cmd, position);
position += 1;
});
parsed.optional.forEach((optional) => {
if (args.length === 0)
return;
const arg = args.shift();
const observedType = guessType(arg);
const matchingTypes = optional.cmd.filter((type) => type === observedType || type === "*");
if (matchingTypes.length === 0)
argumentTypeError(observedType, optional.cmd, position);
position += 1;
});
} catch (err) {
console.warn(err.stack);
}
}
function guessType(arg) {
if (Array.isArray(arg)) {
return "array";
} else if (arg === null) {
return "null";
}
return typeof arg;
}
function argumentTypeError(observedType, allowedTypes, position) {
throw new YError(`Invalid ${positionName[position] || "manyith"} argument. Expected ${allowedTypes.join(" or ")} but received ${observedType}.`);
}
var positionName;
var init_argsert = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/argsert.js"() {
init_import_meta_url();
init_yerror();
init_parse_command();
positionName = ["first", "second", "third", "fourth", "fifth", "sixth"];
__name(argsert, "argsert");
__name(guessType, "guessType");
__name(argumentTypeError, "argumentTypeError");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/middleware.js
function commandMiddlewareFactory(commandMiddleware) {
if (!commandMiddleware)
return [];
return commandMiddleware.map((middleware) => {
middleware.applyBeforeValidation = false;
return middleware;
});
}
function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
return middlewares.reduce((acc, middleware) => {
if (middleware.applyBeforeValidation !== beforeValidation) {
return acc;
}
if (middleware.mutates) {
if (middleware.applied)
return acc;
middleware.applied = true;
}
if (isPromise(acc)) {
return acc.then((initialObj) => Promise.all([initialObj, middleware(initialObj, yargs)])).then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
} else {
const result = middleware(acc, yargs);
return isPromise(result) ? result.then((middlewareObj) => Object.assign(acc, middlewareObj)) : Object.assign(acc, result);
}
}, argv);
}
var GlobalMiddleware;
var init_middleware = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/middleware.js"() {
init_import_meta_url();
init_argsert();
init_is_promise();
GlobalMiddleware = class {
static {
__name(this, "GlobalMiddleware");
}
constructor(yargs) {
this.globalMiddleware = [];
this.frozens = [];
this.yargs = yargs;
}
addMiddleware(callback, applyBeforeValidation, global2 = true, mutates = false) {
argsert("<array|function> [boolean] [boolean] [boolean]", [callback, applyBeforeValidation, global2], arguments.length);
if (Array.isArray(callback)) {
for (let i5 = 0; i5 < callback.length; i5++) {
if (typeof callback[i5] !== "function") {
throw Error("middleware must be a function");
}
const m6 = callback[i5];
m6.applyBeforeValidation = applyBeforeValidation;
m6.global = global2;
}
Array.prototype.push.apply(this.globalMiddleware, callback);
} else if (typeof callback === "function") {
const m6 = callback;
m6.applyBeforeValidation = applyBeforeValidation;
m6.global = global2;
m6.mutates = mutates;
this.globalMiddleware.push(callback);
}
return this.yargs;
}
addCoerceMiddleware(callback, option) {
const aliases2 = this.yargs.getAliases();
this.globalMiddleware = this.globalMiddleware.filter((m6) => {
const toCheck = [...aliases2[option] || [], option];
if (!m6.option)
return true;
else
return !toCheck.includes(m6.option);
});
callback.option = option;
return this.addMiddleware(callback, true, true, true);
}
getMiddleware() {
return this.globalMiddleware;
}
freeze() {
this.frozens.push([...this.globalMiddleware]);
}
unfreeze() {
const frozen = this.frozens.pop();
if (frozen !== void 0)
this.globalMiddleware = frozen;
}
reset() {
this.globalMiddleware = this.globalMiddleware.filter((m6) => m6.global);
}
};
__name(commandMiddlewareFactory, "commandMiddlewareFactory");
__name(applyMiddleware, "applyMiddleware");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/maybe-async-result.js
function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
throw err;
}) {
try {
const result = isFunction(getResult) ? getResult() : getResult;
return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
} catch (err) {
return errorHandler(err);
}
}
function isFunction(arg) {
return typeof arg === "function";
}
var init_maybe_async_result = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/maybe-async-result.js"() {
init_import_meta_url();
init_is_promise();
__name(maybeAsyncResult, "maybeAsyncResult");
__name(isFunction, "isFunction");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/which-module.js
function whichModule(exported) {
if (typeof require === "undefined")
return null;
for (let i5 = 0, files = Object.keys(require.cache), mod; i5 < files.length; i5++) {
mod = require.cache[files[i5]];
if (mod.exports === exported)
return mod;
}
return null;
}
var init_which_module = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/which-module.js"() {
init_import_meta_url();
__name(whichModule, "whichModule");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/command.js
function command(usage2, validation2, globalMiddleware, shim3) {
return new CommandInstance(usage2, validation2, globalMiddleware, shim3);
}
function isCommandBuilderDefinition(builder) {
return typeof builder === "object" && !!builder.builder && typeof builder.handler === "function";
}
function isCommandAndAliases(cmd) {
return cmd.every((c6) => typeof c6 === "string");
}
function isCommandBuilderCallback(builder) {
return typeof builder === "function";
}
function isCommandBuilderOptionDefinitions(builder) {
return typeof builder === "object";
}
function isCommandHandlerDefinition(cmd) {
return typeof cmd === "object" && !Array.isArray(cmd);
}
var DEFAULT_MARKER, CommandInstance;
var init_command2 = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/command.js"() {
init_import_meta_url();
init_common_types();
init_is_promise();
init_middleware();
init_parse_command();
init_yargs_factory();
init_maybe_async_result();
init_which_module();
DEFAULT_MARKER = /(^\*)|(^\$0)/;
CommandInstance = class {
static {
__name(this, "CommandInstance");
}
constructor(usage2, validation2, globalMiddleware, shim3) {
this.requireCache = /* @__PURE__ */ new Set();
this.handlers = {};
this.aliasMap = {};
this.frozens = [];
this.shim = shim3;
this.usage = usage2;
this.globalMiddleware = globalMiddleware;
this.validation = validation2;
}
addDirectory(dir, req, callerFile, opts) {
opts = opts || {};
if (typeof opts.recurse !== "boolean")
opts.recurse = false;
if (!Array.isArray(opts.extensions))
opts.extensions = ["js"];
const parentVisit = typeof opts.visit === "function" ? opts.visit : (o5) => o5;
opts.visit = (obj, joined, filename) => {
const visited = parentVisit(obj, joined, filename);
if (visited) {
if (this.requireCache.has(joined))
return visited;
else
this.requireCache.add(joined);
this.addHandler(visited);
}
return visited;
};
this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
}
addHandler(cmd, description, builder, handler, commandMiddleware, deprecated2) {
let aliases2 = [];
const middlewares = commandMiddlewareFactory(commandMiddleware);
handler = handler || (() => {
});
if (Array.isArray(cmd)) {
if (isCommandAndAliases(cmd)) {
[cmd, ...aliases2] = cmd;
} else {
for (const command2 of cmd) {
this.addHandler(command2);
}
}
} else if (isCommandHandlerDefinition(cmd)) {
let command2 = Array.isArray(cmd.command) || typeof cmd.command === "string" ? cmd.command : this.moduleName(cmd);
if (cmd.aliases)
command2 = [].concat(command2).concat(cmd.aliases);
this.addHandler(command2, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
return;
} else if (isCommandBuilderDefinition(builder)) {
this.addHandler([cmd].concat(aliases2), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
return;
}
if (typeof cmd === "string") {
const parsedCommand = parseCommand2(cmd);
aliases2 = aliases2.map((alias) => parseCommand2(alias).cmd);
let isDefault = false;
const parsedAliases = [parsedCommand.cmd].concat(aliases2).filter((c6) => {
if (DEFAULT_MARKER.test(c6)) {
isDefault = true;
return false;
}
return true;
});
if (parsedAliases.length === 0 && isDefault)
parsedAliases.push("$0");
if (isDefault) {
parsedCommand.cmd = parsedAliases[0];
aliases2 = parsedAliases.slice(1);
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
}
aliases2.forEach((alias) => {
this.aliasMap[alias] = parsedCommand.cmd;
});
if (description !== false) {
this.usage.command(cmd, description, isDefault, aliases2, deprecated2);
}
this.handlers[parsedCommand.cmd] = {
original: cmd,
description,
handler,
builder: builder || {},
middlewares,
deprecated: deprecated2,
demanded: parsedCommand.demanded,
optional: parsedCommand.optional
};
if (isDefault)
this.defaultCommand = this.handlers[parsedCommand.cmd];
}
}
getCommandHandlers() {
return this.handlers;
}
getCommands() {
return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
}
hasDefaultCommand() {
return !!this.defaultCommand;
}
runCommand(command2, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
const commandHandler = this.handlers[command2] || this.handlers[this.aliasMap[command2]] || this.defaultCommand;
const currentContext = yargs.getInternalMethods().getContext();
const parentCommands = currentContext.commands.slice();
const isDefaultCommand = !command2;
if (command2) {
currentContext.commands.push(command2);
currentContext.fullCommands.push(commandHandler.original);
}
const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
return isPromise(builderResult) ? builderResult.then((result) => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
}
applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases2, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
const builder = commandHandler.builder;
let innerYargs = yargs;
if (isCommandBuilderCallback(builder)) {
yargs.getInternalMethods().getUsageInstance().freeze();
const builderOutput = builder(yargs.getInternalMethods().reset(aliases2), helpOrVersionSet);
if (isPromise(builderOutput)) {
return builderOutput.then((output) => {
innerYargs = isYargsInstance(output) ? output : yargs;
return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
});
}
} else if (isCommandBuilderOptionDefinitions(builder)) {
yargs.getInternalMethods().getUsageInstance().freeze();
innerYargs = yargs.getInternalMethods().reset(aliases2);
Object.keys(commandHandler.builder).forEach((key) => {
innerYargs.option(key, builder[key]);
});
}
return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
}
parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
if (isDefaultCommand)
innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
if (this.shouldUpdateUsage(innerYargs)) {
innerYargs.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
}
const innerArgv = innerYargs.getInternalMethods().runYargsParserAndExecuteCommands(null, void 0, true, commandIndex, helpOnly);
return isPromise(innerArgv) ? innerArgv.then((argv) => ({
aliases: innerYargs.parsed.aliases,
innerArgv: argv
})) : {
aliases: innerYargs.parsed.aliases,
innerArgv
};
}
shouldUpdateUsage(yargs) {
return !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && yargs.getInternalMethods().getUsageInstance().getUsage().length === 0;
}
usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
const c6 = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
const pc = parentCommands.filter((c7) => {
return !DEFAULT_MARKER.test(c7);
});
pc.push(c6);
return `$0 ${pc.join(" ")}`;
}
handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases2, yargs, middlewares, positionalMap) {
if (!yargs.getInternalMethods().getHasOutput()) {
const validation2 = yargs.getInternalMethods().runValidation(aliases2, positionalMap, yargs.parsed.error, isDefaultCommand);
innerArgv = maybeAsyncResult(innerArgv, (result) => {
validation2(result);
return result;
});
}
if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
yargs.getInternalMethods().setHasOutput();
const populateDoubleDash = !!yargs.getOptions().configuration["populate--"];
yargs.getInternalMethods().postProcess(innerArgv, populateDoubleDash, false, false);
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
innerArgv = maybeAsyncResult(innerArgv, (result) => {
const handlerResult = commandHandler.handler(result);
return isPromise(handlerResult) ? handlerResult.then(() => result) : result;
});
if (!isDefaultCommand) {
yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
}
if (isPromise(innerArgv) && !yargs.getInternalMethods().hasParseCallback()) {
innerArgv.catch((error2) => {
try {
yargs.getInternalMethods().getUsageInstance().fail(null, error2);
} catch (_err) {
}
});
}
}
if (!isDefaultCommand) {
currentContext.commands.pop();
currentContext.fullCommands.pop();
}
return innerArgv;
}
applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases2, yargs) {
let positionalMap = {};
if (helpOnly)
return innerArgv;
if (!yargs.getInternalMethods().getHasOutput()) {
positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
}
const middlewares = this.globalMiddleware.getMiddleware().slice(0).concat(commandHandler.middlewares);
const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
return isPromise(maybePromiseArgv) ? maybePromiseArgv.then((resolvedInnerArgv) => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases2, yargs, middlewares, positionalMap)) : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases2, yargs, middlewares, positionalMap);
}
populatePositionals(commandHandler, argv, context2, yargs) {
argv._ = argv._.slice(context2.commands.length);
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap = {};
this.validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift();
this.populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift();
this.populatePositional(maybe, argv, positionalMap);
}
argv._ = context2.commands.concat(argv._.map((a5) => "" + a5));
this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
return positionalMap;
}
populatePositional(positional, argv, positionalMap) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length)
positionalMap[cmd] = [String(argv._.shift())];
}
}
cmdToParseOptions(cmdString) {
const parseOptions = {
array: [],
default: {},
alias: {},
demand: {}
};
const parsed = parseCommand2(cmdString);
parsed.demanded.forEach((d6) => {
const [cmd, ...aliases2] = d6.cmd;
if (d6.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases2;
parseOptions.demand[cmd] = true;
});
parsed.optional.forEach((o5) => {
const [cmd, ...aliases2] = o5.cmd;
if (o5.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases2;
});
return parseOptions;
}
postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
}
options.array = options.array.concat(parseOptions.array);
options.config = {};
const unparsed = [];
Object.keys(positionalMap).forEach((key) => {
positionalMap[key].map((value) => {
if (options.configuration["unknown-options-as-args"])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
if (!unparsed.length)
return;
const config = Object.assign({}, options.configuration, {
"populate--": false
});
const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
configuration: config
}));
if (parsed.error) {
yargs.getInternalMethods().getUsageInstance().fail(parsed.error.message, parsed.error);
} else {
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach((key) => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach((key) => {
if (positionalKeys.includes(key)) {
if (!positionalMap[key])
positionalMap[key] = parsed.argv[key];
if (!this.isInConfigs(yargs, key) && !this.isDefaulted(yargs, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
argv[key] = [].concat(argv[key], parsed.argv[key]);
} else {
argv[key] = parsed.argv[key];
}
}
});
}
}
isDefaulted(yargs, key) {
const { default: defaults } = yargs.getOptions();
return Object.prototype.hasOwnProperty.call(defaults, key) || Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key));
}
isInConfigs(yargs, key) {
const { configObjects } = yargs.getOptions();
return configObjects.some((c6) => Object.prototype.hasOwnProperty.call(c6, key)) || configObjects.some((c6) => Object.prototype.hasOwnProperty.call(c6, this.shim.Parser.camelCase(key)));
}
runDefaultBuilderOn(yargs) {
if (!this.defaultCommand)
return;
if (this.shouldUpdateUsage(yargs)) {
const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) ? this.defaultCommand.original : this.defaultCommand.original.replace(/^[^[\]<>]*/, "$0 ");
yargs.getInternalMethods().getUsageInstance().usage(commandString, this.defaultCommand.description);
}
const builder = this.defaultCommand.builder;
if (isCommandBuilderCallback(builder)) {
return builder(yargs, true);
} else if (!isCommandBuilderDefinition(builder)) {
Object.keys(builder).forEach((key) => {
yargs.option(key, builder[key]);
});
}
return void 0;
}
moduleName(obj) {
const mod = whichModule(obj);
if (!mod)
throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
return this.commandFromFilename(mod.filename);
}
commandFromFilename(filename) {
return this.shim.path.basename(filename, this.shim.path.extname(filename));
}
extractDesc({ describe, description, desc }) {
for (const test of [describe, description, desc]) {
if (typeof test === "string" || test === false)
return test;
assertNotStrictEqual(test, true, this.shim);
}
return false;
}
freeze() {
this.frozens.push({
handlers: this.handlers,
aliasMap: this.aliasMap,
defaultCommand: this.defaultCommand
});
}
unfreeze() {
const frozen = this.frozens.pop();
assertNotStrictEqual(frozen, void 0, this.shim);
({
handlers: this.handlers,
aliasMap: this.aliasMap,
defaultCommand: this.defaultCommand
} = frozen);
}
reset() {
this.handlers = {};
this.aliasMap = {};
this.defaultCommand = void 0;
this.requireCache = /* @__PURE__ */ new Set();
return this;
}
};
__name(command, "command");
__name(isCommandBuilderDefinition, "isCommandBuilderDefinition");
__name(isCommandAndAliases, "isCommandAndAliases");
__name(isCommandBuilderCallback, "isCommandBuilderCallback");
__name(isCommandBuilderOptionDefinitions, "isCommandBuilderOptionDefinitions");
__name(isCommandHandlerDefinition, "isCommandHandlerDefinition");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/obj-filter.js
function objFilter(original = {}, filter = () => true) {
const obj = {};
objectKeys(original).forEach((key) => {
if (filter(key, original[key])) {
obj[key] = original[key];
}
});
return obj;
}
var init_obj_filter = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/obj-filter.js"() {
init_import_meta_url();
init_common_types();
__name(objFilter, "objFilter");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/set-blocking.js
function setBlocking(blocking) {
if (typeof process === "undefined")
return;
[process.stdout, process.stderr].forEach((_stream) => {
const stream2 = _stream;
if (stream2._handle && stream2.isTTY && typeof stream2._handle.setBlocking === "function") {
stream2._handle.setBlocking(blocking);
}
});
}
var init_set_blocking = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/set-blocking.js"() {
init_import_meta_url();
__name(setBlocking, "setBlocking");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/usage.js
function isBoolean2(fail) {
return typeof fail === "boolean";
}
function usage(yargs, shim3) {
const __ = shim3.y18n.__;
const self2 = {};
const fails = [];
self2.failFn = /* @__PURE__ */ __name(function failFn(f6) {
fails.push(f6);
}, "failFn");
let failMessage = null;
let globalFailMessage = null;
let showHelpOnFail = true;
self2.showHelpOnFail = /* @__PURE__ */ __name(function showHelpOnFailFn(arg1 = true, arg2) {
const [enabled, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
if (yargs.getInternalMethods().isGlobalContext()) {
globalFailMessage = message;
}
failMessage = message;
showHelpOnFail = enabled;
return self2;
}, "showHelpOnFailFn");
let failureOutput = false;
self2.fail = /* @__PURE__ */ __name(function fail(msg, err) {
const logger4 = yargs.getInternalMethods().getLoggerInstance();
if (fails.length) {
for (let i5 = fails.length - 1; i5 >= 0; --i5) {
const fail2 = fails[i5];
if (isBoolean2(fail2)) {
if (err)
throw err;
else if (msg)
throw Error(msg);
} else {
fail2(msg, err, self2);
}
}
} else {
if (yargs.getExitProcess())
setBlocking(true);
if (!failureOutput) {
failureOutput = true;
if (showHelpOnFail) {
yargs.showHelp("error");
logger4.error();
}
if (msg || err)
logger4.error(msg || err);
const globalOrCommandFailMessage = failMessage || globalFailMessage;
if (globalOrCommandFailMessage) {
if (msg || err)
logger4.error("");
logger4.error(globalOrCommandFailMessage);
}
}
err = err || new YError(msg);
if (yargs.getExitProcess()) {
return yargs.exit(1);
} else if (yargs.getInternalMethods().hasParseCallback()) {
return yargs.exit(1, err);
} else {
throw err;
}
}
}, "fail");
let usages = [];
let usageDisabled = false;
self2.usage = (msg, description) => {
if (msg === null) {
usageDisabled = true;
usages = [];
return self2;
}
usageDisabled = false;
usages.push([msg, description || ""]);
return self2;
};
self2.getUsage = () => {
return usages;
};
self2.getUsageDisabled = () => {
return usageDisabled;
};
self2.getPositionalGroupName = () => {
return __("Positionals:");
};
let examples = [];
self2.example = (cmd, description) => {
examples.push([cmd, description || ""]);
};
let commands5 = [];
self2.command = /* @__PURE__ */ __name(function command2(cmd, description, isDefault, aliases2, deprecated2 = false) {
if (isDefault) {
commands5 = commands5.map((cmdArray) => {
cmdArray[2] = false;
return cmdArray;
});
}
commands5.push([cmd, description || "", isDefault, aliases2, deprecated2]);
}, "command");
self2.getCommands = () => commands5;
let descriptions = {};
self2.describe = /* @__PURE__ */ __name(function describe(keyOrKeys, desc) {
if (Array.isArray(keyOrKeys)) {
keyOrKeys.forEach((k6) => {
self2.describe(k6, desc);
});
} else if (typeof keyOrKeys === "object") {
Object.keys(keyOrKeys).forEach((k6) => {
self2.describe(k6, keyOrKeys[k6]);
});
} else {
descriptions[keyOrKeys] = desc;
}
}, "describe");
self2.getDescriptions = () => descriptions;
let epilogs = [];
self2.epilog = (msg) => {
epilogs.push(msg);
};
let wrapSet = false;
let wrap4;
self2.wrap = (cols) => {
wrapSet = true;
wrap4 = cols;
};
self2.getWrap = () => {
if (shim3.getEnv("YARGS_DISABLE_WRAP")) {
return null;
}
if (!wrapSet) {
wrap4 = windowWidth();
wrapSet = true;
}
return wrap4;
};
const deferY18nLookupPrefix = "__yargsString__:";
self2.deferY18nLookup = (str) => deferY18nLookupPrefix + str;
self2.help = /* @__PURE__ */ __name(function help() {
if (cachedHelpMessage)
return cachedHelpMessage;
normalizeAliases();
const base$0 = yargs.customScriptName ? yargs.$0 : shim3.path.basename(yargs.$0);
const demandedOptions = yargs.getDemandedOptions();
const demandedCommands = yargs.getDemandedCommands();
const deprecatedOptions = yargs.getDeprecatedOptions();
const groups = yargs.getGroups();
const options = yargs.getOptions();
let keys = [];
keys = keys.concat(Object.keys(descriptions));
keys = keys.concat(Object.keys(demandedOptions));
keys = keys.concat(Object.keys(demandedCommands));
keys = keys.concat(Object.keys(options.default));
keys = keys.filter(filterHiddenOptions);
keys = Object.keys(keys.reduce((acc, key) => {
if (key !== "_")
acc[key] = true;
return acc;
}, {}));
const theWrap = self2.getWrap();
const ui2 = shim3.cliui({
width: theWrap,
wrap: !!theWrap
});
if (!usageDisabled) {
if (usages.length) {
usages.forEach((usage2) => {
ui2.div({ text: `${usage2[0].replace(/\$0/g, base$0)}` });
if (usage2[1]) {
ui2.div({ text: `${usage2[1]}`, padding: [1, 0, 0, 0] });
}
});
ui2.div();
} else if (commands5.length) {
let u5 = null;
if (demandedCommands._) {
u5 = `${base$0} <${__("command")}>
`;
} else {
u5 = `${base$0} [${__("command")}]
`;
}
ui2.div(`${u5}`);
}
}
if (commands5.length > 1 || commands5.length === 1 && !commands5[0][2]) {
ui2.div(__("Commands:"));
const context2 = yargs.getInternalMethods().getContext();
const parentCommands = context2.commands.length ? `${context2.commands.join(" ")} ` : "";
if (yargs.getInternalMethods().getParserConfiguration()["sort-commands"] === true) {
commands5 = commands5.sort((a5, b6) => a5[0].localeCompare(b6[0]));
}
const prefix = base$0 ? `${base$0} ` : "";
commands5.forEach((command2) => {
const commandString = `${prefix}${parentCommands}${command2[0].replace(/^\$0 ?/, "")}`;
ui2.span({
text: commandString,
padding: [0, 2, 0, 2],
width: maxWidth(commands5, theWrap, `${base$0}${parentCommands}`) + 4
}, { text: command2[1] });
const hints = [];
if (command2[2])
hints.push(`[${__("default")}]`);
if (command2[3] && command2[3].length) {
hints.push(`[${__("aliases:")} ${command2[3].join(", ")}]`);
}
if (command2[4]) {
if (typeof command2[4] === "string") {
hints.push(`[${__("deprecated: %s", command2[4])}]`);
} else {
hints.push(`[${__("deprecated")}]`);
}
}
if (hints.length) {
ui2.div({
text: hints.join(" "),
padding: [0, 0, 0, 2],
align: "right"
});
} else {
ui2.div();
}
});
ui2.div();
}
const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
keys = keys.filter((key) => !yargs.parsed.newAliases[key] && aliasKeys.every((alias) => (options.alias[alias] || []).indexOf(key) === -1));
const defaultGroup = __("Options:");
if (!groups[defaultGroup])
groups[defaultGroup] = [];
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
const isLongSwitch = /* @__PURE__ */ __name((sw) => /^--/.test(getText(sw)), "isLongSwitch");
const displayedGroups = Object.keys(groups).filter((groupName) => groups[groupName].length > 0).map((groupName) => {
const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
if (aliasKeys.includes(key))
return key;
for (let i5 = 0, aliasKey; (aliasKey = aliasKeys[i5]) !== void 0; i5++) {
if ((options.alias[aliasKey] || []).includes(key))
return aliasKey;
}
return key;
});
return { groupName, normalizedKeys };
}).filter(({ normalizedKeys }) => normalizedKeys.length > 0).map(({ groupName, normalizedKeys }) => {
const switches = normalizedKeys.reduce((acc, key) => {
acc[key] = [key].concat(options.alias[key] || []).map((sw) => {
if (groupName === self2.getPositionalGroupName())
return sw;
else {
return (/^[0-9]$/.test(sw) ? options.boolean.includes(key) ? "-" : "--" : sw.length > 1 ? "--" : "-") + sw;
}
}).sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) ? 0 : isLongSwitch(sw1) ? 1 : -1).join(", ");
return acc;
}, {});
return { groupName, normalizedKeys, switches };
});
const shortSwitchesUsed = displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).some(({ normalizedKeys, switches }) => !normalizedKeys.every((key) => isLongSwitch(switches[key])));
if (shortSwitchesUsed) {
displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).forEach(({ normalizedKeys, switches }) => {
normalizedKeys.forEach((key) => {
if (isLongSwitch(switches[key])) {
switches[key] = addIndentation(switches[key], "-x, ".length);
}
});
});
}
displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
ui2.div(groupName);
normalizedKeys.forEach((key) => {
const kswitch = switches[key];
let desc = descriptions[key] || "";
let type = null;
if (desc.includes(deferY18nLookupPrefix))
desc = __(desc.substring(deferY18nLookupPrefix.length));
if (options.boolean.includes(key))
type = `[${__("boolean")}]`;
if (options.count.includes(key))
type = `[${__("count")}]`;
if (options.string.includes(key))
type = `[${__("string")}]`;
if (options.normalize.includes(key))
type = `[${__("string")}]`;
if (options.array.includes(key))
type = `[${__("array")}]`;
if (options.number.includes(key))
type = `[${__("number")}]`;
const deprecatedExtra = /* @__PURE__ */ __name((deprecated2) => typeof deprecated2 === "string" ? `[${__("deprecated: %s", deprecated2)}]` : `[${__("deprecated")}]`, "deprecatedExtra");
const extra = [
key in deprecatedOptions ? deprecatedExtra(deprecatedOptions[key]) : null,
type,
key in demandedOptions ? `[${__("required")}]` : null,
options.choices && options.choices[key] ? `[${__("choices:")} ${self2.stringifiedValues(options.choices[key])}]` : null,
defaultString(options.default[key], options.defaultDescription[key])
].filter(Boolean).join(" ");
ui2.span({
text: getText(kswitch),
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
width: maxWidth(switches, theWrap) + 4
}, desc);
const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()["hide-types"] === true;
if (extra && !shouldHideOptionExtras)
ui2.div({ text: extra, padding: [0, 0, 0, 2], align: "right" });
else
ui2.div();
});
ui2.div();
});
if (examples.length) {
ui2.div(__("Examples:"));
examples.forEach((example) => {
example[0] = example[0].replace(/\$0/g, base$0);
});
examples.forEach((example) => {
if (example[1] === "") {
ui2.div({
text: example[0],
padding: [0, 2, 0, 2]
});
} else {
ui2.div({
text: example[0],
padding: [0, 2, 0, 2],
width: maxWidth(examples, theWrap) + 4
}, {
text: example[1]
});
}
});
ui2.div();
}
if (epilogs.length > 0) {
const e7 = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
ui2.div(`${e7}
`);
}
return ui2.toString().replace(/\s*$/, "");
}, "help");
function maxWidth(table, theWrap, modifier) {
let width = 0;
if (!Array.isArray(table)) {
table = Object.values(table).map((v7) => [v7]);
}
table.forEach((v7) => {
width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText(v7[0])}` : getText(v7[0])) + getIndentation(v7[0]), width);
});
if (theWrap)
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
return width;
}
__name(maxWidth, "maxWidth");
function normalizeAliases() {
const demandedOptions = yargs.getDemandedOptions();
const options = yargs.getOptions();
(Object.keys(options.alias) || []).forEach((key) => {
options.alias[key].forEach((alias) => {
if (descriptions[alias])
self2.describe(key, descriptions[alias]);
if (alias in demandedOptions)
yargs.demandOption(key, demandedOptions[alias]);
if (options.boolean.includes(alias))
yargs.boolean(key);
if (options.count.includes(alias))
yargs.count(key);
if (options.string.includes(alias))
yargs.string(key);
if (options.normalize.includes(alias))
yargs.normalize(key);
if (options.array.includes(alias))
yargs.array(key);
if (options.number.includes(alias))
yargs.number(key);
});
});
}
__name(normalizeAliases, "normalizeAliases");
let cachedHelpMessage;
self2.cacheHelpMessage = function() {
cachedHelpMessage = this.help();
};
self2.clearCachedHelpMessage = function() {
cachedHelpMessage = void 0;
};
self2.hasCachedHelpMessage = function() {
return !!cachedHelpMessage;
};
function addUngroupedKeys(keys, aliases2, groups, defaultGroup) {
let groupedKeys = [];
let toCheck = null;
Object.keys(groups).forEach((group) => {
groupedKeys = groupedKeys.concat(groups[group]);
});
keys.forEach((key) => {
toCheck = [key].concat(aliases2[key]);
if (!toCheck.some((k6) => groupedKeys.indexOf(k6) !== -1)) {
groups[defaultGroup].push(key);
}
});
return groupedKeys;
}
__name(addUngroupedKeys, "addUngroupedKeys");
function filterHiddenOptions(key) {
return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt];
}
__name(filterHiddenOptions, "filterHiddenOptions");
self2.showHelp = (level) => {
const logger4 = yargs.getInternalMethods().getLoggerInstance();
if (!level)
level = "error";
const emit = typeof level === "function" ? level : logger4[level];
emit(self2.help());
};
self2.functionDescription = (fn2) => {
const description = fn2.name ? shim3.Parser.decamelize(fn2.name, "-") : __("generated-value");
return ["(", description, ")"].join("");
};
self2.stringifiedValues = /* @__PURE__ */ __name(function stringifiedValues(values, separator) {
let string = "";
const sep5 = separator || ", ";
const array = [].concat(values);
if (!values || !array.length)
return string;
array.forEach((value) => {
if (string.length)
string += sep5;
string += JSON.stringify(value);
});
return string;
}, "stringifiedValues");
function defaultString(value, defaultDescription) {
let string = `[${__("default:")} `;
if (value === void 0 && !defaultDescription)
return null;
if (defaultDescription) {
string += defaultDescription;
} else {
switch (typeof value) {
case "string":
string += `"${value}"`;
break;
case "object":
string += JSON.stringify(value);
break;
default:
string += value;
}
}
return `${string}]`;
}
__name(defaultString, "defaultString");
function windowWidth() {
const maxWidth2 = 80;
if (shim3.process.stdColumns) {
return Math.min(maxWidth2, shim3.process.stdColumns);
} else {
return maxWidth2;
}
}
__name(windowWidth, "windowWidth");
let version5 = null;
self2.version = (ver) => {
version5 = ver;
};
self2.showVersion = (level) => {
const logger4 = yargs.getInternalMethods().getLoggerInstance();
if (!level)
level = "error";
const emit = typeof level === "function" ? level : logger4[level];
emit(version5);
};
self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
failMessage = null;
failureOutput = false;
usages = [];
usageDisabled = false;
epilogs = [];
examples = [];
commands5 = [];
descriptions = objFilter(descriptions, (k6) => !localLookup[k6]);
return self2;
}, "reset");
const frozens = [];
self2.freeze = /* @__PURE__ */ __name(function freeze() {
frozens.push({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands: commands5,
descriptions
});
}, "freeze");
self2.unfreeze = /* @__PURE__ */ __name(function unfreeze(defaultCommand = false) {
const frozen = frozens.pop();
if (!frozen)
return;
if (defaultCommand) {
descriptions = { ...frozen.descriptions, ...descriptions };
commands5 = [...frozen.commands, ...commands5];
usages = [...frozen.usages, ...usages];
examples = [...frozen.examples, ...examples];
epilogs = [...frozen.epilogs, ...epilogs];
} else {
({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands: commands5,
descriptions
} = frozen);
}
}, "unfreeze");
return self2;
}
function isIndentedText(text) {
return typeof text === "object";
}
function addIndentation(text, indent) {
return isIndentedText(text) ? { text: text.text, indentation: text.indentation + indent } : { text, indentation: indent };
}
function getIndentation(text) {
return isIndentedText(text) ? text.indentation : 0;
}
function getText(text) {
return isIndentedText(text) ? text.text : text;
}
var init_usage = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/usage.js"() {
init_import_meta_url();
init_obj_filter();
init_yerror();
init_set_blocking();
__name(isBoolean2, "isBoolean");
__name(usage, "usage");
__name(isIndentedText, "isIndentedText");
__name(addIndentation, "addIndentation");
__name(getIndentation, "getIndentation");
__name(getText, "getText");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/completion-templates.js
var completionShTemplate, completionZshTemplate;
var init_completion_templates = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/completion-templates.js"() {
init_import_meta_url();
completionShTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_{{app_name}}_yargs_completions()
{
local cur_word args type_list
cur_word="\${COMP_WORDS[COMP_CWORD]}"
args=("\${COMP_WORDS[@]}")
# ask yargs to generate completions.
type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
# if no match was found, fall back to filename completion
if [ \${#COMPREPLY[@]} -eq 0 ]; then
COMPREPLY=()
fi
return 0
}
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
completionZshTemplate = `#compdef {{app_name}}
###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
#
_{{app_name}}_yargs_completions()
{
local reply
local si=$IFS
IFS=$'
' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
IFS=$si
_describe 'values' reply
}
compdef _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/completion.js
function completion(yargs, usage2, command2, shim3) {
return new Completion(yargs, usage2, command2, shim3);
}
function isSyncCompletionFunction(completionFunction) {
return completionFunction.length < 3;
}
function isFallbackCompletionFunction(completionFunction) {
return completionFunction.length > 3;
}
var Completion;
var init_completion = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/completion.js"() {
init_import_meta_url();
init_command2();
init_common_types();
init_completion_templates();
init_is_promise();
init_parse_command();
Completion = class {
static {
__name(this, "Completion");
}
constructor(yargs, usage2, command2, shim3) {
var _a4, _b2, _c3;
this.yargs = yargs;
this.usage = usage2;
this.command = command2;
this.shim = shim3;
this.completionKey = "get-yargs-completions";
this.aliases = null;
this.customCompletionFunction = null;
this.indexAfterLastReset = 0;
this.zshShell = (_c3 = ((_a4 = this.shim.getEnv("SHELL")) === null || _a4 === void 0 ? void 0 : _a4.includes("zsh")) || ((_b2 = this.shim.getEnv("ZSH_NAME")) === null || _b2 === void 0 ? void 0 : _b2.includes("zsh"))) !== null && _c3 !== void 0 ? _c3 : false;
}
defaultCompletion(args, argv, current, done) {
const handlers2 = this.command.getCommandHandlers();
for (let i5 = 0, ii = args.length; i5 < ii; ++i5) {
if (handlers2[args[i5]] && handlers2[args[i5]].builder) {
const builder = handlers2[args[i5]].builder;
if (isCommandBuilderCallback(builder)) {
this.indexAfterLastReset = i5 + 1;
const y4 = this.yargs.getInternalMethods().reset();
builder(y4, true);
return y4.argv;
}
}
}
const completions = [];
this.commandCompletions(completions, args, current);
this.optionCompletions(completions, args, argv, current);
this.choicesFromOptionsCompletions(completions, args, argv, current);
this.choicesFromPositionalsCompletions(completions, args, argv, current);
done(null, completions);
}
commandCompletions(completions, args, current) {
const parentCommands = this.yargs.getInternalMethods().getContext().commands;
if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args)) {
this.usage.getCommands().forEach((usageCommand) => {
const commandName = parseCommand2(usageCommand[0]).cmd;
if (args.indexOf(commandName) === -1) {
if (!this.zshShell) {
completions.push(commandName);
} else {
const desc = usageCommand[1] || "";
completions.push(commandName.replace(/:/g, "\\:") + ":" + desc);
}
}
});
}
}
optionCompletions(completions, args, argv, current) {
if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args)) {
const options = this.yargs.getOptions();
const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
Object.keys(options.key).forEach((key) => {
const negable = !!options.configuration["boolean-negation"] && options.boolean.includes(key);
const isPositionalKey = positionalKeys.includes(key);
if (!isPositionalKey && !options.hiddenOptions.includes(key) && !this.argsContainKey(args, key, negable)) {
this.completeOptionKey(key, completions, current, negable && !!options.default[key]);
}
});
}
}
choicesFromOptionsCompletions(completions, args, argv, current) {
if (this.previousArgHasChoices(args)) {
const choices = this.getPreviousArgChoices(args);
if (choices && choices.length > 0) {
completions.push(...choices.map((c6) => c6.replace(/:/g, "\\:")));
}
}
}
choicesFromPositionalsCompletions(completions, args, argv, current) {
if (current === "" && completions.length > 0 && this.previousArgHasChoices(args)) {
return;
}
const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + 1);
const positionalKey = positionalKeys[argv._.length - offset - 1];
if (!positionalKey) {
return;
}
const choices = this.yargs.getOptions().choices[positionalKey] || [];
for (const choice of choices) {
if (choice.startsWith(current)) {
completions.push(choice.replace(/:/g, "\\:"));
}
}
}
getPreviousArgChoices(args) {
if (args.length < 1)
return;
let previousArg = args[args.length - 1];
let filter = "";
if (!previousArg.startsWith("-") && args.length > 1) {
filter = previousArg;
previousArg = args[args.length - 2];
}
if (!previousArg.startsWith("-"))
return;
const previousArgKey = previousArg.replace(/^-+/, "");
const options = this.yargs.getOptions();
const possibleAliases = [
previousArgKey,
...this.yargs.getAliases()[previousArgKey] || []
];
let choices;
for (const possibleAlias of possibleAliases) {
if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && Array.isArray(options.choices[possibleAlias])) {
choices = options.choices[possibleAlias];
break;
}
}
if (choices) {
return choices.filter((choice) => !filter || choice.startsWith(filter));
}
}
previousArgHasChoices(args) {
const choices = this.getPreviousArgChoices(args);
return choices !== void 0 && choices.length > 0;
}
argsContainKey(args, key, negable) {
const argsContains = /* @__PURE__ */ __name((s5) => args.indexOf((/^[^0-9]$/.test(s5) ? "-" : "--") + s5) !== -1, "argsContains");
if (argsContains(key))
return true;
if (negable && argsContains(`no-${key}`))
return true;
if (this.aliases) {
for (const alias of this.aliases[key]) {
if (argsContains(alias))
return true;
}
}
return false;
}
completeOptionKey(key, completions, current, negable) {
var _a4, _b2, _c3, _d2;
let keyWithDesc = key;
if (this.zshShell) {
const descs = this.usage.getDescriptions();
const aliasKey = (_b2 = (_a4 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a4 === void 0 ? void 0 : _a4[key]) === null || _b2 === void 0 ? void 0 : _b2.find((alias) => {
const desc2 = descs[alias];
return typeof desc2 === "string" && desc2.length > 0;
});
const descFromAlias = aliasKey ? descs[aliasKey] : void 0;
const desc = (_d2 = (_c3 = descs[key]) !== null && _c3 !== void 0 ? _c3 : descFromAlias) !== null && _d2 !== void 0 ? _d2 : "";
keyWithDesc = `${key.replace(/:/g, "\\:")}:${desc.replace("__yargsString__:", "").replace(/(\r\n|\n|\r)/gm, " ")}`;
}
const startsByTwoDashes = /* @__PURE__ */ __name((s5) => /^--/.test(s5), "startsByTwoDashes");
const isShortOption = /* @__PURE__ */ __name((s5) => /^[^0-9]$/.test(s5), "isShortOption");
const dashes = !startsByTwoDashes(current) && isShortOption(key) ? "-" : "--";
completions.push(dashes + keyWithDesc);
if (negable) {
completions.push(dashes + "no-" + keyWithDesc);
}
}
customCompletion(args, argv, current, done) {
assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
if (isSyncCompletionFunction(this.customCompletionFunction)) {
const result = this.customCompletionFunction(current, argv);
if (isPromise(result)) {
return result.then((list) => {
this.shim.process.nextTick(() => {
done(null, list);
});
}).catch((err) => {
this.shim.process.nextTick(() => {
done(err, void 0);
});
});
}
return done(null, result);
} else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), (completions) => {
done(null, completions);
});
} else {
return this.customCompletionFunction(current, argv, (completions) => {
done(null, completions);
});
}
}
getCompletion(args, done) {
const current = args.length ? args[args.length - 1] : "";
const argv = this.yargs.parse(args, true);
const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args, argv2, current, done) : (argv2) => this.defaultCompletion(args, argv2, current, done);
return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
}
generateCompletionScript($0, cmd) {
let script = this.zshShell ? completionZshTemplate : completionShTemplate;
const name2 = this.shim.path.basename($0);
if ($0.match(/\.js$/))
$0 = `./${$0}`;
script = script.replace(/{{app_name}}/g, name2);
script = script.replace(/{{completion_command}}/g, cmd);
return script.replace(/{{app_path}}/g, $0);
}
registerFunction(fn2) {
this.customCompletionFunction = fn2;
}
setParsed(parsed) {
this.aliases = parsed.aliases;
}
};
__name(completion, "completion");
__name(isSyncCompletionFunction, "isSyncCompletionFunction");
__name(isFallbackCompletionFunction, "isFallbackCompletionFunction");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/levenshtein.js
function levenshtein(a5, b6) {
if (a5.length === 0)
return b6.length;
if (b6.length === 0)
return a5.length;
const matrix = [];
let i5;
for (i5 = 0; i5 <= b6.length; i5++) {
matrix[i5] = [i5];
}
let j6;
for (j6 = 0; j6 <= a5.length; j6++) {
matrix[0][j6] = j6;
}
for (i5 = 1; i5 <= b6.length; i5++) {
for (j6 = 1; j6 <= a5.length; j6++) {
if (b6.charAt(i5 - 1) === a5.charAt(j6 - 1)) {
matrix[i5][j6] = matrix[i5 - 1][j6 - 1];
} else {
if (i5 > 1 && j6 > 1 && b6.charAt(i5 - 2) === a5.charAt(j6 - 1) && b6.charAt(i5 - 1) === a5.charAt(j6 - 2)) {
matrix[i5][j6] = matrix[i5 - 2][j6 - 2] + 1;
} else {
matrix[i5][j6] = Math.min(matrix[i5 - 1][j6 - 1] + 1, Math.min(matrix[i5][j6 - 1] + 1, matrix[i5 - 1][j6] + 1));
}
}
}
}
return matrix[b6.length][a5.length];
}
var init_levenshtein = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/utils/levenshtein.js"() {
init_import_meta_url();
__name(levenshtein, "levenshtein");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/validation.js
function validation(yargs, usage2, shim3) {
const __ = shim3.y18n.__;
const __n = shim3.y18n.__n;
const self2 = {};
self2.nonOptionCount = /* @__PURE__ */ __name(function nonOptionCount(argv) {
const demandedCommands = yargs.getDemandedCommands();
const positionalCount = argv._.length + (argv["--"] ? argv["--"].length : 0);
const _s2 = positionalCount - yargs.getInternalMethods().getContext().commands.length;
if (demandedCommands._ && (_s2 < demandedCommands._.min || _s2 > demandedCommands._.max)) {
if (_s2 < demandedCommands._.min) {
if (demandedCommands._.minMsg !== void 0) {
usage2.fail(demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s2.toString()).replace(/\$1/, demandedCommands._.min.toString()) : null);
} else {
usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", _s2, _s2.toString(), demandedCommands._.min.toString()));
}
} else if (_s2 > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== void 0) {
usage2.fail(demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s2.toString()).replace(/\$1/, demandedCommands._.max.toString()) : null);
} else {
usage2.fail(__n("Too many non-option arguments: got %s, maximum of %s", "Too many non-option arguments: got %s, maximum of %s", _s2, _s2.toString(), demandedCommands._.max.toString()));
}
}
}
}, "nonOptionCount");
self2.positionalCount = /* @__PURE__ */ __name(function positionalCount(required, observed) {
if (observed < required) {
usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", observed, observed + "", required + ""));
}
}, "positionalCount");
self2.requiredArguments = /* @__PURE__ */ __name(function requiredArguments(argv, demandedOptions) {
let missing = null;
for (const key of Object.keys(demandedOptions)) {
if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === "undefined") {
missing = missing || {};
missing[key] = demandedOptions[key];
}
}
if (missing) {
const customMsgs = [];
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg);
}
}
const customMsg = customMsgs.length ? `
${customMsgs.join("\n")}` : "";
usage2.fail(__n("Missing required argument: %s", "Missing required arguments: %s", Object.keys(missing).length, Object.keys(missing).join(", ") + customMsg));
}
}, "requiredArguments");
self2.unknownArguments = /* @__PURE__ */ __name(function unknownArguments(argv, aliases2, positionalMap, isDefaultCommand, checkPositionals = true) {
var _a4;
const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
const unknown = [];
const currentContext = yargs.getInternalMethods().getContext();
Object.keys(argv).forEach((key) => {
if (!specialKeys.includes(key) && !Object.prototype.hasOwnProperty.call(positionalMap, key) && !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && !self2.isValidAndSomeAliasIsNotNew(key, aliases2)) {
unknown.push(key);
}
});
if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
argv._.slice(currentContext.commands.length).forEach((key) => {
if (!commandKeys.includes("" + key)) {
unknown.push("" + key);
}
});
}
if (checkPositionals) {
const demandedCommands = yargs.getDemandedCommands();
const maxNonOptDemanded = ((_a4 = demandedCommands._) === null || _a4 === void 0 ? void 0 : _a4.max) || 0;
const expected = currentContext.commands.length + maxNonOptDemanded;
if (expected < argv._.length) {
argv._.slice(expected).forEach((key) => {
key = String(key);
if (!currentContext.commands.includes(key) && !unknown.includes(key)) {
unknown.push(key);
}
});
}
}
if (unknown.length) {
usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown.length, unknown.map((s5) => s5.trim() ? s5 : `"${s5}"`).join(", ")));
}
}, "unknownArguments");
self2.unknownCommands = /* @__PURE__ */ __name(function unknownCommands(argv) {
const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
const unknown = [];
const currentContext = yargs.getInternalMethods().getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach((key) => {
if (!commandKeys.includes("" + key)) {
unknown.push("" + key);
}
});
}
if (unknown.length > 0) {
usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown.length, unknown.join(", ")));
return true;
} else {
return false;
}
}, "unknownCommands");
self2.isValidAndSomeAliasIsNotNew = /* @__PURE__ */ __name(function isValidAndSomeAliasIsNotNew(key, aliases2) {
if (!Object.prototype.hasOwnProperty.call(aliases2, key)) {
return false;
}
const newAliases = yargs.parsed.newAliases;
return [key, ...aliases2[key]].some((a5) => !Object.prototype.hasOwnProperty.call(newAliases, a5) || !newAliases[key]);
}, "isValidAndSomeAliasIsNotNew");
self2.limitedChoices = /* @__PURE__ */ __name(function limitedChoices(argv) {
const options = yargs.getOptions();
const invalid = {};
if (!Object.keys(options.choices).length)
return;
Object.keys(argv).forEach((key) => {
if (specialKeys.indexOf(key) === -1 && Object.prototype.hasOwnProperty.call(options.choices, key)) {
[].concat(argv[key]).forEach((value) => {
if (options.choices[key].indexOf(value) === -1 && value !== void 0) {
invalid[key] = (invalid[key] || []).concat(value);
}
});
}
});
const invalidKeys = Object.keys(invalid);
if (!invalidKeys.length)
return;
let msg = __("Invalid values:");
invalidKeys.forEach((key) => {
msg += `
${__("Argument: %s, Given: %s, Choices: %s", key, usage2.stringifiedValues(invalid[key]), usage2.stringifiedValues(options.choices[key]))}`;
});
usage2.fail(msg);
}, "limitedChoices");
let implied = {};
self2.implies = /* @__PURE__ */ __name(function implies(key, value) {
argsert("<string|object> [array|number|string]", [key, value], arguments.length);
if (typeof key === "object") {
Object.keys(key).forEach((k6) => {
self2.implies(k6, key[k6]);
});
} else {
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
value.forEach((i5) => self2.implies(key, i5));
} else {
assertNotStrictEqual(value, void 0, shim3);
implied[key].push(value);
}
}
}, "implies");
self2.getImplied = /* @__PURE__ */ __name(function getImplied() {
return implied;
}, "getImplied");
function keyExists(argv, val2) {
const num = Number(val2);
val2 = isNaN(num) ? val2 : num;
if (typeof val2 === "number") {
val2 = argv._.length >= val2;
} else if (val2.match(/^--no-.+/)) {
val2 = val2.match(/^--no-(.+)/)[1];
val2 = !Object.prototype.hasOwnProperty.call(argv, val2);
} else {
val2 = Object.prototype.hasOwnProperty.call(argv, val2);
}
return val2;
}
__name(keyExists, "keyExists");
self2.implications = /* @__PURE__ */ __name(function implications(argv) {
const implyFail = [];
Object.keys(implied).forEach((key) => {
const origKey = key;
(implied[key] || []).forEach((value) => {
let key2 = origKey;
const origValue = value;
key2 = keyExists(argv, key2);
value = keyExists(argv, value);
if (key2 && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
}
});
});
if (implyFail.length) {
let msg = `${__("Implications failed:")}
`;
implyFail.forEach((value) => {
msg += value;
});
usage2.fail(msg);
}
}, "implications");
let conflicting = {};
self2.conflicts = /* @__PURE__ */ __name(function conflicts(key, value) {
argsert("<string|object> [array|string]", [key, value], arguments.length);
if (typeof key === "object") {
Object.keys(key).forEach((k6) => {
self2.conflicts(k6, key[k6]);
});
} else {
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
value.forEach((i5) => self2.conflicts(key, i5));
} else {
conflicting[key].push(value);
}
}
}, "conflicts");
self2.getConflicting = () => conflicting;
self2.conflicting = /* @__PURE__ */ __name(function conflictingFn(argv) {
Object.keys(argv).forEach((key) => {
if (conflicting[key]) {
conflicting[key].forEach((value) => {
if (value && argv[key] !== void 0 && argv[value] !== void 0) {
usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
}
});
}
});
if (yargs.getInternalMethods().getParserConfiguration()["strip-dashed"]) {
Object.keys(conflicting).forEach((key) => {
conflicting[key].forEach((value) => {
if (value && argv[shim3.Parser.camelCase(key)] !== void 0 && argv[shim3.Parser.camelCase(value)] !== void 0) {
usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
}
});
});
}
}, "conflictingFn");
self2.recommendCommands = /* @__PURE__ */ __name(function recommendCommands(cmd, potentialCommands) {
const threshold = 3;
potentialCommands = potentialCommands.sort((a5, b6) => b6.length - a5.length);
let recommended = null;
let bestDistance = Infinity;
for (let i5 = 0, candidate; (candidate = potentialCommands[i5]) !== void 0; i5++) {
const d6 = levenshtein(cmd, candidate);
if (d6 <= threshold && d6 < bestDistance) {
bestDistance = d6;
recommended = candidate;
}
}
if (recommended)
usage2.fail(__("Did you mean %s?", recommended));
}, "recommendCommands");
self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
implied = objFilter(implied, (k6) => !localLookup[k6]);
conflicting = objFilter(conflicting, (k6) => !localLookup[k6]);
return self2;
}, "reset");
const frozens = [];
self2.freeze = /* @__PURE__ */ __name(function freeze() {
frozens.push({
implied,
conflicting
});
}, "freeze");
self2.unfreeze = /* @__PURE__ */ __name(function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, void 0, shim3);
({ implied, conflicting } = frozen);
}, "unfreeze");
return self2;
}
var specialKeys;
var init_validation2 = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/validation.js"() {
init_import_meta_url();
init_argsert();
init_common_types();
init_levenshtein();
init_obj_filter();
specialKeys = ["$0", "--", "_"];
__name(validation, "validation");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/yargs-factory.js
function YargsFactory(_shim) {
return (processArgs = [], cwd2 = _shim.process.cwd(), parentRequire) => {
const yargs = new YargsInstance(processArgs, cwd2, parentRequire, _shim);
Object.defineProperty(yargs, "argv", {
get: /* @__PURE__ */ __name(() => {
return yargs.parse();
}, "get"),
enumerable: true
});
yargs.help();
yargs.version();
return yargs;
};
}
function isYargsInstance(y4) {
return !!y4 && typeof y4.getInternalMethods === "function";
}
var __classPrivateFieldSet2, __classPrivateFieldGet4, _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation, kCopyDoubleDash, kCreateLogger, kDeleteFromParserHintObject, kEmitWarning, kFreeze, kGetDollarZero, kGetParserConfiguration, kGetUsageConfiguration, kGuessLocale, kGuessVersion, kParsePositionalNumbers, kPkgUp, kPopulateParserHintArray, kPopulateParserHintSingleValueDictionary, kPopulateParserHintArrayDictionary, kPopulateParserHintDictionary, kSanitizeKey, kSetKey, kUnfreeze, kValidateAsync, kGetCommandInstance, kGetContext, kGetHasOutput, kGetLoggerInstance, kGetParseContext, kGetUsageInstance, kGetValidationInstance, kHasParseCallback, kIsGlobalContext, kPostProcess, kRebase, kReset, kRunYargsParserAndExecuteCommands, kRunValidation, kSetHasOutput, kTrackManuallySetKeys, YargsInstance;
var init_yargs_factory = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/build/lib/yargs-factory.js"() {
init_import_meta_url();
init_command2();
init_common_types();
init_yerror();
init_usage();
init_argsert();
init_completion();
init_validation2();
init_obj_filter();
init_apply_extends();
init_middleware();
init_is_promise();
init_maybe_async_result();
init_set_blocking();
__classPrivateFieldSet2 = function(receiver, state2, value, kind, f6) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f6) throw new TypeError("Private accessor was defined without a setter");
if (typeof state2 === "function" ? receiver !== state2 || !f6 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f6.call(receiver, value) : f6 ? f6.value = value : state2.set(receiver, value), value;
};
__classPrivateFieldGet4 = function(receiver, state2, kind, f6) {
if (kind === "a" && !f6) throw new TypeError("Private accessor was defined without a getter");
if (typeof state2 === "function" ? receiver !== state2 || !f6 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f6 : kind === "a" ? f6.call(receiver) : f6 ? f6.value : state2.get(receiver);
};
__name(YargsFactory, "YargsFactory");
kCopyDoubleDash = Symbol("copyDoubleDash");
kCreateLogger = Symbol("copyDoubleDash");
kDeleteFromParserHintObject = Symbol("deleteFromParserHintObject");
kEmitWarning = Symbol("emitWarning");
kFreeze = Symbol("freeze");
kGetDollarZero = Symbol("getDollarZero");
kGetParserConfiguration = Symbol("getParserConfiguration");
kGetUsageConfiguration = Symbol("getUsageConfiguration");
kGuessLocale = Symbol("guessLocale");
kGuessVersion = Symbol("guessVersion");
kParsePositionalNumbers = Symbol("parsePositionalNumbers");
kPkgUp = Symbol("pkgUp");
kPopulateParserHintArray = Symbol("populateParserHintArray");
kPopulateParserHintSingleValueDictionary = Symbol("populateParserHintSingleValueDictionary");
kPopulateParserHintArrayDictionary = Symbol("populateParserHintArrayDictionary");
kPopulateParserHintDictionary = Symbol("populateParserHintDictionary");
kSanitizeKey = Symbol("sanitizeKey");
kSetKey = Symbol("setKey");
kUnfreeze = Symbol("unfreeze");
kValidateAsync = Symbol("validateAsync");
kGetCommandInstance = Symbol("getCommandInstance");
kGetContext = Symbol("getContext");
kGetHasOutput = Symbol("getHasOutput");
kGetLoggerInstance = Symbol("getLoggerInstance");
kGetParseContext = Symbol("getParseContext");
kGetUsageInstance = Symbol("getUsageInstance");
kGetValidationInstance = Symbol("getValidationInstance");
kHasParseCallback = Symbol("hasParseCallback");
kIsGlobalContext = Symbol("isGlobalContext");
kPostProcess = Symbol("postProcess");
kRebase = Symbol("rebase");
kReset = Symbol("reset");
kRunYargsParserAndExecuteCommands = Symbol("runYargsParserAndExecuteCommands");
kRunValidation = Symbol("runValidation");
kSetHasOutput = Symbol("setHasOutput");
kTrackManuallySetKeys = Symbol("kTrackManuallySetKeys");
YargsInstance = class {
static {
__name(this, "YargsInstance");
}
constructor(processArgs = [], cwd2, parentRequire, shim3) {
this.customScriptName = false;
this.parsed = false;
_YargsInstance_command.set(this, void 0);
_YargsInstance_cwd.set(this, void 0);
_YargsInstance_context.set(this, { commands: [], fullCommands: [] });
_YargsInstance_completion.set(this, null);
_YargsInstance_completionCommand.set(this, null);
_YargsInstance_defaultShowHiddenOpt.set(this, "show-hidden");
_YargsInstance_exitError.set(this, null);
_YargsInstance_detectLocale.set(this, true);
_YargsInstance_emittedWarnings.set(this, {});
_YargsInstance_exitProcess.set(this, true);
_YargsInstance_frozens.set(this, []);
_YargsInstance_globalMiddleware.set(this, void 0);
_YargsInstance_groups.set(this, {});
_YargsInstance_hasOutput.set(this, false);
_YargsInstance_helpOpt.set(this, null);
_YargsInstance_isGlobalContext.set(this, true);
_YargsInstance_logger.set(this, void 0);
_YargsInstance_output.set(this, "");
_YargsInstance_options.set(this, void 0);
_YargsInstance_parentRequire.set(this, void 0);
_YargsInstance_parserConfig.set(this, {});
_YargsInstance_parseFn.set(this, null);
_YargsInstance_parseContext.set(this, null);
_YargsInstance_pkgs.set(this, {});
_YargsInstance_preservedGroups.set(this, {});
_YargsInstance_processArgs.set(this, void 0);
_YargsInstance_recommendCommands.set(this, false);
_YargsInstance_shim.set(this, void 0);
_YargsInstance_strict.set(this, false);
_YargsInstance_strictCommands.set(this, false);
_YargsInstance_strictOptions.set(this, false);
_YargsInstance_usage.set(this, void 0);
_YargsInstance_usageConfig.set(this, {});
_YargsInstance_versionOpt.set(this, null);
_YargsInstance_validation.set(this, void 0);
__classPrivateFieldSet2(this, _YargsInstance_shim, shim3, "f");
__classPrivateFieldSet2(this, _YargsInstance_processArgs, processArgs, "f");
__classPrivateFieldSet2(this, _YargsInstance_cwd, cwd2, "f");
__classPrivateFieldSet2(this, _YargsInstance_parentRequire, parentRequire, "f");
__classPrivateFieldSet2(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
this.$0 = this[kGetDollarZero]();
this[kReset]();
__classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet4(this, _YargsInstance_command, "f"), "f");
__classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet4(this, _YargsInstance_usage, "f"), "f");
__classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet4(this, _YargsInstance_validation, "f"), "f");
__classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet4(this, _YargsInstance_options, "f"), "f");
__classPrivateFieldGet4(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet4(this, _YargsInstance_defaultShowHiddenOpt, "f");
__classPrivateFieldSet2(this, _YargsInstance_logger, this[kCreateLogger](), "f");
}
addHelpOpt(opt, msg) {
const defaultHelpOpt = "help";
argsert("[string|boolean] [string]", [opt, msg], arguments.length);
if (__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f")) {
this[kDeleteFromParserHintObject](__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f"));
__classPrivateFieldSet2(this, _YargsInstance_helpOpt, null, "f");
}
if (opt === false && msg === void 0)
return this;
__classPrivateFieldSet2(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
this.boolean(__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f"));
this.describe(__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet4(this, _YargsInstance_usage, "f").deferY18nLookup("Show help"));
return this;
}
help(opt, msg) {
return this.addHelpOpt(opt, msg);
}
addShowHiddenOpt(opt, msg) {
argsert("[string|boolean] [string]", [opt, msg], arguments.length);
if (opt === false && msg === void 0)
return this;
const showHiddenOpt = typeof opt === "string" ? opt : __classPrivateFieldGet4(this, _YargsInstance_defaultShowHiddenOpt, "f");
this.boolean(showHiddenOpt);
this.describe(showHiddenOpt, msg || __classPrivateFieldGet4(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
__classPrivateFieldGet4(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
return this;
}
showHidden(opt, msg) {
return this.addShowHiddenOpt(opt, msg);
}
alias(key, value) {
argsert("<object|string|array> [string|array]", [key, value], arguments.length);
this[kPopulateParserHintArrayDictionary](this.alias.bind(this), "alias", key, value);
return this;
}
array(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("array", keys);
this[kTrackManuallySetKeys](keys);
return this;
}
boolean(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("boolean", keys);
this[kTrackManuallySetKeys](keys);
return this;
}
check(f6, global2) {
argsert("<function> [boolean]", [f6, global2], arguments.length);
this.middleware((argv, _yargs) => {
return maybeAsyncResult(() => {
return f6(argv, _yargs.getOptions());
}, (result) => {
if (!result) {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet4(this, _YargsInstance_shim, "f").y18n.__("Argument check failed: %s", f6.toString()));
} else if (typeof result === "string" || result instanceof Error) {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").fail(result.toString(), result);
}
return argv;
}, (err) => {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err);
return argv;
});
}, false, global2);
return this;
}
choices(key, value) {
argsert("<object|string|array> [string|array]", [key, value], arguments.length);
this[kPopulateParserHintArrayDictionary](this.choices.bind(this), "choices", key, value);
return this;
}
coerce(keys, value) {
argsert("<object|string|array> [function]", [keys, value], arguments.length);
if (Array.isArray(keys)) {
if (!value) {
throw new YError("coerce callback must be provided");
}
for (const key of keys) {
this.coerce(key, value);
}
return this;
} else if (typeof keys === "object") {
for (const key of Object.keys(keys)) {
this.coerce(key, keys[key]);
}
return this;
}
if (!value) {
throw new YError("coerce callback must be provided");
}
__classPrivateFieldGet4(this, _YargsInstance_options, "f").key[keys] = true;
__classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => {
let aliases2;
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
if (!shouldCoerce) {
return argv;
}
return maybeAsyncResult(() => {
aliases2 = yargs.getAliases();
return value(argv[keys]);
}, (result) => {
argv[keys] = result;
const stripAliased = yargs.getInternalMethods().getParserConfiguration()["strip-aliased"];
if (aliases2[keys] && stripAliased !== true) {
for (const alias of aliases2[keys]) {
argv[alias] = result;
}
}
return argv;
}, (err) => {
throw new YError(err.message);
});
}, keys);
return this;
}
conflicts(key1, key2) {
argsert("<string|object> [string|array]", [key1, key2], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").conflicts(key1, key2);
return this;
}
config(key = "config", msg, parseFn) {
argsert("[object|string] [string|function] [function]", [key, msg, parseFn], arguments.length);
if (typeof key === "object" && !Array.isArray(key)) {
key = applyExtends(key, __classPrivateFieldGet4(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
__classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects || []).concat(key);
return this;
}
if (typeof msg === "function") {
parseFn = msg;
msg = void 0;
}
this.describe(key, msg || __classPrivateFieldGet4(this, _YargsInstance_usage, "f").deferY18nLookup("Path to JSON config file"));
(Array.isArray(key) ? key : [key]).forEach((k6) => {
__classPrivateFieldGet4(this, _YargsInstance_options, "f").config[k6] = parseFn || true;
});
return this;
}
completion(cmd, desc, fn2) {
argsert("[string] [string|boolean|function] [function]", [cmd, desc, fn2], arguments.length);
if (typeof desc === "function") {
fn2 = desc;
desc = void 0;
}
__classPrivateFieldSet2(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f") || "completion", "f");
if (!desc && desc !== false) {
desc = "generate completion script";
}
this.command(__classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f"), desc);
if (fn2)
__classPrivateFieldGet4(this, _YargsInstance_completion, "f").registerFunction(fn2);
return this;
}
command(cmd, description, builder, handler, middlewares, deprecated2) {
argsert("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]", [cmd, description, builder, handler, middlewares, deprecated2], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated2);
return this;
}
commands(cmd, description, builder, handler, middlewares, deprecated2) {
return this.command(cmd, description, builder, handler, middlewares, deprecated2);
}
commandDir(dir, opts) {
argsert("<string> [object]", [dir, opts], arguments.length);
const req = __classPrivateFieldGet4(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet4(this, _YargsInstance_shim, "f").require;
__classPrivateFieldGet4(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getCallerFile(), opts);
return this;
}
count(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("count", keys);
this[kTrackManuallySetKeys](keys);
return this;
}
default(key, value, defaultDescription) {
argsert("<object|string|array> [*] [string]", [key, value, defaultDescription], arguments.length);
if (defaultDescription) {
assertSingleKey(key, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
__classPrivateFieldGet4(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
}
if (typeof value === "function") {
assertSingleKey(key, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
if (!__classPrivateFieldGet4(this, _YargsInstance_options, "f").defaultDescription[key])
__classPrivateFieldGet4(this, _YargsInstance_options, "f").defaultDescription[key] = __classPrivateFieldGet4(this, _YargsInstance_usage, "f").functionDescription(value);
value = value.call();
}
this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), "default", key, value);
return this;
}
defaults(key, value, defaultDescription) {
return this.default(key, value, defaultDescription);
}
demandCommand(min = 1, max, minMsg, maxMsg) {
argsert("[number] [number|string] [string|null|undefined] [string|null|undefined]", [min, max, minMsg, maxMsg], arguments.length);
if (typeof max !== "number") {
minMsg = max;
max = Infinity;
}
this.global("_", false);
__classPrivateFieldGet4(this, _YargsInstance_options, "f").demandedCommands._ = {
min,
max,
minMsg,
maxMsg
};
return this;
}
demand(keys, max, msg) {
if (Array.isArray(max)) {
max.forEach((key) => {
assertNotStrictEqual(msg, true, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
this.demandOption(key, msg);
});
max = Infinity;
} else if (typeof max !== "number") {
msg = max;
max = Infinity;
}
if (typeof keys === "number") {
assertNotStrictEqual(msg, true, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
this.demandCommand(keys, max, msg, msg);
} else if (Array.isArray(keys)) {
keys.forEach((key) => {
assertNotStrictEqual(msg, true, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
this.demandOption(key, msg);
});
} else {
if (typeof msg === "string") {
this.demandOption(keys, msg);
} else if (msg === true || typeof msg === "undefined") {
this.demandOption(keys);
}
}
return this;
}
demandOption(keys, msg) {
argsert("<object|string|array> [string]", [keys, msg], arguments.length);
this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), "demandedOptions", keys, msg);
return this;
}
deprecateOption(option, message) {
argsert("<string> [string|boolean]", [option, message], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_options, "f").deprecatedOptions[option] = message;
return this;
}
describe(keys, description) {
argsert("<object|string|array> [string]", [keys, description], arguments.length);
this[kSetKey](keys, true);
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").describe(keys, description);
return this;
}
detectLocale(detect) {
argsert("<boolean>", [detect], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_detectLocale, detect, "f");
return this;
}
env(prefix) {
argsert("[string|boolean]", [prefix], arguments.length);
if (prefix === false)
delete __classPrivateFieldGet4(this, _YargsInstance_options, "f").envPrefix;
else
__classPrivateFieldGet4(this, _YargsInstance_options, "f").envPrefix = prefix || "";
return this;
}
epilogue(msg) {
argsert("<string>", [msg], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").epilog(msg);
return this;
}
epilog(msg) {
return this.epilogue(msg);
}
example(cmd, description) {
argsert("<string|array> [string]", [cmd, description], arguments.length);
if (Array.isArray(cmd)) {
cmd.forEach((exampleParams) => this.example(...exampleParams));
} else {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").example(cmd, description);
}
return this;
}
exit(code, err) {
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
__classPrivateFieldSet2(this, _YargsInstance_exitError, err, "f");
if (__classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f"))
__classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.exit(code);
}
exitProcess(enabled = true) {
argsert("[boolean]", [enabled], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_exitProcess, enabled, "f");
return this;
}
fail(f6) {
argsert("<function|boolean>", [f6], arguments.length);
if (typeof f6 === "boolean" && f6 !== false) {
throw new YError("Invalid first argument. Expected function or boolean 'false'");
}
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").failFn(f6);
return this;
}
getAliases() {
return this.parsed ? this.parsed.aliases : {};
}
async getCompletion(args, done) {
argsert("<array> [function]", [args, done], arguments.length);
if (!done) {
return new Promise((resolve25, reject) => {
__classPrivateFieldGet4(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => {
if (err)
reject(err);
else
resolve25(completions);
});
});
} else {
return __classPrivateFieldGet4(this, _YargsInstance_completion, "f").getCompletion(args, done);
}
}
getDemandedOptions() {
argsert([], 0);
return __classPrivateFieldGet4(this, _YargsInstance_options, "f").demandedOptions;
}
getDemandedCommands() {
argsert([], 0);
return __classPrivateFieldGet4(this, _YargsInstance_options, "f").demandedCommands;
}
getDeprecatedOptions() {
argsert([], 0);
return __classPrivateFieldGet4(this, _YargsInstance_options, "f").deprecatedOptions;
}
getDetectLocale() {
return __classPrivateFieldGet4(this, _YargsInstance_detectLocale, "f");
}
getExitProcess() {
return __classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f");
}
getGroups() {
return Object.assign({}, __classPrivateFieldGet4(this, _YargsInstance_groups, "f"), __classPrivateFieldGet4(this, _YargsInstance_preservedGroups, "f"));
}
getHelp() {
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
if (!__classPrivateFieldGet4(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
if (!this.parsed) {
const parse7 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet4(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
if (isPromise(parse7)) {
return parse7.then(() => {
return __classPrivateFieldGet4(this, _YargsInstance_usage, "f").help();
});
}
}
const builderResponse = __classPrivateFieldGet4(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
return builderResponse.then(() => {
return __classPrivateFieldGet4(this, _YargsInstance_usage, "f").help();
});
}
}
return Promise.resolve(__classPrivateFieldGet4(this, _YargsInstance_usage, "f").help());
}
getOptions() {
return __classPrivateFieldGet4(this, _YargsInstance_options, "f");
}
getStrict() {
return __classPrivateFieldGet4(this, _YargsInstance_strict, "f");
}
getStrictCommands() {
return __classPrivateFieldGet4(this, _YargsInstance_strictCommands, "f");
}
getStrictOptions() {
return __classPrivateFieldGet4(this, _YargsInstance_strictOptions, "f");
}
global(globals, global2) {
argsert("<string|array> [boolean]", [globals, global2], arguments.length);
globals = [].concat(globals);
if (global2 !== false) {
__classPrivateFieldGet4(this, _YargsInstance_options, "f").local = __classPrivateFieldGet4(this, _YargsInstance_options, "f").local.filter((l6) => globals.indexOf(l6) === -1);
} else {
globals.forEach((g6) => {
if (!__classPrivateFieldGet4(this, _YargsInstance_options, "f").local.includes(g6))
__classPrivateFieldGet4(this, _YargsInstance_options, "f").local.push(g6);
});
}
return this;
}
group(opts, groupName) {
argsert("<string|array> <string>", [opts, groupName], arguments.length);
const existing = __classPrivateFieldGet4(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet4(this, _YargsInstance_groups, "f")[groupName];
if (__classPrivateFieldGet4(this, _YargsInstance_preservedGroups, "f")[groupName]) {
delete __classPrivateFieldGet4(this, _YargsInstance_preservedGroups, "f")[groupName];
}
const seen = {};
__classPrivateFieldGet4(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter((key) => {
if (seen[key])
return false;
return seen[key] = true;
});
return this;
}
hide(key) {
argsert("<string>", [key], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_options, "f").hiddenOptions.push(key);
return this;
}
implies(key, value) {
argsert("<string|object> [number|string|array]", [key, value], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").implies(key, value);
return this;
}
locale(locale) {
argsert("[string]", [locale], arguments.length);
if (locale === void 0) {
this[kGuessLocale]();
return __classPrivateFieldGet4(this, _YargsInstance_shim, "f").y18n.getLocale();
}
__classPrivateFieldSet2(this, _YargsInstance_detectLocale, false, "f");
__classPrivateFieldGet4(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
return this;
}
middleware(callback, applyBeforeValidation, global2) {
return __classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global2);
}
nargs(key, value) {
argsert("<string|object|array> [number]", [key, value], arguments.length);
this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), "narg", key, value);
return this;
}
normalize(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("normalize", keys);
return this;
}
number(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("number", keys);
this[kTrackManuallySetKeys](keys);
return this;
}
option(key, opt) {
argsert("<string|object> [object]", [key, opt], arguments.length);
if (typeof key === "object") {
Object.keys(key).forEach((k6) => {
this.options(k6, key[k6]);
});
} else {
if (typeof opt !== "object") {
opt = {};
}
this[kTrackManuallySetKeys](key);
if (__classPrivateFieldGet4(this, _YargsInstance_versionOpt, "f") && (key === "version" || (opt === null || opt === void 0 ? void 0 : opt.alias) === "version")) {
this[kEmitWarning]([
'"version" is a reserved word.',
"Please do one of the following:",
'- Disable version with `yargs.version(false)` if using "version" as an option',
"- Use the built-in `yargs.version` method instead (if applicable)",
"- Use a different option key",
"https://yargs.js.org/docs/#api-reference-version"
].join("\n"), void 0, "versionWarning");
}
__classPrivateFieldGet4(this, _YargsInstance_options, "f").key[key] = true;
if (opt.alias)
this.alias(key, opt.alias);
const deprecate = opt.deprecate || opt.deprecated;
if (deprecate) {
this.deprecateOption(key, deprecate);
}
const demand = opt.demand || opt.required || opt.require;
if (demand) {
this.demand(key, demand);
}
if (opt.demandOption) {
this.demandOption(key, typeof opt.demandOption === "string" ? opt.demandOption : void 0);
}
if (opt.conflicts) {
this.conflicts(key, opt.conflicts);
}
if ("default" in opt) {
this.default(key, opt.default);
}
if (opt.implies !== void 0) {
this.implies(key, opt.implies);
}
if (opt.nargs !== void 0) {
this.nargs(key, opt.nargs);
}
if (opt.config) {
this.config(key, opt.configParser);
}
if (opt.normalize) {
this.normalize(key);
}
if (opt.choices) {
this.choices(key, opt.choices);
}
if (opt.coerce) {
this.coerce(key, opt.coerce);
}
if (opt.group) {
this.group(key, opt.group);
}
if (opt.boolean || opt.type === "boolean") {
this.boolean(key);
if (opt.alias)
this.boolean(opt.alias);
}
if (opt.array || opt.type === "array") {
this.array(key);
if (opt.alias)
this.array(opt.alias);
}
if (opt.number || opt.type === "number") {
this.number(key);
if (opt.alias)
this.number(opt.alias);
}
if (opt.string || opt.type === "string") {
this.string(key);
if (opt.alias)
this.string(opt.alias);
}
if (opt.count || opt.type === "count") {
this.count(key);
}
if (typeof opt.global === "boolean") {
this.global(key, opt.global);
}
if (opt.defaultDescription) {
__classPrivateFieldGet4(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
}
if (opt.skipValidation) {
this.skipValidation(key);
}
const desc = opt.describe || opt.description || opt.desc;
const descriptions = __classPrivateFieldGet4(this, _YargsInstance_usage, "f").getDescriptions();
if (!Object.prototype.hasOwnProperty.call(descriptions, key) || typeof desc === "string") {
this.describe(key, desc);
}
if (opt.hidden) {
this.hide(key);
}
if (opt.requiresArg) {
this.requiresArg(key);
}
}
return this;
}
options(key, opt) {
return this.option(key, opt);
}
parse(args, shortCircuit, _parseFn) {
argsert("[string|array] [function|boolean|object] [function]", [args, shortCircuit, _parseFn], arguments.length);
this[kFreeze]();
if (typeof args === "undefined") {
args = __classPrivateFieldGet4(this, _YargsInstance_processArgs, "f");
}
if (typeof shortCircuit === "object") {
__classPrivateFieldSet2(this, _YargsInstance_parseContext, shortCircuit, "f");
shortCircuit = _parseFn;
}
if (typeof shortCircuit === "function") {
__classPrivateFieldSet2(this, _YargsInstance_parseFn, shortCircuit, "f");
shortCircuit = false;
}
if (!shortCircuit)
__classPrivateFieldSet2(this, _YargsInstance_processArgs, args, "f");
if (__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f"))
__classPrivateFieldSet2(this, _YargsInstance_exitProcess, false, "f");
const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit);
const tmpParsed = this.parsed;
__classPrivateFieldGet4(this, _YargsInstance_completion, "f").setParsed(this.parsed);
if (isPromise(parsed)) {
return parsed.then((argv) => {
if (__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f"))
__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet4(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet4(this, _YargsInstance_output, "f"));
return argv;
}).catch((err) => {
if (__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f")) {
__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet4(this, _YargsInstance_output, "f"));
}
throw err;
}).finally(() => {
this[kUnfreeze]();
this.parsed = tmpParsed;
});
} else {
if (__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f"))
__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet4(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet4(this, _YargsInstance_output, "f"));
this[kUnfreeze]();
this.parsed = tmpParsed;
}
return parsed;
}
parseAsync(args, shortCircuit, _parseFn) {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise;
}
parseSync(args, shortCircuit, _parseFn) {
const maybePromise = this.parse(args, shortCircuit, _parseFn);
if (isPromise(maybePromise)) {
throw new YError(".parseSync() must not be used with asynchronous builders, handlers, or middleware");
}
return maybePromise;
}
parserConfiguration(config) {
argsert("<object>", [config], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_parserConfig, config, "f");
return this;
}
pkgConf(key, rootPath) {
argsert("<string> [string]", [key, rootPath], arguments.length);
let conf = null;
const obj = this[kPkgUp](rootPath || __classPrivateFieldGet4(this, _YargsInstance_cwd, "f"));
if (obj[key] && typeof obj[key] === "object") {
conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet4(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
__classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects || []).concat(conf);
}
return this;
}
positional(key, opts) {
argsert("<string> <object>", [key, opts], arguments.length);
const supportedOpts = [
"default",
"defaultDescription",
"implies",
"normalize",
"choices",
"conflicts",
"coerce",
"type",
"describe",
"desc",
"description",
"alias"
];
opts = objFilter(opts, (k6, v7) => {
if (k6 === "type" && !["string", "number", "boolean"].includes(v7))
return false;
return supportedOpts.includes(k6);
});
const fullCommand = __classPrivateFieldGet4(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet4(this, _YargsInstance_context, "f").fullCommands.length - 1];
const parseOptions = fullCommand ? __classPrivateFieldGet4(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) : {
array: [],
alias: {},
default: {},
demand: {}
};
objectKeys(parseOptions).forEach((pk) => {
const parseOption = parseOptions[pk];
if (Array.isArray(parseOption)) {
if (parseOption.indexOf(key) !== -1)
opts[pk] = true;
} else {
if (parseOption[key] && !(pk in opts))
opts[pk] = parseOption[key];
}
});
this.group(key, __classPrivateFieldGet4(this, _YargsInstance_usage, "f").getPositionalGroupName());
return this.option(key, opts);
}
recommendCommands(recommend = true) {
argsert("[boolean]", [recommend], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_recommendCommands, recommend, "f");
return this;
}
required(keys, max, msg) {
return this.demand(keys, max, msg);
}
require(keys, max, msg) {
return this.demand(keys, max, msg);
}
requiresArg(keys) {
argsert("<array|string|object> [number]", [keys], arguments.length);
if (typeof keys === "string" && __classPrivateFieldGet4(this, _YargsInstance_options, "f").narg[keys]) {
return this;
} else {
this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), "narg", keys, NaN);
}
return this;
}
showCompletionScript($0, cmd) {
argsert("[string] [string]", [$0, cmd], arguments.length);
$0 = $0 || this.$0;
__classPrivateFieldGet4(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet4(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f") || "completion"));
return this;
}
showHelp(level) {
argsert("[string|function]", [level], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
if (!__classPrivateFieldGet4(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
if (!this.parsed) {
const parse7 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet4(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
if (isPromise(parse7)) {
parse7.then(() => {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").showHelp(level);
});
return this;
}
}
const builderResponse = __classPrivateFieldGet4(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
if (isPromise(builderResponse)) {
builderResponse.then(() => {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").showHelp(level);
});
return this;
}
}
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").showHelp(level);
return this;
}
scriptName(scriptName) {
this.customScriptName = true;
this.$0 = scriptName;
return this;
}
showHelpOnFail(enabled, message) {
argsert("[boolean|string] [string]", [enabled, message], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
return this;
}
showVersion(level) {
argsert("[string|function]", [level], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").showVersion(level);
return this;
}
skipValidation(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("skipValidation", keys);
return this;
}
strict(enabled) {
argsert("[boolean]", [enabled], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_strict, enabled !== false, "f");
return this;
}
strictCommands(enabled) {
argsert("[boolean]", [enabled], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_strictCommands, enabled !== false, "f");
return this;
}
strictOptions(enabled) {
argsert("[boolean]", [enabled], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_strictOptions, enabled !== false, "f");
return this;
}
string(keys) {
argsert("<array|string>", [keys], arguments.length);
this[kPopulateParserHintArray]("string", keys);
this[kTrackManuallySetKeys](keys);
return this;
}
terminalWidth() {
argsert([], 0);
return __classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.stdColumns;
}
updateLocale(obj) {
return this.updateStrings(obj);
}
updateStrings(obj) {
argsert("<object>", [obj], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_detectLocale, false, "f");
__classPrivateFieldGet4(this, _YargsInstance_shim, "f").y18n.updateLocale(obj);
return this;
}
usage(msg, description, builder, handler) {
argsert("<string|null|undefined> [string|boolean] [function|object] [function]", [msg, description, builder, handler], arguments.length);
if (description !== void 0) {
assertNotStrictEqual(msg, null, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
if ((msg || "").match(/^\$0( |$)/)) {
return this.command(msg, description, builder, handler);
} else {
throw new YError(".usage() description must start with $0 if being used as alias for .command()");
}
} else {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").usage(msg);
return this;
}
}
usageConfiguration(config) {
argsert("<object>", [config], arguments.length);
__classPrivateFieldSet2(this, _YargsInstance_usageConfig, config, "f");
return this;
}
version(opt, msg, ver) {
const defaultVersionOpt = "version";
argsert("[boolean|string] [string] [string]", [opt, msg, ver], arguments.length);
if (__classPrivateFieldGet4(this, _YargsInstance_versionOpt, "f")) {
this[kDeleteFromParserHintObject](__classPrivateFieldGet4(this, _YargsInstance_versionOpt, "f"));
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").version(void 0);
__classPrivateFieldSet2(this, _YargsInstance_versionOpt, null, "f");
}
if (arguments.length === 0) {
ver = this[kGuessVersion]();
opt = defaultVersionOpt;
} else if (arguments.length === 1) {
if (opt === false) {
return this;
}
ver = opt;
opt = defaultVersionOpt;
} else if (arguments.length === 2) {
ver = msg;
msg = void 0;
}
__classPrivateFieldSet2(this, _YargsInstance_versionOpt, typeof opt === "string" ? opt : defaultVersionOpt, "f");
msg = msg || __classPrivateFieldGet4(this, _YargsInstance_usage, "f").deferY18nLookup("Show version number");
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").version(ver || void 0);
this.boolean(__classPrivateFieldGet4(this, _YargsInstance_versionOpt, "f"));
this.describe(__classPrivateFieldGet4(this, _YargsInstance_versionOpt, "f"), msg);
return this;
}
wrap(cols) {
argsert("<number|null|undefined>", [cols], arguments.length);
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").wrap(cols);
return this;
}
[(_YargsInstance_command = /* @__PURE__ */ new WeakMap(), _YargsInstance_cwd = /* @__PURE__ */ new WeakMap(), _YargsInstance_context = /* @__PURE__ */ new WeakMap(), _YargsInstance_completion = /* @__PURE__ */ new WeakMap(), _YargsInstance_completionCommand = /* @__PURE__ */ new WeakMap(), _YargsInstance_defaultShowHiddenOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitError = /* @__PURE__ */ new WeakMap(), _YargsInstance_detectLocale = /* @__PURE__ */ new WeakMap(), _YargsInstance_emittedWarnings = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitProcess = /* @__PURE__ */ new WeakMap(), _YargsInstance_frozens = /* @__PURE__ */ new WeakMap(), _YargsInstance_globalMiddleware = /* @__PURE__ */ new WeakMap(), _YargsInstance_groups = /* @__PURE__ */ new WeakMap(), _YargsInstance_hasOutput = /* @__PURE__ */ new WeakMap(), _YargsInstance_helpOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_isGlobalContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_logger = /* @__PURE__ */ new WeakMap(), _YargsInstance_output = /* @__PURE__ */ new WeakMap(), _YargsInstance_options = /* @__PURE__ */ new WeakMap(), _YargsInstance_parentRequire = /* @__PURE__ */ new WeakMap(), _YargsInstance_parserConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseFn = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_pkgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_preservedGroups = /* @__PURE__ */ new WeakMap(), _YargsInstance_processArgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_recommendCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_shim = /* @__PURE__ */ new WeakMap(), _YargsInstance_strict = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictOptions = /* @__PURE__ */ new WeakMap(), _YargsInstance_usage = /* @__PURE__ */ new WeakMap(), _YargsInstance_usageConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_versionOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_validation = /* @__PURE__ */ new WeakMap(), kCopyDoubleDash)](argv) {
if (!argv._ || !argv["--"])
return argv;
argv._.push.apply(argv._, argv["--"]);
try {
delete argv["--"];
} catch (_err) {
}
return argv;
}
[kCreateLogger]() {
return {
log: /* @__PURE__ */ __name((...args) => {
if (!this[kHasParseCallback]())
console.log(...args);
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
if (__classPrivateFieldGet4(this, _YargsInstance_output, "f").length)
__classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet4(this, _YargsInstance_output, "f") + "\n", "f");
__classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet4(this, _YargsInstance_output, "f") + args.join(" "), "f");
}, "log"),
error: /* @__PURE__ */ __name((...args) => {
if (!this[kHasParseCallback]())
console.error(...args);
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
if (__classPrivateFieldGet4(this, _YargsInstance_output, "f").length)
__classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet4(this, _YargsInstance_output, "f") + "\n", "f");
__classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet4(this, _YargsInstance_output, "f") + args.join(" "), "f");
}, "error")
};
}
[kDeleteFromParserHintObject](optionKey) {
objectKeys(__classPrivateFieldGet4(this, _YargsInstance_options, "f")).forEach((hintKey) => {
if (/* @__PURE__ */ ((key) => key === "configObjects")(hintKey))
return;
const hint = __classPrivateFieldGet4(this, _YargsInstance_options, "f")[hintKey];
if (Array.isArray(hint)) {
if (hint.includes(optionKey))
hint.splice(hint.indexOf(optionKey), 1);
} else if (typeof hint === "object") {
delete hint[optionKey];
}
});
delete __classPrivateFieldGet4(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
}
[kEmitWarning](warning, type, deduplicationId) {
if (!__classPrivateFieldGet4(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
__classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
__classPrivateFieldGet4(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
}
}
[kFreeze]() {
__classPrivateFieldGet4(this, _YargsInstance_frozens, "f").push({
options: __classPrivateFieldGet4(this, _YargsInstance_options, "f"),
configObjects: __classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects.slice(0),
exitProcess: __classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f"),
groups: __classPrivateFieldGet4(this, _YargsInstance_groups, "f"),
strict: __classPrivateFieldGet4(this, _YargsInstance_strict, "f"),
strictCommands: __classPrivateFieldGet4(this, _YargsInstance_strictCommands, "f"),
strictOptions: __classPrivateFieldGet4(this, _YargsInstance_strictOptions, "f"),
completionCommand: __classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f"),
output: __classPrivateFieldGet4(this, _YargsInstance_output, "f"),
exitError: __classPrivateFieldGet4(this, _YargsInstance_exitError, "f"),
hasOutput: __classPrivateFieldGet4(this, _YargsInstance_hasOutput, "f"),
parsed: this.parsed,
parseFn: __classPrivateFieldGet4(this, _YargsInstance_parseFn, "f"),
parseContext: __classPrivateFieldGet4(this, _YargsInstance_parseContext, "f")
});
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").freeze();
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").freeze();
__classPrivateFieldGet4(this, _YargsInstance_command, "f").freeze();
__classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").freeze();
}
[kGetDollarZero]() {
let $0 = "";
let default$0;
if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.argv()[0])) {
default$0 = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
} else {
default$0 = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
}
$0 = default$0.map((x6) => {
const b6 = this[kRebase](__classPrivateFieldGet4(this, _YargsInstance_cwd, "f"), x6);
return x6.match(/^(\/|([a-zA-Z]:)?\\)/) && b6.length < x6.length ? b6 : x6;
}).join(" ").trim();
if (__classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("_") && __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("_")) {
$0 = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("_").replace(`${__classPrivateFieldGet4(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet4(this, _YargsInstance_shim, "f").process.execPath())}/`, "");
}
return $0;
}
[kGetParserConfiguration]() {
return __classPrivateFieldGet4(this, _YargsInstance_parserConfig, "f");
}
[kGetUsageConfiguration]() {
return __classPrivateFieldGet4(this, _YargsInstance_usageConfig, "f");
}
[kGuessLocale]() {
if (!__classPrivateFieldGet4(this, _YargsInstance_detectLocale, "f"))
return;
const locale = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("LC_ALL") || __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("LC_MESSAGES") || __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("LANG") || __classPrivateFieldGet4(this, _YargsInstance_shim, "f").getEnv("LANGUAGE") || "en_US";
this.locale(locale.replace(/[.:].*/, ""));
}
[kGuessVersion]() {
const obj = this[kPkgUp]();
return obj.version || "unknown";
}
[kParsePositionalNumbers](argv) {
const args = argv["--"] ? argv["--"] : argv._;
for (let i5 = 0, arg; (arg = args[i5]) !== void 0; i5++) {
if (__classPrivateFieldGet4(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
args[i5] = Number(arg);
}
}
return argv;
}
[kPkgUp](rootPath) {
const npath = rootPath || "*";
if (__classPrivateFieldGet4(this, _YargsInstance_pkgs, "f")[npath])
return __classPrivateFieldGet4(this, _YargsInstance_pkgs, "f")[npath];
let obj = {};
try {
let startDir = rootPath || __classPrivateFieldGet4(this, _YargsInstance_shim, "f").mainFilename;
if (!rootPath && __classPrivateFieldGet4(this, _YargsInstance_shim, "f").path.extname(startDir)) {
startDir = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").path.dirname(startDir);
}
const pkgJsonPath = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
if (names.includes("package.json")) {
return "package.json";
} else {
return void 0;
}
});
assertNotStrictEqual(pkgJsonPath, void 0, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
obj = JSON.parse(__classPrivateFieldGet4(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, "utf8"));
} catch (_noop) {
}
__classPrivateFieldGet4(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
return __classPrivateFieldGet4(this, _YargsInstance_pkgs, "f")[npath];
}
[kPopulateParserHintArray](type, keys) {
keys = [].concat(keys);
keys.forEach((key) => {
key = this[kSanitizeKey](key);
__classPrivateFieldGet4(this, _YargsInstance_options, "f")[type].push(key);
});
}
[kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
__classPrivateFieldGet4(this, _YargsInstance_options, "f")[type2][key2] = value2;
});
}
[kPopulateParserHintArrayDictionary](builder, type, key, value) {
this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
__classPrivateFieldGet4(this, _YargsInstance_options, "f")[type2][key2] = (__classPrivateFieldGet4(this, _YargsInstance_options, "f")[type2][key2] || []).concat(value2);
});
}
[kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
if (Array.isArray(key)) {
key.forEach((k6) => {
builder(k6, value);
});
} else if (/* @__PURE__ */ ((key2) => typeof key2 === "object")(key)) {
for (const k6 of objectKeys(key)) {
builder(k6, key[k6]);
}
} else {
singleKeyHandler(type, this[kSanitizeKey](key), value);
}
}
[kSanitizeKey](key) {
if (key === "__proto__")
return "___proto___";
return key;
}
[kSetKey](key, set) {
this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), "key", key, set);
return this;
}
[kUnfreeze]() {
var _a4, _b2, _c3, _d2, _e2, _f, _g, _h, _j, _k, _l2, _m3;
const frozen = __classPrivateFieldGet4(this, _YargsInstance_frozens, "f").pop();
assertNotStrictEqual(frozen, void 0, __classPrivateFieldGet4(this, _YargsInstance_shim, "f"));
let configObjects;
_a4 = this, _b2 = this, _c3 = this, _d2 = this, _e2 = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l2 = this, _m3 = this, {
options: { set value(_o) {
__classPrivateFieldSet2(_a4, _YargsInstance_options, _o, "f");
} }.value,
configObjects,
exitProcess: { set value(_o) {
__classPrivateFieldSet2(_b2, _YargsInstance_exitProcess, _o, "f");
} }.value,
groups: { set value(_o) {
__classPrivateFieldSet2(_c3, _YargsInstance_groups, _o, "f");
} }.value,
output: { set value(_o) {
__classPrivateFieldSet2(_d2, _YargsInstance_output, _o, "f");
} }.value,
exitError: { set value(_o) {
__classPrivateFieldSet2(_e2, _YargsInstance_exitError, _o, "f");
} }.value,
hasOutput: { set value(_o) {
__classPrivateFieldSet2(_f, _YargsInstance_hasOutput, _o, "f");
} }.value,
parsed: this.parsed,
strict: { set value(_o) {
__classPrivateFieldSet2(_g, _YargsInstance_strict, _o, "f");
} }.value,
strictCommands: { set value(_o) {
__classPrivateFieldSet2(_h, _YargsInstance_strictCommands, _o, "f");
} }.value,
strictOptions: { set value(_o) {
__classPrivateFieldSet2(_j, _YargsInstance_strictOptions, _o, "f");
} }.value,
completionCommand: { set value(_o) {
__classPrivateFieldSet2(_k, _YargsInstance_completionCommand, _o, "f");
} }.value,
parseFn: { set value(_o) {
__classPrivateFieldSet2(_l2, _YargsInstance_parseFn, _o, "f");
} }.value,
parseContext: { set value(_o) {
__classPrivateFieldSet2(_m3, _YargsInstance_parseContext, _o, "f");
} }.value
} = frozen;
__classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects = configObjects;
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").unfreeze();
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").unfreeze();
__classPrivateFieldGet4(this, _YargsInstance_command, "f").unfreeze();
__classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").unfreeze();
}
[kValidateAsync](validation2, argv) {
return maybeAsyncResult(argv, (result) => {
validation2(result);
return result;
});
}
getInternalMethods() {
return {
getCommandInstance: this[kGetCommandInstance].bind(this),
getContext: this[kGetContext].bind(this),
getHasOutput: this[kGetHasOutput].bind(this),
getLoggerInstance: this[kGetLoggerInstance].bind(this),
getParseContext: this[kGetParseContext].bind(this),
getParserConfiguration: this[kGetParserConfiguration].bind(this),
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
getUsageInstance: this[kGetUsageInstance].bind(this),
getValidationInstance: this[kGetValidationInstance].bind(this),
hasParseCallback: this[kHasParseCallback].bind(this),
isGlobalContext: this[kIsGlobalContext].bind(this),
postProcess: this[kPostProcess].bind(this),
reset: this[kReset].bind(this),
runValidation: this[kRunValidation].bind(this),
runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this),
setHasOutput: this[kSetHasOutput].bind(this)
};
}
[kGetCommandInstance]() {
return __classPrivateFieldGet4(this, _YargsInstance_command, "f");
}
[kGetContext]() {
return __classPrivateFieldGet4(this, _YargsInstance_context, "f");
}
[kGetHasOutput]() {
return __classPrivateFieldGet4(this, _YargsInstance_hasOutput, "f");
}
[kGetLoggerInstance]() {
return __classPrivateFieldGet4(this, _YargsInstance_logger, "f");
}
[kGetParseContext]() {
return __classPrivateFieldGet4(this, _YargsInstance_parseContext, "f") || {};
}
[kGetUsageInstance]() {
return __classPrivateFieldGet4(this, _YargsInstance_usage, "f");
}
[kGetValidationInstance]() {
return __classPrivateFieldGet4(this, _YargsInstance_validation, "f");
}
[kHasParseCallback]() {
return !!__classPrivateFieldGet4(this, _YargsInstance_parseFn, "f");
}
[kIsGlobalContext]() {
return __classPrivateFieldGet4(this, _YargsInstance_isGlobalContext, "f");
}
[kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
if (calledFromCommand)
return argv;
if (isPromise(argv))
return argv;
if (!populateDoubleDash) {
argv = this[kCopyDoubleDash](argv);
}
const parsePositionalNumbers = this[kGetParserConfiguration]()["parse-positional-numbers"] || this[kGetParserConfiguration]()["parse-positional-numbers"] === void 0;
if (parsePositionalNumbers) {
argv = this[kParsePositionalNumbers](argv);
}
if (runGlobalMiddleware) {
argv = applyMiddleware(argv, this, __classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
}
return argv;
}
[kReset](aliases2 = {}) {
__classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet4(this, _YargsInstance_options, "f") || {}, "f");
const tmpOptions = {};
tmpOptions.local = __classPrivateFieldGet4(this, _YargsInstance_options, "f").local || [];
tmpOptions.configObjects = __classPrivateFieldGet4(this, _YargsInstance_options, "f").configObjects || [];
const localLookup = {};
tmpOptions.local.forEach((l6) => {
localLookup[l6] = true;
(aliases2[l6] || []).forEach((a5) => {
localLookup[a5] = true;
});
});
Object.assign(__classPrivateFieldGet4(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet4(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
const keys = __classPrivateFieldGet4(this, _YargsInstance_groups, "f")[groupName].filter((key) => !(key in localLookup));
if (keys.length > 0) {
acc[groupName] = keys;
}
return acc;
}, {}));
__classPrivateFieldSet2(this, _YargsInstance_groups, {}, "f");
const arrayOptions = [
"array",
"boolean",
"string",
"skipValidation",
"count",
"normalize",
"number",
"hiddenOptions"
];
const objectOptions = [
"narg",
"key",
"alias",
"default",
"defaultDescription",
"config",
"choices",
"demandedOptions",
"demandedCommands",
"deprecatedOptions"
];
arrayOptions.forEach((k6) => {
tmpOptions[k6] = (__classPrivateFieldGet4(this, _YargsInstance_options, "f")[k6] || []).filter((k7) => !localLookup[k7]);
});
objectOptions.forEach((k6) => {
tmpOptions[k6] = objFilter(__classPrivateFieldGet4(this, _YargsInstance_options, "f")[k6], (k7) => !localLookup[k7]);
});
tmpOptions.envPrefix = __classPrivateFieldGet4(this, _YargsInstance_options, "f").envPrefix;
__classPrivateFieldSet2(this, _YargsInstance_options, tmpOptions, "f");
__classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet4(this, _YargsInstance_usage, "f") ? __classPrivateFieldGet4(this, _YargsInstance_usage, "f").reset(localLookup) : usage(this, __classPrivateFieldGet4(this, _YargsInstance_shim, "f")), "f");
__classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet4(this, _YargsInstance_validation, "f") ? __classPrivateFieldGet4(this, _YargsInstance_validation, "f").reset(localLookup) : validation(this, __classPrivateFieldGet4(this, _YargsInstance_usage, "f"), __classPrivateFieldGet4(this, _YargsInstance_shim, "f")), "f");
__classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet4(this, _YargsInstance_command, "f") ? __classPrivateFieldGet4(this, _YargsInstance_command, "f").reset() : command(__classPrivateFieldGet4(this, _YargsInstance_usage, "f"), __classPrivateFieldGet4(this, _YargsInstance_validation, "f"), __classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet4(this, _YargsInstance_shim, "f")), "f");
if (!__classPrivateFieldGet4(this, _YargsInstance_completion, "f"))
__classPrivateFieldSet2(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet4(this, _YargsInstance_usage, "f"), __classPrivateFieldGet4(this, _YargsInstance_command, "f"), __classPrivateFieldGet4(this, _YargsInstance_shim, "f")), "f");
__classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").reset();
__classPrivateFieldSet2(this, _YargsInstance_completionCommand, null, "f");
__classPrivateFieldSet2(this, _YargsInstance_output, "", "f");
__classPrivateFieldSet2(this, _YargsInstance_exitError, null, "f");
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, false, "f");
this.parsed = false;
return this;
}
[kRebase](base, dir) {
return __classPrivateFieldGet4(this, _YargsInstance_shim, "f").path.relative(base, dir);
}
[kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
let skipValidation = !!calledFromCommand || helpOnly;
args = args || __classPrivateFieldGet4(this, _YargsInstance_processArgs, "f");
__classPrivateFieldGet4(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").y18n.__;
__classPrivateFieldGet4(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
const populateDoubleDash = !!__classPrivateFieldGet4(this, _YargsInstance_options, "f").configuration["populate--"];
const config = Object.assign({}, __classPrivateFieldGet4(this, _YargsInstance_options, "f").configuration, {
"populate--": true
});
const parsed = __classPrivateFieldGet4(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet4(this, _YargsInstance_options, "f"), {
configuration: { "parse-positional-numbers": false, ...config }
}));
const argv = Object.assign(parsed.argv, __classPrivateFieldGet4(this, _YargsInstance_parseContext, "f"));
let argvPromise = void 0;
const aliases2 = parsed.aliases;
let helpOptSet = false;
let versionOptSet = false;
Object.keys(argv).forEach((key) => {
if (key === __classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f") && argv[key]) {
helpOptSet = true;
} else if (key === __classPrivateFieldGet4(this, _YargsInstance_versionOpt, "f") && argv[key]) {
versionOptSet = true;
}
});
argv.$0 = this.$0;
this.parsed = parsed;
if (commandIndex === 0) {
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
}
try {
this[kGuessLocale]();
if (shortCircuit) {
return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
}
if (__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f")) {
const helpCmds = [__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f")].concat(aliases2[__classPrivateFieldGet4(this, _YargsInstance_helpOpt, "f")] || []).filter((k6) => k6.length > 1);
if (helpCmds.includes("" + argv._[argv._.length - 1])) {
argv._.pop();
helpOptSet = true;
}
}
__classPrivateFieldSet2(this, _YargsInstance_isGlobalContext, false, "f");
const handlerKeys = __classPrivateFieldGet4(this, _YargsInstance_command, "f").getCommands();
const requestCompletions = __classPrivateFieldGet4(this, _YargsInstance_completion, "f").completionKey in argv;
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
if (argv._.length) {
if (handlerKeys.length) {
let firstUnknownCommand;
for (let i5 = commandIndex || 0, cmd; argv._[i5] !== void 0; i5++) {
cmd = String(argv._[i5]);
if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f")) {
const innerArgv = __classPrivateFieldGet4(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i5 + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
} else if (!firstUnknownCommand && cmd !== __classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f")) {
firstUnknownCommand = cmd;
break;
}
}
if (!__classPrivateFieldGet4(this, _YargsInstance_command, "f").hasDefaultCommand() && __classPrivateFieldGet4(this, _YargsInstance_recommendCommands, "f") && firstUnknownCommand && !skipRecommendation) {
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
}
}
if (__classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f") && argv._.includes(__classPrivateFieldGet4(this, _YargsInstance_completionCommand, "f")) && !requestCompletions) {
if (__classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f"))
setBlocking(true);
this.showCompletionScript();
this.exit(0);
}
}
if (__classPrivateFieldGet4(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
const innerArgv = __classPrivateFieldGet4(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
}
if (requestCompletions) {
if (__classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f"))
setBlocking(true);
args = [].concat(args);
const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet4(this, _YargsInstance_completion, "f").completionKey}`) + 1);
__classPrivateFieldGet4(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
if (err)
throw new YError(err.message);
(completions || []).forEach((completion2) => {
__classPrivateFieldGet4(this, _YargsInstance_logger, "f").log(completion2);
});
this.exit(0);
});
return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
}
if (!__classPrivateFieldGet4(this, _YargsInstance_hasOutput, "f")) {
if (helpOptSet) {
if (__classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f"))
setBlocking(true);
skipValidation = true;
this.showHelp("log");
this.exit(0);
} else if (versionOptSet) {
if (__classPrivateFieldGet4(this, _YargsInstance_exitProcess, "f"))
setBlocking(true);
skipValidation = true;
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").showVersion("log");
this.exit(0);
}
}
if (!skipValidation && __classPrivateFieldGet4(this, _YargsInstance_options, "f").skipValidation.length > 0) {
skipValidation = Object.keys(argv).some((key) => __classPrivateFieldGet4(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true);
}
if (!skipValidation) {
if (parsed.error)
throw new YError(parsed.error.message);
if (!requestCompletions) {
const validation2 = this[kRunValidation](aliases2, {}, parsed.error);
if (!calledFromCommand) {
argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true);
}
argvPromise = this[kValidateAsync](validation2, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
if (isPromise(argvPromise) && !calledFromCommand) {
argvPromise = argvPromise.then(() => {
return applyMiddleware(argv, this, __classPrivateFieldGet4(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
});
}
}
}
} catch (err) {
if (err instanceof YError)
__classPrivateFieldGet4(this, _YargsInstance_usage, "f").fail(err.message, err);
else
throw err;
}
return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
}
[kRunValidation](aliases2, positionalMap, parseErrors, isDefaultCommand) {
const demandedOptions = { ...this.getDemandedOptions() };
return (argv) => {
if (parseErrors)
throw new YError(parseErrors.message);
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").nonOptionCount(argv);
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
let failedStrictCommands = false;
if (__classPrivateFieldGet4(this, _YargsInstance_strictCommands, "f")) {
failedStrictCommands = __classPrivateFieldGet4(this, _YargsInstance_validation, "f").unknownCommands(argv);
}
if (__classPrivateFieldGet4(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases2, positionalMap, !!isDefaultCommand);
} else if (__classPrivateFieldGet4(this, _YargsInstance_strictOptions, "f")) {
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases2, {}, false, false);
}
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").limitedChoices(argv);
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").implications(argv);
__classPrivateFieldGet4(this, _YargsInstance_validation, "f").conflicting(argv);
};
}
[kSetHasOutput]() {
__classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
}
[kTrackManuallySetKeys](keys) {
if (typeof keys === "string") {
__classPrivateFieldGet4(this, _YargsInstance_options, "f").key[keys] = true;
} else {
for (const k6 of keys) {
__classPrivateFieldGet4(this, _YargsInstance_options, "f").key[k6] = true;
}
}
}
};
__name(isYargsInstance, "isYargsInstance");
}
});
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/index.mjs
var Yargs, yargs_default;
var init_yargs = __esm({
"../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/index.mjs"() {
"use strict";
init_import_meta_url();
init_esm();
init_yargs_factory();
Yargs = YargsFactory(esm_default);
yargs_default = Yargs;
}
});
// src/ai/index.ts
var aiNamespace, aiFineTuneNamespace;
var init_ai = __esm({
"src/ai/index.ts"() {
init_import_meta_url();
init_create_command();
aiNamespace = createNamespace({
metadata: {
description: "\u{1F916} Manage AI models",
status: "stable",
owner: "Product: AI"
}
});
aiFineTuneNamespace = createNamespace({
metadata: {
description: "Interact with finetune files",
status: "stable",
owner: "Product: AI"
}
});
}
});
// src/ai/utils.ts
function getErrorMessage(error2) {
return `${error2.text || error2.toString()}${error2.notes ? ` ${error2.notes.map((note) => note.text).join(", ")}` : ""}`;
}
function truncate2(str, maxLen) {
return str.slice(0, maxLen) + (str.length > maxLen ? "..." : "");
}
function truncateDescription(description, alreadyUsed) {
if (description === void 0 || description === null) {
return "";
}
if (process.stdout.columns === void 0) {
return truncate2(description, 100);
}
return truncate2(description, process.stdout.columns - alreadyUsed);
}
async function aiCatalogList(complianceConfig, accountId, partialUrl) {
const pageSize = 50;
let page = 1;
const results = [];
while (results.length % pageSize === 0) {
const json = await fetchResult(
complianceConfig,
`/accounts/${accountId}/ai/${partialUrl}`,
{},
new URLSearchParams({
per_page: pageSize.toString(),
page: page.toString()
})
);
page++;
results.push(...json);
if (json.length < pageSize) {
break;
}
}
return results;
}
async function aiFinetuneList(complianceConfig, accountId) {
const results = await fetchResult(
complianceConfig,
`/accounts/${accountId}/ai/finetunes`,
{},
new URLSearchParams({})
);
return results;
}
var listCatalogEntries, listFinetuneEntries;
var init_utils4 = __esm({
"src/ai/utils.ts"() {
init_import_meta_url();
init_cfetch();
__name(getErrorMessage, "getErrorMessage");
__name(truncate2, "truncate");
__name(truncateDescription, "truncateDescription");
__name(aiCatalogList, "aiCatalogList");
__name(aiFinetuneList, "aiFinetuneList");
listCatalogEntries = /* @__PURE__ */ __name(async (complianceConfig, accountId) => {
return await aiCatalogList(complianceConfig, accountId, "models/search");
}, "listCatalogEntries");
listFinetuneEntries = /* @__PURE__ */ __name(async (complianceConfig, accountId) => {
return await aiFinetuneList(complianceConfig, accountId);
}, "listFinetuneEntries");
}
});
// src/ai/createFinetune.ts
var import_fs15, import_path11, import_undici7, requiredAssets, aiFineTuneCreateCommand;
var init_createFinetune = __esm({
"src/ai/createFinetune.ts"() {
init_import_meta_url();
import_fs15 = __toESM(require("fs"));
import_path11 = __toESM(require("path"));
import_undici7 = __toESM(require_undici());
init_cfetch();
init_create_command();
init_logger();
init_user2();
init_utils4();
requiredAssets = ["adapter_config.json", "adapter_model.safetensors"];
aiFineTuneCreateCommand = createCommand({
metadata: {
description: "Create finetune and upload assets",
status: "stable",
owner: "Product: AI"
},
args: {
model_name: {
type: "string",
demandOption: true,
description: "The catalog model name"
},
finetune_name: {
type: "string",
demandOption: true,
description: "The finetune name"
},
folder_path: {
type: "string",
demandOption: true,
description: "The folder path containing the finetune assets"
}
},
positionalArgs: ["model_name", "finetune_name", "folder_path"],
async handler({ finetune_name, model_name, folder_path }, { config }) {
const accountId = await requireAuth(config);
logger.log(
`\u{1F300} Creating new finetune "${finetune_name}" for model "${model_name}"...`
);
try {
const files = import_fs15.default.readdirSync(folder_path, {
withFileTypes: true
});
if (requiredAssets.every(
(asset) => files.some((file) => file.name === asset)
)) {
try {
const finetune = await fetchResult(
config,
`/accounts/${accountId}/ai/finetunes`,
{
method: "POST",
body: JSON.stringify({
model: model_name,
name: finetune_name,
description: ""
})
}
);
for (let i5 = 0; i5 < files.length; i5++) {
const file = files[i5];
if (requiredAssets.includes(file.name)) {
const filePath = import_path11.default.join(folder_path, file.name);
logger.log(
`\u{1F300} Uploading file "${filePath}" to "${finetune_name}"...`
);
try {
const formdata = new import_undici7.FormData();
formdata.set("file_name", file.name);
formdata.set("file", new Blob([import_fs15.default.readFileSync(filePath)]));
await fetchResult(
config,
`/accounts/${accountId}/ai/finetunes/${finetune.id}/finetune-assets`,
{
method: "POST",
body: formdata
}
);
} catch (e7) {
logger.error(
`\u{1F6A8} Couldn't upload file: ${getErrorMessage(
e7
)}, quiting...`
);
return;
}
}
}
logger.log(
`\u2705 Assets uploaded, finetune "${finetune_name}" is ready to use.`
);
} catch (e7) {
logger.error(
`\u{1F6A8} Finetune couldn't be created: ${getErrorMessage(e7)}`
);
}
} else {
logger.error(
`\u{1F6A8} Asset missing. Required assets: ${requiredAssets.join(", ")}`
);
}
} catch (e7) {
logger.error(
`\u{1F6A8} Folder does not exist: ${getErrorMessage(e7)}`
);
}
}
});
}
});
// src/ai/listCatalog.ts
var aiModelsCommand;
var init_listCatalog = __esm({
"src/ai/listCatalog.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_utils4();
aiModelsCommand = createCommand({
metadata: {
description: "List catalog models",
status: "stable",
owner: "Product: AI"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
async handler({ json }, { config }) {
const accountId = await requireAuth(config);
const entries = await listCatalogEntries(config, accountId);
if (json) {
logger.log(JSON.stringify(entries, null, 2));
} else {
if (entries.length === 0) {
logger.log(`No models found.`);
} else {
logger.table(
entries.map((entry) => ({
model: entry.id,
name: entry.name,
description: truncateDescription(
entry.description,
entry.id.length + entry.name.length + (entry.task ? entry.task.name.length : 0) + 10
),
task: entry.task ? entry.task.name : ""
}))
);
}
}
}
});
}
});
// src/ai/listFinetune.ts
var aiFineTuneListCommand;
var init_listFinetune = __esm({
"src/ai/listFinetune.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_utils4();
aiFineTuneListCommand = createCommand({
metadata: {
description: "List your finetune files",
status: "stable",
owner: "Product: AI"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
async handler({ json }, { config }) {
const accountId = await requireAuth(config);
const entries = await listFinetuneEntries(config, accountId);
if (json) {
logger.log(JSON.stringify(entries, null, 2));
} else {
if (entries.length === 0) {
logger.log(`No finetune assets found.`);
} else {
logger.table(
entries.map((entry) => ({
finetune_id: entry.id,
name: entry.name,
description: truncateDescription(
entry.description,
entry.id.length + entry.name.length + 10
)
}))
);
}
}
}
});
}
});
// src/build/index.ts
var buildCommand2;
var init_build3 = __esm({
"src/build/index.ts"() {
init_import_meta_url();
init_create_command();
init_src2();
buildCommand2 = createCommand({
metadata: {
description: "\u{1F528} Build a Worker",
owner: "Workers: Authoring and Testing",
status: "stable",
hidden: true
},
behaviour: {
printBanner: false,
provideConfig: false
},
async handler(buildArgs) {
const { wrangler } = createCLIParser([
"deploy",
"--dry-run",
"--outdir=dist",
...buildArgs.env ? ["--env", buildArgs.env] : [],
...buildArgs.config ? ["--config", buildArgs.config] : []
]);
await wrangler.parse();
}
});
}
});
// src/api/mtls-certificate.ts
async function uploadMTlsCertificateFromFs(complianceConfig, accountId, details) {
return await uploadMTlsCertificate(complianceConfig, accountId, {
certificateChain: readFileSync6(details.certificateChainFilename),
privateKey: readFileSync6(details.privateKeyFilename),
name: details.name
});
}
async function uploadCaCertificateFromFs(complianceConfig, accountId, details) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/mtls_certificates`,
{
method: "POST",
body: JSON.stringify({
name: details.name,
certificates: readFileSync6(details.certificates),
ca: details.ca
})
}
);
}
async function uploadMTlsCertificate(complianceConfig, accountId, body) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/mtls_certificates`,
{
method: "POST",
body: JSON.stringify({
name: body.name,
certificates: body.certificateChain,
private_key: body.privateKey,
ca: false
})
}
);
}
async function getMTlsCertificate(complianceConfig, accountId, id) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/mtls_certificates/${id}`,
{}
);
}
async function listMTlsCertificates(complianceConfig, accountId, filter, ca2 = false) {
const params = new URLSearchParams();
if (!ca2) {
params.append("ca", String(false));
}
if (filter.name) {
params.append("name", filter.name);
}
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/mtls_certificates`,
{},
params
);
}
async function getMTlsCertificateByName(complianceConfig, accountId, name2, ca2 = false) {
const certificates = await listMTlsCertificates(
complianceConfig,
accountId,
{ name: name2 },
ca2
);
if (certificates.length === 0) {
throw new ErrorMTlsCertificateNameNotFound(
`certificate not found with name "${name2}"`
);
}
if (certificates.length > 1) {
throw new ErrorMTlsCertificateManyNamesMatch(
`multiple certificates found with name "${name2}"`
);
}
const certificate = certificates[0];
return certificate;
}
async function deleteMTlsCertificate(complianceConfig, accountId, certificateId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/mtls_certificates/${certificateId}`,
{ method: "DELETE" }
);
}
var ErrorMTlsCertificateNameNotFound, ErrorMTlsCertificateManyNamesMatch;
var init_mtls_certificate = __esm({
"src/api/mtls-certificate.ts"() {
init_import_meta_url();
init_cfetch();
init_errors();
init_parse();
ErrorMTlsCertificateNameNotFound = class extends UserError {
static {
__name(this, "ErrorMTlsCertificateNameNotFound");
}
};
ErrorMTlsCertificateManyNamesMatch = class extends UserError {
static {
__name(this, "ErrorMTlsCertificateManyNamesMatch");
}
};
__name(uploadMTlsCertificateFromFs, "uploadMTlsCertificateFromFs");
__name(uploadCaCertificateFromFs, "uploadCaCertificateFromFs");
__name(uploadMTlsCertificate, "uploadMTlsCertificate");
__name(getMTlsCertificate, "getMTlsCertificate");
__name(listMTlsCertificates, "listMTlsCertificates");
__name(getMTlsCertificateByName, "getMTlsCertificateByName");
__name(deleteMTlsCertificate, "deleteMTlsCertificate");
}
});
// src/cert/cert.ts
var certNamespace, certUploadNamespace, certUploadMtlsCommand, certUploadCaCertCommand, certListCommand, certDeleteCommand;
var init_cert = __esm({
"src/cert/cert.ts"() {
init_import_meta_url();
init_mtls_certificate();
init_create_command();
init_dialogs();
init_logger();
init_user2();
certNamespace = createNamespace({
metadata: {
description: "\u{1FAAA} Manage client mTLS certificates and CA certificate chains used for secured connections",
status: "open-beta",
owner: "Product: SSL"
}
});
certUploadNamespace = createNamespace({
metadata: {
description: "Upload a new cert",
status: "open-beta",
owner: "Product: SSL"
}
});
certUploadMtlsCommand = createCommand({
metadata: {
description: "Upload an mTLS certificate",
status: "stable",
owner: "Product: SSL"
},
args: {
cert: {
description: "The path to a certificate file (.pem) containing a chain of certificates to upload",
type: "string",
demandOption: true
},
key: {
description: "The path to a file containing the private key for your leaf certificate",
type: "string",
demandOption: true
},
name: {
description: "The name for the certificate",
type: "string"
}
},
async handler({ cert, key, name: name2 }, { config }) {
const accountId = await requireAuth(config);
logger.log(
name2 ? `Uploading mTLS Certificate ${name2}...` : `Uploading mTLS Certificate...`
);
const certResponse = await uploadMTlsCertificateFromFs(config, accountId, {
certificateChainFilename: cert,
privateKeyFilename: key,
name: name2
});
const expiresOn = new Date(certResponse.expires_on).toLocaleDateString();
logger.log(
name2 ? `Success! Uploaded mTLS Certificate ${name2}` : `Success! Uploaded mTLS Certificate`
);
logger.log(`ID: ${certResponse.id}`);
logger.log(`Issuer: ${certResponse.issuer}`);
logger.log(`Expires on ${expiresOn}`);
}
});
certUploadCaCertCommand = createCommand({
metadata: {
description: "Upload a CA certificate chain",
status: "stable",
owner: "Product: SSL"
},
args: {
name: {
describe: "The name for the certificate",
type: "string"
},
"ca-cert": {
description: "The path to a certificate file (.pem) containing a chain of CA certificates to upload",
type: "string",
demandOption: true
}
},
async handler({ caCert, name: name2 }, { config }) {
const accountId = await requireAuth(config);
logger.log(
name2 ? `Uploading CA Certificate ${name2}...` : `Uploading CA Certificate...`
);
const certResponse = await uploadCaCertificateFromFs(config, accountId, {
certificates: caCert,
ca: true,
name: name2
});
const expiresOn = new Date(certResponse.expires_on).toLocaleDateString();
logger.log(
name2 ? `Success! Uploaded CA Certificate ${name2}` : `Success! Uploaded CA Certificate`
);
logger.log(`ID: ${certResponse.id}`);
logger.log(`Issuer: ${certResponse.issuer}`);
logger.log(`Expires on ${expiresOn}`);
}
});
certListCommand = createCommand({
metadata: {
description: "List uploaded mTLS certificates",
status: "stable",
owner: "Product: SSL"
},
async handler(_4, { config }) {
const accountId = await requireAuth(config);
const certificates = await listMTlsCertificates(
config,
accountId,
{},
true
);
for (const certificate of certificates) {
logger.log(`ID: ${certificate.id}`);
if (certificate.name) {
logger.log(`Name: ${certificate.name}`);
}
logger.log(`Issuer: ${certificate.issuer}`);
logger.log(
`Created on: ${new Date(certificate.uploaded_on).toLocaleDateString()}`
);
logger.log(
`Expires on: ${new Date(certificate.expires_on).toLocaleDateString()}`
);
if (certificate.ca) {
logger.log(`CA: ${certificate.ca}`);
}
logger.log("\n");
}
}
});
certDeleteCommand = createCommand({
metadata: {
description: "Delete an mTLS certificate",
status: "stable",
owner: "Product: SSL"
},
args: {
id: {
description: "The id of the mTLS certificate to delete",
type: "string"
},
name: {
description: "The name of the mTLS certificate record to delete",
type: "string"
}
},
async handler({ id, name: name2 }, { config }) {
const accountId = await requireAuth(config);
if (id && name2) {
return logger.error(`Can't provide both --id and --name.`);
} else if (!id && !name2) {
return logger.error(`Must provide --id or --name.`);
}
let certificate;
if (id) {
certificate = await getMTlsCertificate(config, accountId, id);
} else {
certificate = await getMTlsCertificateByName(
config,
accountId,
name2,
true
);
}
const response = await confirm(
`Are you sure you want to delete certificate ${certificate.id}${certificate.name ? ` (${certificate.name})` : ""}?`
);
if (!response) {
logger.log("Not deleting");
return;
}
await deleteMTlsCertificate(config, accountId, certificate.id);
logger.log(
`Deleted certificate ${certificate.id} ${certificate.name ? `(${certificate.name})` : ""} successfully`
);
}
});
}
});
// src/cloudchamber/apply.ts
function mergeDeep3(target, source) {
if (typeof target !== "object" || target === null) {
return source;
}
if (typeof source !== "object" || source === null) {
return target;
}
const result = { ...target };
for (const key of Object.keys(source)) {
const srcVal = source[key];
const tgtVal = target[key];
if (isObject2(tgtVal) && isObject2(srcVal)) {
result[key] = mergeDeep3(tgtVal, srcVal);
} else {
result[key] = srcVal;
}
}
return result;
}
function isObject2(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function applyCommandOptionalYargs(yargs) {
return yargs.option("skip-defaults", {
requiresArg: true,
type: "boolean",
demandOption: false,
describe: "Skips recommended defaults added by apply"
});
}
function createApplicationToModifyApplication2(req) {
return {
configuration: req.configuration,
instances: req.max_instances !== void 0 ? 0 : req.instances,
max_instances: req.max_instances,
constraints: req.constraints,
affinities: req.affinities,
scheduling_policy: req.scheduling_policy
};
}
function applicationToCreateApplication(accountId, application) {
const app = {
configuration: {
...application.configuration,
image: resolveImageName(accountId, application.configuration.image)
},
constraints: application.constraints,
max_instances: application.max_instances,
name: application.name,
scheduling_policy: application.scheduling_policy,
affinities: application.affinities,
instances: application.max_instances !== void 0 ? 0 : application.instances,
jobs: application.jobs ? true : void 0,
durable_objects: application.durable_objects
};
return app;
}
function cleanupObservability2(observability) {
if (observability === void 0) {
return;
}
if (observability.logging !== void 0 && observability.logs !== void 0) {
delete observability.logging;
}
}
function observabilityToConfiguration2(observability, existingObservabilityConfig) {
const observabilityLogsEnabled = observability?.logs?.enabled === true || observability?.enabled === true && observability?.logs?.enabled !== false;
const logsAlreadyEnabled = existingObservabilityConfig?.logs?.enabled;
if (observabilityLogsEnabled) {
return { logs: { enabled: true } };
} else {
if (logsAlreadyEnabled === void 0) {
return void 0;
} else {
return { logs: { enabled: false } };
}
}
}
function containerAppToInstanceType(containerApp) {
let configuration = containerApp.configuration ?? {};
if (containerApp.instance_type !== void 0) {
if (typeof containerApp.instance_type === "string") {
return { instance_type: containerApp.instance_type };
}
configuration = {
vcpu: containerApp.instance_type.vcpu,
memory_mib: containerApp.instance_type.memory_mib,
disk: {
size_mb: containerApp.instance_type.disk_mb
}
};
}
if (configuration.disk?.size_mb === void 0 && configuration.vcpu === void 0 && configuration.memory_mib === void 0) {
return { instance_type: "dev" /* DEV */ };
}
return configuration;
}
function containerAppToCreateApplication(accountId, containerApp, observability, existingApp, skipDefaults = false) {
const observabilityConfiguration = observabilityToConfiguration2(
observability,
existingApp?.configuration.observability
);
const instanceType = containerAppToInstanceType(containerApp);
const configuration = {
...containerApp.configuration,
...instanceType,
observability: observabilityConfiguration
};
if (containerApp.name === void 0) {
throw new FatalError("Container application name failed to be set", 1, {
telemetryMessage: true
});
}
const app = {
...containerApp,
name: containerApp.name,
configuration: {
...configuration,
// De-sugar image name
image: resolveImageName(accountId, configuration.image)
},
instances: containerApp.instances ?? 0,
scheduling_policy: containerApp.scheduling_policy ?? "default" /* DEFAULT */,
constraints: {
...containerApp.constraints ?? (!skipDefaults ? { tier: 1 } : void 0),
cities: containerApp.constraints?.cities?.map(
(city) => city.toLowerCase()
),
regions: containerApp.constraints?.regions?.map(
(region) => region.toUpperCase()
)
}
};
delete app["class_name"];
delete app["image"];
delete app["image_build_context"];
delete app["image_vars"];
delete app["rollout_step_percentage"];
delete app["rollout_kind"];
delete app["instance_type"];
return app;
}
async function apply2(args, config) {
startSection(
"Deploy a container application",
"deploy changes to your application"
);
config.containers ??= [];
if (config.containers.length === 0) {
endSection(
"You don't have any container applications defined in your wrangler.toml",
"You can set the following configuration in your wrangler.toml"
);
const configuration = {
image: "docker.io/cloudflare/hello-world:1.0",
instances: 2,
name: config.name ?? "my-containers-application",
instance_type: "dev"
};
const endConfig = args.env !== void 0 ? {
env: { [args.env]: { containers: [configuration] } }
} : { containers: [configuration] };
formatConfigSnippet(endConfig, config.configPath).split("\n").forEach((el) => logRaw(` ${el}`));
return;
}
const applications = await promiseSpinner(
ApplicationsService.listApplications(),
{ message: "Loading applications" }
);
applications.forEach(
(app) => cleanupObservability2(app.configuration.observability)
);
const applicationByNames = {};
for (const application of applications) {
applicationByNames[application.name] = application;
}
const actions = [];
log(dim("Container application changes\n"));
for (const appConfigNoDefaults of config.containers) {
appConfigNoDefaults.configuration ??= {};
appConfigNoDefaults.configuration.image = appConfigNoDefaults.image;
const application = applicationByNames[appConfigNoDefaults.name ?? // we should never actually reach this point, but just in case
`${config.name}-${appConfigNoDefaults.class_name}`];
const accountId = config.account_id || await getAccountId(config);
const appConfig = containerAppToCreateApplication(
accountId,
appConfigNoDefaults,
config.observability,
application,
args.skipDefaults
);
if (application !== void 0 && application !== null) {
const prevApp = sortObjectRecursive(
stripUndefined(applicationToCreateApplication(accountId, application))
);
if (appConfigNoDefaults.scheduling_policy === void 0) {
appConfig.scheduling_policy = prevApp.scheduling_policy;
}
if (prevApp.durable_objects !== void 0 && appConfigNoDefaults.durable_objects !== void 0 && prevApp.durable_objects.namespace_id !== appConfigNoDefaults.durable_objects.namespace_id) {
throw new UserError(
`Application "${prevApp.name}" is assigned to durable object ${prevApp.durable_objects.namespace_id}, but a new DO namespace is being assigned to the application,
you should delete the container application and deploy again`
);
}
const prevContainer = appConfig.configuration.instance_type !== void 0 ? cleanForInstanceType(prevApp) : prevApp;
const nowContainer = mergeDeep3(
prevContainer,
sortObjectRecursive(appConfig)
);
const prev = formatConfigSnippet(
{ containers: [prevContainer] },
config.configPath
);
const now = formatConfigSnippet(
{ containers: [nowContainer] },
config.configPath
);
const diff = new Diff(prev, now);
if (diff.changes === 0) {
updateStatus(`no changes ${brandColor(application.name)}`);
continue;
}
updateStatus(
`${brandColor.underline("EDIT")} ${application.name}`,
false
);
newline();
diff.print();
newline();
if (appConfigNoDefaults.rollout_kind !== "none") {
actions.push({
action: "modify",
application: createApplicationToModifyApplication2(appConfig),
id: application.id,
name: application.name,
rollout_step_percentage: application.durable_objects !== void 0 ? appConfigNoDefaults.rollout_step_percentage ?? 25 : appConfigNoDefaults.rollout_step_percentage,
rollout_kind: appConfigNoDefaults.rollout_kind == "full_manual" ? CreateApplicationRolloutRequest.kind.FULL_MANUAL : CreateApplicationRolloutRequest.kind.FULL_AUTO
});
} else {
log("Skipping application rollout");
newline();
}
continue;
}
updateStatus(bold.underline(green.underline("NEW")) + ` ${appConfig.name}`);
const s5 = formatConfigSnippet(
{
containers: [
{
...appConfig,
instances: appConfig.max_instances !== void 0 ? (
// trick until we allow setting instances to undefined in the API
void 0
) : appConfig.instances
}
]
},
config.configPath
);
s5.trimEnd().split("\n").forEach((el) => log(` ${el}`));
newline();
const configToPush = { ...appConfig };
actions.push({
action: "create",
application: configToPush
});
}
if (actions.length == 0) {
endSection("No changes to be made");
return;
}
function formatError2(err) {
if (err.body.error === "VALIDATE_INPUT" /* VALIDATE_INPUT */ && err.body.details !== void 0) {
let message = "";
for (const key in err.body.details) {
message += ` ${brandColor(key)} ${err.body.details[key]}
`;
}
return message;
}
if (err.body.error !== void 0) {
return ` ${err.body.error}`;
}
return JSON.stringify(err.body);
}
__name(formatError2, "formatError");
for (const action of actions) {
if (action.action === "create") {
let application;
try {
application = await promiseSpinner(
ApplicationsService.createApplication(action.application),
{ message: `Creating ${action.application.name}` }
);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (!(err instanceof ApiError)) {
throw new UserError(
`Unexpected error creating application: ${err.message}`
);
}
if (err.status === 400) {
throw new UserError(
`Error creating application due to a misconfiguration
${formatError2(err)}`
);
}
throw new UserError(
`Error creating application due to an internal error (request id: ${err.body.request_id}):
${formatError2(err)}`
);
}
success(
`Created application ${brandColor(action.application.name)} (Application ID: ${application.id})`,
{
shape: shapes.bar
}
);
continue;
}
if (action.action === "modify") {
try {
await promiseSpinner(
ApplicationsService.modifyApplication(action.id, {
...action.application,
instances: action.application.max_instances !== void 0 ? void 0 : action.application.instances
}),
{ message: `Modifying ${action.application.name}` }
);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (!(err instanceof ApiError)) {
throw new UserError(
`Unexpected error modifying application ${action.name}: ${err.message}`
);
}
if (err.status === 400) {
throw new UserError(
`Error modifying application ${action.name} due to a misconfiguration:
${formatError2(err)}`
);
}
throw new UserError(
`Error modifying application ${action.name} due to an internal error (request id: ${err.body.request_id}):
${formatError2(err)}`
);
}
if (action.rollout_step_percentage !== void 0) {
try {
await promiseSpinner(
RolloutsService.createApplicationRollout(action.id, {
description: "Progressive update",
strategy: CreateApplicationRolloutRequest.strategy.ROLLING,
target_configuration: action.application.configuration ?? {},
...configRolloutStepsToAPI(action.rollout_step_percentage),
kind: action.rollout_kind
}),
{
message: `rolling out container version ${action.name}`
}
);
} catch (err) {
if (!(err instanceof Error)) {
throw err;
}
if (!(err instanceof ApiError)) {
throw new UserError(
`Unexpected error rolling out application ${action.name}:
${err.message}`
);
}
if (err.status === 400) {
throw new UserError(
`Error rolling out application ${action.name} due to a misconfiguration:
${formatError2(err)}`
);
}
throw new UserError(
`Error rolling out application ${action.name} due to an internal error (request id: ${err.body.request_id}): ${formatError2(err)}`
);
}
}
success(`Modified application ${brandColor(action.name)}`, {
shape: shapes.bar
});
continue;
}
}
newline();
endSection("Applied changes");
}
async function applyCommand(args, config) {
return apply2(
{
skipDefaults: args.skipDefaults,
env: args.env
},
config
);
}
var init_apply = __esm({
"src/cloudchamber/apply.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_containers_shared();
init_config2();
init_deploy();
init_errors();
init_user2();
init_sortObjectRecursive();
init_common();
init_diff();
init_instance_type();
__name(mergeDeep3, "mergeDeep");
__name(isObject2, "isObject");
__name(applyCommandOptionalYargs, "applyCommandOptionalYargs");
__name(createApplicationToModifyApplication2, "createApplicationToModifyApplication");
__name(applicationToCreateApplication, "applicationToCreateApplication");
__name(cleanupObservability2, "cleanupObservability");
__name(observabilityToConfiguration2, "observabilityToConfiguration");
__name(containerAppToInstanceType, "containerAppToInstanceType");
__name(containerAppToCreateApplication, "containerAppToCreateApplication");
__name(apply2, "apply");
__name(applyCommand, "applyCommand");
}
});
// src/cloudchamber/cli/util.ts
function capitalize(str) {
return str.length > 0 ? str[0].toUpperCase() + str.substring(1) : str;
}
function statusToColored(status2) {
if (!status2) {
return bgYellow("PLACING");
}
const mappings = {
placed: bgYellow,
running: bgGreen,
stopped: bgYellow,
stopping: bgYellow,
failed: bgRed,
unhealthy: bgRed
};
if (!(status2 in mappings)) {
return bgYellow(status2);
}
return mappings[status2](status2.toUpperCase());
}
var init_util = __esm({
"src/cloudchamber/cli/util.ts"() {
init_import_meta_url();
init_colors();
__name(capitalize, "capitalize");
__name(statusToColored, "statusToColored");
}
});
// src/cloudchamber/cli/index.ts
function pollRegistriesUntilCondition(onRegistries) {
return new Promise((res, rej) => {
let errCount = 0;
const poll = /* @__PURE__ */ __name(() => {
ImageRegistriesService.listImageRegistries().then((registries) => {
try {
if (!onRegistries(registries)) {
setTimeout(() => poll(), 500);
} else {
res(registries);
}
} catch (err) {
rej(err);
}
}).catch((err) => {
errCount++;
if (errCount > 3) {
rej(err);
return;
}
poll();
});
}, "poll");
poll();
});
}
function pollSSHKeysUntilCondition(onSSHKeys) {
return new Promise((res, rej) => {
let errCount = 0;
const poll = /* @__PURE__ */ __name(() => {
SshPublicKeysService.listSshPublicKeys().then((sshKeys) => {
try {
if (!onSSHKeys(sshKeys)) {
setTimeout(() => poll(), 500);
} else {
res(sshKeys);
}
} catch (err) {
rej(err);
}
}).catch((err) => {
errCount++;
if (errCount > 3) {
rej(err);
return;
}
poll();
});
}, "poll");
poll();
});
}
async function pollDeploymentUntilCondition(deploymentId, onDeployment) {
return new Promise((res, rej) => {
let errCount = 0;
const poll = /* @__PURE__ */ __name(() => {
DeploymentsService.getDeploymentV2(deploymentId).then((deployment) => {
errCount = 0;
try {
if (!onDeployment(deployment)) {
setTimeout(() => poll(), 500);
} else {
res(deployment);
}
} catch (err) {
rej(err);
}
}).catch((err) => {
errCount++;
if (errCount > 3) {
rej(err);
}
});
}, "poll");
poll();
});
}
async function pollDeploymentUntilConditionWithPlacement(placementId, onPlacement) {
return new Promise((res, rej) => {
let errCount = 0;
const poll = /* @__PURE__ */ __name(() => {
PlacementsService.getPlacement(placementId).then((placement) => {
errCount = 0;
if (!onPlacement(placement)) {
setTimeout(() => poll(), 500);
} else {
res(placement);
}
}).catch((err) => {
errCount++;
if (errCount > 3) {
rej(err);
}
});
}, "poll");
poll();
});
}
function unexpectedLastEvent(placement) {
throw new WaitForAnotherPlacement(
`There has been an unknown error creating the container. (${placement.events[placement.events.length - 1].name})`
);
}
async function waitForEvent(deployment, ...eventName) {
if (!deployment.current_placement) {
throw new Error("unexpected null current placement");
}
let foundEvent;
const placement = await pollDeploymentUntilConditionWithPlacement(
deployment.current_placement.id,
(p6) => {
const event = p6.events.find(
(e7) => eventName.includes(e7.name)
);
if (!event) {
if (p6.status["health"] === "failed") {
return true;
}
if (p6.status["health"] == "stopped") {
return true;
}
return false;
}
foundEvent = event;
return true;
}
);
return { event: foundEvent, placement };
}
async function waitForImagePull(deployment) {
const s5 = spinner();
s5.start("Pulling your image");
const [eventPlacement, err] = await wrap2(
waitForEvent(deployment, "ImagePulled", "ImagePullError")
);
s5.stop();
if (err) {
throw new UserError(err.message);
}
if (eventPlacement.event == void 0 || eventPlacement.event.name === "ImagePullError" && eventPlacement.event.type !== "UserError") {
checkPlacementStatus(eventPlacement.placement);
return;
}
if (eventPlacement.event.name == "ImagePullError") {
if (eventPlacement.event.message.includes("404")) {
throw new UserError(
`Your container image couldn't be pulled, (404 not found). Did you specify the correct URL?
Run ${brandColor(
process.argv0 + " cloudchamber modify " + deployment.id
)} to change the deployment image`
);
}
throw new UserError(capitalize(eventPlacement.event.message));
}
updateStatus("Pulled your image");
log(
`${brandColor("pulled image")} ${dim(
`in ${eventPlacement.event.details["duration"]}`
)}
`
);
}
function checkPlacementStatus(placement) {
if (placement.status["health"] === "stopped") {
throw new WaitForAnotherPlacement(
`The container stopped while waiting for the deployment to be created.
Either the deployment has been modified, changed location, or your container is in a reboot loop!`
);
}
unexpectedLastEvent(placement);
}
async function waitForVMToStart(deployment) {
const s5 = spinner();
s5.start("Creating your container");
const [eventPlacement, err] = await wrap2(
waitForEvent(deployment, "VMStarted")
);
s5.stop();
if (err) {
throw new UserError(err.message);
}
if (!eventPlacement.event) {
checkPlacementStatus(eventPlacement.placement);
}
const ipv4 = eventPlacement.placement.status["ipv4Address"];
if (ipv4) {
log(`${brandColor("assigned IPv4 address")} ${dim(ipv4)}
`);
}
const ipv62 = eventPlacement.placement.status["ipv6Address"];
if (ipv62) {
log(`${brandColor("assigned IPv6 address")} ${dim(ipv62)}
`);
}
endSection("Done");
logRaw(status.success + " Created your container\n");
logRaw(
`Run ${brandColor(
`wrangler cloudchamber list ${deployment.id.slice(0, 6)}`
)} to check its status`
);
}
async function waitForPlacementInstance(deployment) {
const s5 = spinner();
s5.start(
"Assigning a placement in " + idToLocationName(deployment.location.name)
);
const [d6, err] = await wrap2(
pollDeploymentUntilCondition(deployment.id, (newDeployment) => {
if (newDeployment.current_placement && !deployment.current_placement) {
return true;
}
if (!newDeployment.current_placement) {
return false;
}
if (newDeployment.version > deployment.version) {
s5.stop();
throw new WaitForAnotherPlacement(
`There is a new version of the deployment modified in another wrangler session, new version is ${newDeployment.version}`
);
}
if (newDeployment.current_placement.deployment_version < deployment.version) {
return false;
}
return newDeployment.current_placement.id !== deployment.current_placement?.id;
})
);
s5.stop();
if (err instanceof WaitForAnotherPlacement) {
throw err;
}
if (err) {
throw new UserError(err.message);
}
updateStatus(
"Assigned placement in " + idToLocationName(deployment.location.name),
false
);
if (d6.current_placement !== void 0) {
log(
`${brandColor("version")} ${dim(d6.current_placement.deployment_version)}`
);
log(`${brandColor("id")} ${dim(d6.current_placement?.id)}`);
newline();
}
deployment.current_placement = d6.current_placement;
}
async function waitForPlacement(deployment) {
let currentDeployment = { ...deployment };
let keepIterating = true;
while (keepIterating) {
try {
await waitForPlacementInstance(currentDeployment);
await waitForImagePull(currentDeployment);
await waitForVMToStart(currentDeployment);
keepIterating = false;
} catch (err) {
if (err instanceof WaitForAnotherPlacement) {
updateStatus(status.error + " " + err.message);
log(
"We will retry by waiting for another placement. You can see more details about your deployment with \n" + brandColor("wrangler cloudchamber list " + currentDeployment.id) + "\n"
);
const [newDeployment, getDeploymentError] = await wrap2(
DeploymentsService.getDeploymentV2(deployment.id)
);
if (getDeploymentError) {
throw new UserError(
"Couldn't retrieve a new deployment: " + getDeploymentError.message
);
}
currentDeployment = newDeployment;
continue;
}
throw err;
}
}
}
var WaitForAnotherPlacement;
var init_cli2 = __esm({
"src/cloudchamber/cli/index.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_interactive();
init_containers_shared();
init_errors();
init_wrap();
init_locations();
init_util();
__name(pollRegistriesUntilCondition, "pollRegistriesUntilCondition");
__name(pollSSHKeysUntilCondition, "pollSSHKeysUntilCondition");
__name(pollDeploymentUntilCondition, "pollDeploymentUntilCondition");
__name(pollDeploymentUntilConditionWithPlacement, "pollDeploymentUntilConditionWithPlacement");
__name(unexpectedLastEvent, "unexpectedLastEvent");
WaitForAnotherPlacement = class extends Error {
static {
__name(this, "WaitForAnotherPlacement");
}
constructor(message) {
super(message);
}
};
__name(waitForEvent, "waitForEvent");
__name(waitForImagePull, "waitForImagePull");
__name(checkPlacementStatus, "checkPlacementStatus");
__name(waitForVMToStart, "waitForVMToStart");
__name(waitForPlacementInstance, "waitForPlacementInstance");
__name(waitForPlacement, "waitForPlacement");
}
});
// src/cloudchamber/cli/locations.ts
function plural(word, size) {
if (size > 1) {
return `${word}s`;
}
return word;
}
async function getLocation2(args, options = {}) {
const locations = await getLocations();
if (args.location !== void 0 && !locations.find((location2) => location2.location === args.location)) {
locations.push({
name: `Other (${args.location})`,
location: args.location,
region: ""
});
}
if (args.location !== void 0) {
const location2 = await processArgument(args, "location", {
question: whichLocationQuestion,
label: "location",
defaultValue: args.location ?? "",
type: "select",
maxItemsPerPage: 6,
options: locations.map((locationOption) => ({
label: locationOption.name,
value: locationOption.location
}))
});
return location2;
}
const regionsToLocation = {};
for (const location2 of locations) {
regionsToLocation[location2.region] ??= [];
regionsToLocation[location2.region].push(location2);
}
if (options.skipLocation) {
regionsToLocation["Skip"] = [];
}
const region = await inputPrompt({
question: whichRegionQuestion,
label: "region",
defaultValue: args.location ?? "",
type: "select",
maxItemsPerPage: 4,
options: Object.keys(regionsToLocation).map((r7) => ({
value: r7,
label: `${r7} ${r7 === "Skip" ? "" : `(${regionsToLocation[r7].length} ${plural(
"location",
regionsToLocation[r7].length
)})`}`
}))
});
if (region === "Skip") {
return "Skip";
}
const locationsToChoose = regionsToLocation[region];
const locationToPops = {};
for (const location2 of locationsToChoose) {
locationToPops[location2.name] ??= [];
locationToPops[location2.name].push(location2);
}
const location = await inputPrompt({
question: whichLocationQuestion,
label: "location",
defaultValue: args.location ?? "",
type: "select",
maxItemsPerPage: 6,
options: Object.keys(locationToPops).map((locationOption) => ({
value: locationOption,
label: locationOption
}))
});
const pops = locationToPops[location];
if (pops.length === 1) {
return pops.pop().location;
}
const chosenPop = await inputPrompt({
question: `There is multiple points of presence in ${location}, which one do you want to be in?`,
label: "location",
defaultValue: args.location ?? "",
type: "select",
maxItemsPerPage: 6,
options: pops.map((locationOpt) => ({
label: `${locationOpt.name} (${locationOpt.location})`,
value: locationOpt.location
}))
});
return chosenPop;
}
var whichLocationQuestion, whichRegionQuestion;
var init_locations2 = __esm({
"src/cloudchamber/cli/locations.ts"() {
init_import_meta_url();
init_args();
init_interactive();
init_locations();
whichLocationQuestion = "Choose where you want to deploy your container";
whichRegionQuestion = "Choose which region you want to deploy your container in";
__name(plural, "plural");
__name(getLocation2, "getLocation");
}
});
// src/cloudchamber/network/network.ts
async function getNetworkInput(args) {
const ipv4 = await processArgument(args, "ipv4", {
question: "Add an IPv4 to the deployment?",
helpText: "Your deployment will have IPv4 network connectivity if you select yes. Your deployment will always have an IPv6",
label: "Include IPv4",
type: "confirm"
});
return ipv4 === true ? { assign_ipv4: "predefined" /* PREDEFINED */ } : { assign_ipv6: "predefined" /* PREDEFINED */ };
}
var init_network = __esm({
"src/cloudchamber/network/network.ts"() {
init_import_meta_url();
init_args();
init_containers_shared();
__name(getNetworkInput, "getNetworkInput");
}
});
// src/cloudchamber/ssh/validate.ts
function validateSSHKey(line) {
const supportedSyntaxInfo = "Syntax is space-separated: keytype, base64-encoded key, comment(optional). Example: 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC0chNcjRotdsxXTwPPNoqVCGn4EcEWdUkkBPNm/v4gm cool-public-key'";
const supportedKeyTypes = ["ssh-ed25519"];
const syntaxError = `Invalid Authorized Key format.`;
const keyTypeError = `Invalid key type. Supported key types are: ${supportedKeyTypes.join(
","
)}. ${supportedSyntaxInfo}`;
const invalidKey = `Invalid public key. ${supportedSyntaxInfo}`;
const parts = line.split(" ");
if (![2, 3].includes(parts.length)) {
throw new Error(syntaxError);
}
const keyType = parts[0];
if (!supportedKeyTypes.includes(keyType)) {
throw new Error(keyTypeError);
}
const base64Key = parts[1];
try {
atob(base64Key);
} catch {
throw new Error(invalidKey);
}
}
function validatePublicSSHKeyCLI(line, { json }) {
const bail = /* @__PURE__ */ __name((reason) => {
if (!json) {
throw new UserError(reason);
} else {
logger.json({ error: reason });
(0, import_process2.exit)(1);
}
}, "bail");
try {
validateSSHKey(line);
} catch (err) {
if (err instanceof Error) {
bail(err.message);
}
bail("unknown error validating ssh key");
}
}
var import_process2;
var init_validate = __esm({
"src/cloudchamber/ssh/validate.ts"() {
init_import_meta_url();
import_process2 = require("process");
init_errors();
init_logger();
__name(validateSSHKey, "validateSSHKey");
__name(validatePublicSSHKeyCLI, "validatePublicSSHKeyCLI");
}
});
// src/cloudchamber/ssh/ssh.ts
function createSSHPublicKeyOptionalYargs(yargs) {
return yargs.option("name", {
type: "string",
describe: "The alias to your ssh key, you can put a recognisable name for you here"
}).option("public-key", {
type: "string",
describe: "An SSH public key, you can specify either a path or the ssh key directly here"
});
}
async function retrieveSSHKey(sshKeyPath, { json } = { json: false }) {
try {
const file = (await (0, import_promises12.readFile)(sshKeyPath)).toString();
validatePublicSSHKeyCLI(file, { json });
return file;
} catch {
if (!json) {
logger.debug("couldn't read the file, assuming input is an ssh key");
}
validatePublicSSHKeyCLI(sshKeyPath, { json });
return sshKeyPath;
}
}
async function sshPrompts(args, keys = void 0) {
const [key, prompt2] = await shouldPromptForNewSSHKeyAppear(keys);
if (prompt2) {
const yes = await inputPrompt({
question: "You didn't add any public keys from your .ssh folder, do you want to add one?",
label: "",
defaultValue: false,
helpText: "If you don't add a public ssh key, you won't be able to ssh into your container unless you set it up",
type: "confirm"
});
if (yes) {
const sshKey = await promptForSSHKey({
...args,
name: void 0,
publicKey: void 0
});
updateStatus(
"You will be able to ssh into containers where you add this ssh key from now on!"
);
return sshKey.id;
}
return key || void 0;
}
return key || void 0;
}
async function tryToRetrieveAllDefaultSSHKeyPaths() {
const HOME = (0, import_os4.homedir)();
const path72 = `${HOME}/.ssh`;
const paths = [];
try {
const dirList = await (0, import_promises12.readdir)(path72);
for (const file of dirList) {
if (file.endsWith(".pub")) {
const s5 = await (0, import_promises12.stat)(`${path72}/${file}`);
if (s5.isFile()) {
paths.push(`${path72}/${file}`);
}
}
}
} catch {
return [];
}
return paths;
}
async function tryToRetrieveADefaultPath() {
const paths = await tryToRetrieveAllDefaultSSHKeyPaths();
const path72 = paths.pop();
return path72 ?? "";
}
function clipPublicSSHKey(value) {
return value.split(" ").slice(1).map(
(val2, i5) => dim(val2.length >= 10 && i5 === 0 ? val2.slice(0, 10) + "..." : val2)
).join(" ");
}
async function shouldPromptForNewSSHKeyAppear(keys = void 0) {
try {
const { start, stop } = spinner();
start("Loading");
const [sshKeys, err] = keys !== void 0 ? [keys, null] : await wrap2(pollSSHKeysUntilCondition(() => true));
stop();
if (err !== null) {
log(
"\n" + status.warning + " We couldn't load the ssh public keys of the account, so Wrangler doesn't know if you have your SSH keys configured right. Try again?\n"
);
return [void 0, false];
}
const defaultSSHKeyPaths = await tryToRetrieveAllDefaultSSHKeyPaths();
if (defaultSSHKeyPaths.length === 0) {
return [void 0, false];
}
let foundValidSSHKeyThatDontExist = false;
for (const defaultSSHKeyPath of defaultSSHKeyPaths) {
const file = (await (0, import_promises12.readFile)(defaultSSHKeyPath)).toString().trim();
try {
validateSSHKey(file);
} catch {
continue;
}
const key = sshKeys.find((k6) => k6.public_key?.includes(file));
if (key) {
return [key.id, false];
}
foundValidSSHKeyThatDontExist = true;
}
return [void 0, foundValidSSHKeyThatDontExist];
} catch {
return [void 0, false];
}
}
async function handleListSSHKeysCommand(_args, _config) {
startSection("SSH Keys", "", false);
const { start, stop } = spinner();
start("Loading your ssh keys");
const [sshKeys, err] = await wrap2(pollSSHKeysUntilCondition(() => true));
stop();
if (err) {
throw err;
}
if (sshKeys.length === 0) {
endSection(
"No ssh keys added to your account!",
"You can add one with\n" + brandColor("wrangler cloudchamber ssh create")
);
return;
}
for (const sshKey of sshKeys) {
newline();
updateStatus(
`${sshKey.name}
ID: ${dim(sshKey.id)}
Key: ${dim(
(sshKey.public_key ?? "").trim()
)}`,
false
);
}
endSection("");
}
async function handleCreateSSHPublicKeyCommand(args) {
startSection(
"Choose an ssh key to add",
"It will allow you to ssh into new containers"
);
await promptForSSHKey(args);
success("You are now able to ssh into your containers");
logRaw(
dim(
"\nRemember that you will have to wait for a container restart until you're able to ssh into it"
)
);
}
async function promptForSSHKey(args) {
const { username } = (0, import_os4.userInfo)();
const name2 = await inputPrompt({
question: "Name your ssh key in a recognisable format for later",
label: "name",
validate: /* @__PURE__ */ __name((value) => {
if (typeof value !== "string") {
return "unknown error";
}
if (value.length === 0) {
return "you should fill this input";
}
}, "validate"),
defaultValue: args.name ?? "",
initialValue: args.name ?? "",
helpText: `for example: 'ssh-key-${username || "me"}'`,
type: "text"
});
const defaultSSHKeyPath = await tryToRetrieveADefaultPath();
const sshKeyPath = await inputPrompt({
question: "Insert the path to your public ssh key",
label: "ssh_key",
validate: /* @__PURE__ */ __name((value) => {
if (typeof value !== "string") {
return "unknown error";
}
if (value.length === 0) {
return "you should fill this input";
}
}, "validate"),
defaultValue: args.publicKey ?? defaultSSHKeyPath,
initialValue: args.publicKey ?? defaultSSHKeyPath,
helpText: "Or insert the key directly",
type: "text"
});
const sshKey = await retrieveSSHKey(sshKeyPath);
log(
`${brandColor("Verified")} public key successfully!
` + brandColor(sshKey.split(" ").slice(0, 1).join(" ")) + " " + clipPublicSSHKey(sshKey)
);
const { start, stop } = spinner();
start("Adding your ssh key");
const [res, err] = await wrap2(
SshPublicKeysService.createSshPublicKey({
public_key: sshKey.trim(),
name: name2
})
);
stop();
if (err != null) {
throw new UserError("Error adding your public ssh key: " + err.message);
}
return res;
}
var import_promises12, import_os4, sshCommand;
var init_ssh = __esm({
"src/cloudchamber/ssh/ssh.ts"() {
init_import_meta_url();
import_promises12 = require("fs/promises");
import_os4 = require("os");
init_cli();
init_colors();
init_interactive();
init_containers_shared();
init_errors();
init_is_interactive();
init_logger();
init_cli2();
init_common();
init_wrap();
init_validate();
__name(createSSHPublicKeyOptionalYargs, "createSSHPublicKeyOptionalYargs");
__name(retrieveSSHKey, "retrieveSSHKey");
__name(sshPrompts, "sshPrompts");
sshCommand = /* @__PURE__ */ __name((yargs, scope) => {
return yargs.command(
"list",
"list the ssh keys added to your account",
(args) => args,
(args) => handleFailure(
`wrangler cloudchamber ssh list`,
async (sshArgs, config) => {
if (isNonInteractiveOrCI()) {
const sshKeys = await SshPublicKeysService.listSshPublicKeys();
logger.json(sshKeys);
return;
}
await handleListSSHKeysCommand(sshArgs, config);
},
scope
)(args)
).command(
"create",
"create an ssh key",
(args) => createSSHPublicKeyOptionalYargs(args),
(args) => handleFailure(
`wrangler cloudchamber ssh create`,
async (sshArgs, _config) => {
if (isNonInteractiveOrCI()) {
const body = checkEverythingIsSet(sshArgs, ["publicKey", "name"]);
const sshKey = await retrieveSSHKey(body.publicKey, {
json: true
});
const addedSSHKey = await SshPublicKeysService.createSshPublicKey(
{
...body,
public_key: sshKey.trim()
}
);
logger.json(addedSSHKey);
return;
}
await handleCreateSSHPublicKeyCommand(sshArgs);
},
scope
)(args)
);
}, "sshCommand");
__name(tryToRetrieveAllDefaultSSHKeyPaths, "tryToRetrieveAllDefaultSSHKeyPaths");
__name(tryToRetrieveADefaultPath, "tryToRetrieveADefaultPath");
__name(clipPublicSSHKey, "clipPublicSSHKey");
__name(shouldPromptForNewSSHKeyAppear, "shouldPromptForNewSSHKeyAppear");
__name(handleListSSHKeysCommand, "handleListSSHKeysCommand");
__name(handleCreateSSHPublicKeyCommand, "handleCreateSSHPublicKeyCommand");
__name(promptForSSHKey, "promptForSSHKey");
}
});
// src/cloudchamber/create.ts
function createCommandOptionalYargs(yargs) {
return yargs.option("image", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Image to use for your deployment"
}).option("location", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Location on Cloudflare's network where your deployment will run"
}).option("var", {
requiresArg: true,
type: "string",
array: true,
demandOption: false,
describe: "Container environment variables",
coerce: /* @__PURE__ */ __name((arg) => arg.map((a5) => a5?.toString() ?? ""), "coerce")
}).option("label", {
requiresArg: true,
type: "array",
demandOption: false,
describe: "Deployment labels",
coerce: /* @__PURE__ */ __name((arg) => arg.map((a5) => a5?.toString() ?? ""), "coerce")
}).option("all-ssh-keys", {
requiresArg: false,
type: "boolean",
demandOption: false,
describe: "To add all SSH keys configured on your account to be added to this deployment, set this option to true"
}).option("ssh-key-id", {
requiresArg: false,
type: "string",
array: true,
demandOption: false,
describe: "ID of the SSH key to add to the deployment"
}).option("instance-type", {
requiresArg: true,
choices: ["dev", "basic", "standard"],
demandOption: false,
describe: "Instance type to allocate to this deployment"
}).option("vcpu", {
requiresArg: true,
type: "number",
demandOption: false,
describe: "Number of vCPUs to allocate to this deployment."
}).option("memory", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Amount of memory (GiB, MiB...) to allocate to this deployment. Ex: 4GiB."
}).option("ipv4", {
requiresArg: false,
type: "boolean",
demandOption: false,
describe: "Include an IPv4 in the deployment"
});
}
async function createCommand2(args, config) {
const environmentVariables = collectEnvironmentVariables(
[],
config,
args.var
);
const labels = collectLabels(args.label);
if (isNonInteractiveOrCI()) {
if (config.cloudchamber.image != void 0 && args.image == void 0) {
args.image = config.cloudchamber.image;
}
if (config.cloudchamber.location != void 0 && args.location == void 0) {
args.location = config.cloudchamber.location;
}
const body = checkEverythingIsSet(args, ["image", "location"]);
const { err } = parseImageName(body.image);
if (err !== void 0) {
throw new Error(err);
}
const keysToAdd = args.allSshKeys ? (await pollSSHKeysUntilCondition(() => true)).map((key) => key.id) : [];
const useIpv4 = args.ipv4 ?? config.cloudchamber.ipv4;
const network = useIpv4 === true ? { assign_ipv4: "predefined" /* PREDEFINED */ } : { assign_ipv6: "predefined" /* PREDEFINED */ };
const memoryMib = resolveMemory(args, config.cloudchamber);
const vcpu = args.vcpu ?? config.cloudchamber.vcpu;
const instanceType = checkInstanceType(args, config.cloudchamber);
const deploymentRequest = {
image: body.image,
location: body.location,
ssh_public_key_ids: keysToAdd,
environment_variables: environmentVariables,
labels,
instance_type: instanceType,
network
};
if (instanceType === void 0) {
deploymentRequest.vcpu = vcpu;
deploymentRequest.memory_mib = memoryMib;
}
const deployment = await DeploymentsService.createDeploymentV2(deploymentRequest);
logger.json(deployment);
return;
}
await handleCreateCommand(args, config, environmentVariables, labels);
}
async function askWhichSSHKeysDoTheyWantToAdd(args, key) {
const keyItems = await pollSSHKeysUntilCondition(() => true);
const keys = keyItems.map((keyItem) => keyItem.id);
if (args.allSshKeys === true) {
return keys;
}
if (args.sshKeyId && args.sshKeyId.length) {
return key ? [...args.sshKeyId, key] : args.sshKeyId;
}
if (keys.length === 1) {
const yes = await inputPrompt({
question: `Do you want to add the SSH key ${keyItems[0].name}?`,
type: "confirm",
helpText: "You need this to SSH into the VM",
defaultValue: false,
label: ""
});
if (yes) {
return keys;
}
return [];
}
if (keys.length <= 1) {
return [];
}
const res = await inputPrompt({
question: "You have multiple SSH keys in your account, what do you want to do for this new deployment?",
label: "ssh",
defaultValue: false,
helpText: "",
type: "select",
options: [
{ label: "Add all of them", value: "all" },
{ label: "Select the keys", value: "select" },
{ label: "Don't add any SSH keys", value: "none" }
]
});
if (res === "all") {
return keys;
}
if (res === "select") {
const resKeys = await inputPrompt({
question: "Select the keys you want to add",
label: "",
defaultValue: [],
helpText: "Select one key with the 'space' key. Submit with 'enter'",
type: "multiselect",
options: keyItems.map((keyOpt) => ({
label: keyOpt.name,
value: keyOpt.id
})),
validate: /* @__PURE__ */ __name((values) => {
if (!Array.isArray(values)) {
return "unknown error";
}
if (values.length === 0) {
return "Select atleast one ssh key!";
}
return;
}, "validate")
});
return resKeys;
}
return [];
}
async function handleCreateCommand(args, config, environmentVariables, labels) {
startSection("Create a Cloudflare container", "Step 1 of 2");
const sshKeyID = await sshPrompts(args);
const givenImage = args.image ?? config.cloudchamber.image;
const image = await processArgument({ image: givenImage }, "image", {
question: whichImageQuestion,
label: "image",
validate: /* @__PURE__ */ __name((value) => {
if (typeof value !== "string") {
return "Unknown error";
}
if (value.length === 0) {
value = defaultContainerImage;
}
const { err: err2 } = parseImageName(value);
return err2;
}, "validate"),
defaultValue: givenImage ?? defaultContainerImage,
helpText: 'NAME:TAG ("latest" tag is not allowed)',
type: "text"
});
const location = await getLocation2({
location: args.location ?? config.cloudchamber.location
});
const keys = await askWhichSSHKeysDoTheyWantToAdd(args, sshKeyID);
const network = await getNetworkInput({
ipv4: args.ipv4 ?? config.cloudchamber.ipv4
});
const selectedEnvironmentVariables = await promptForEnvironmentVariables(
environmentVariables,
[],
false
);
const selectedLabels = await promptForLabels(labels, [], false);
const account = await loadAccount();
const memoryMib = resolveMemory(args, config.cloudchamber) ?? account.defaults.memory_mib ?? Math.round(
parseByteSize(account.defaults.memory ?? "2000MiB", 1024) / (1024 * 1024)
);
const vcpu = args.vcpu ?? config.cloudchamber.vcpu ?? account.defaults.vcpus;
const instanceType = await promptForInstanceType(true);
renderDeploymentConfiguration("create", {
image,
location,
network,
instanceType,
vcpu,
memoryMib,
environmentVariables: selectedEnvironmentVariables,
labels: selectedLabels,
env: args.env
});
const yes = await inputPrompt({
type: "confirm",
question: "Proceed?",
label: ""
});
if (!yes) {
cancel("Not creating the container");
return;
}
const { start, stop } = spinner();
start("Creating your container", "your container will be created shortly");
const deploymentRequest = {
image,
location,
ssh_public_key_ids: keys,
environment_variables: environmentVariables,
labels,
instance_type: instanceType,
vcpu: void 0,
memory_mib: void 0,
network
};
if (instanceType === void 0) {
deploymentRequest.vcpu = vcpu;
deploymentRequest.memory_mib = memoryMib;
}
const [deployment, err] = await wrap2(
DeploymentsService.createDeploymentV2(deploymentRequest)
);
if (err) {
stop();
renderDeploymentMutationError(account, err);
return;
}
stop();
updateStatus("Created deployment", false);
log(`${brandColor("id")} ${dim(deployment.id)}
`);
endSection("Creating a placement for your container");
startSection("Create a Cloudflare container", "Step 2 of 2");
await waitForPlacement(deployment);
}
var defaultContainerImage, whichImageQuestion;
var init_create2 = __esm({
"src/cloudchamber/create.ts"() {
init_import_meta_url();
init_cli();
init_args();
init_colors();
init_interactive();
init_containers_shared();
init_is_interactive();
init_logger();
init_parse();
init_cli2();
init_locations2();
init_common();
init_wrap();
init_instance_type();
init_locations();
init_network();
init_ssh();
defaultContainerImage = "docker.io/cloudflare/hello-world:1.0";
__name(createCommandOptionalYargs, "createCommandOptionalYargs");
__name(createCommand2, "createCommand");
__name(askWhichSSHKeysDoTheyWantToAdd, "askWhichSSHKeysDoTheyWantToAdd");
__name(handleCreateCommand, "handleCreateCommand");
whichImageQuestion = "Which image should we use for your container?";
}
});
// src/utils/render-labelled-values.ts
function formatLabelledValues(view, {
formatLabel = /* @__PURE__ */ __name((label) => white(label + ":"), "formatLabel"),
formatValue = /* @__PURE__ */ __name((value) => gray(value), "formatValue"),
spacerCount = 2,
indentationCount = 0,
valuesAlignmentColumn: valuesAlignment = Math.max(
...Object.keys(view).map((label) => stripAnsi2(formatLabel(label)).length)
),
lineSeparator = "\n",
labelJustification = "left"
} = {}) {
const labelLengthsWithoutANSI = Object.keys(view).map(
(label) => stripAnsi2(formatLabel(label)).length
);
const formattedLines = Object.entries(view).map(([label, value], i5) => {
const indentation = indentationCount ? " ".repeat(indentationCount) : "";
const labelAlignment = labelJustification === "left" ? "" : " ".repeat(valuesAlignment - labelLengthsWithoutANSI[i5]);
const formattedAndAlignedLabel = labelAlignment + formatLabel(label);
const formattedAndAlignedMultilineValue = formatValue(value).split("\n").map((line, lineNo) => {
const prefixSpacing = " ".repeat(
lineNo === 0 ? valuesAlignment + spacerCount - labelLengthsWithoutANSI[i5] - labelAlignment.length : valuesAlignment + spacerCount + indentationCount
);
return prefixSpacing + line;
}).join("\n");
return indentation + formattedAndAlignedLabel + formattedAndAlignedMultilineValue;
});
const output = formattedLines.join(lineSeparator);
return collapseWhiteSpaceLines(output);
}
function collapseWhiteSpaceLines(input) {
return input.replaceAll(/^\s+$/gm, "");
}
var init_render_labelled_values = __esm({
"src/utils/render-labelled-values.ts"() {
init_import_meta_url();
init_colors();
init_strip_ansi();
__name(formatLabelledValues, "formatLabelledValues");
__name(collapseWhiteSpaceLines, "collapseWhiteSpaceLines");
}
});
// src/cloudchamber/curl.ts
function yargsCurl(args) {
return args.positional("path", { type: "string", default: "/" }).option("header", {
type: "array",
alias: "H",
describe: "Add headers in the form of --header <name>:<value>"
}).option("data", {
type: "string",
describe: "Add a JSON body to the request",
alias: "d"
}).option("data-deprecated", {
type: "string",
hidden: true,
alias: "D"
}).option("method", {
type: "string",
alias: "X",
default: "GET"
}).option("silent", {
describe: "Only output response",
type: "boolean",
alias: "s"
}).option("verbose", {
describe: "Print everything, like request id, or headers",
type: "boolean",
alias: "v"
}).option("use-stdin", {
describe: "Equivalent of using --data-binary @- in curl",
type: "boolean",
alias: "stdin"
});
}
async function curlCommand(args, config) {
await requestFromCmd(args, config);
}
async function read(stream2) {
const chunks = [];
for await (const chunk of stream2) {
chunks.push(chunk);
}
return Buffer.concat(chunks).toString("utf8");
}
async function requestFromCmd(args, _config) {
const requestId = `wrangler-${(0, import_crypto2.randomUUID)()}`;
if (args.verbose && !args.silent) {
logRaw(bold(brandColor("Request ID: " + requestId)));
}
if (args.useStdin) {
args.data = await read(process.stdin);
}
try {
const headers = (args.header ?? []).reduce(
(prev, now) => ({
...prev,
[now.toString().split(":")[0].trim()]: now.toString().split(":")[1].trim()
}),
{ "coordinator-request-id": requestId }
);
const data = args.data ?? args.dataDeprecated;
const res = await request(OpenAPI, {
url: args.path,
method: args.method,
body: data ? JSON.parse(data) : void 0,
mediaType: "application/json",
headers
});
if (args.silent) {
logRaw(
JSON.stringify(
!args.verbose ? res : {
res,
headers,
request_id: requestId
},
null,
4
)
);
} else {
if (args.verbose) {
logRaw(cyanBright(">> Headers"));
logRaw(
formatLabelledValues(headers, {
indentationCount: 4,
formatLabel: /* @__PURE__ */ __name(function(label) {
return yellow(label + ":");
}, "formatLabel"),
formatValue: yellow
})
);
logRaw(cyanBright(">> Body"));
}
const text = JSON.stringify(res, null, 4);
logRaw(text);
}
return;
} catch (error2) {
if (error2 instanceof ApiError) {
logRaw(
JSON.stringify({
request: error2.request,
status: error2.status,
statusText: error2.statusText,
body: error2.body
})
);
} else {
logRaw(String(error2));
}
}
}
var import_crypto2;
var init_curl = __esm({
"src/cloudchamber/curl.ts"() {
init_import_meta_url();
import_crypto2 = require("crypto");
init_cli();
init_colors();
init_containers_shared();
init_request();
init_render_labelled_values();
__name(yargsCurl, "yargsCurl");
__name(curlCommand, "curlCommand");
__name(read, "read");
__name(requestFromCmd, "requestFromCmd");
}
});
// src/cloudchamber/cli/deployments.ts
function ipv6(placement) {
if (!placement) {
return yellow("no ipv6 yet");
}
if (!placement.status["ipv6Address"]) {
return yellow("no ipv6 yet");
}
return placement.status["ipv6Address"];
}
function uptime(placement) {
if (!placement) {
return yellow("inactive");
}
const ms = Date.now() - new Date(placement.created_at).getTime();
const days = Math.floor(ms / 864e5);
const hours = new Date(ms).getUTCHours();
const minutes = new Date(ms).getUTCMinutes();
const seconds = new Date(ms).getUTCSeconds();
const uptimeString = `${days ? days + "d " : ""}${hours ? hours + "h " : ""}${minutes ? minutes + "m " : ""}${seconds}s`;
return uptimeString;
}
function version2(deployment) {
if (!deployment.current_placement) {
return "";
}
if (deployment.current_placement.deployment_version !== deployment.version) {
return ` (${yellow(
`version ${deployment.current_placement.deployment_version}`
)})`;
}
return ` (version ${deployment.version})`;
}
function health(placement) {
if (!placement) {
return statusToColored();
}
if (!placement.status["health"]) {
return statusToColored();
}
return statusToColored(placement.status["health"]);
}
async function loadDeployments(deploymentIdPrefix, deploymentsParams) {
const { start, stop } = spinner();
start("Loading deployments");
const [deploymentsResponse, err] = await wrap2(
DeploymentsService.listDeploymentsV2(
void 0,
deploymentsParams?.location,
deploymentsParams?.image,
deploymentsParams?.state,
deploymentsParams?.state,
deploymentsParams?.labels
)
);
stop();
if (err) {
throw new UserError(
"There has been an error while loading your deployments: \n " + err.message
);
}
const deployments = deploymentsResponse.filter(
(d6) => d6.id.startsWith(deploymentIdPrefix ?? "")
);
if (deployments.length === 0 && !deploymentIdPrefix) {
endSection(
"you don't have any deployments in your account",
"You can create one with\n " + brandColor("wrangler cloudchamber create")
);
(0, import_process3.exit)(0);
}
if (deployments.length === 0 && deploymentIdPrefix) {
endSection(
"you don't have any deployments that match the id " + deploymentIdPrefix
);
(0, import_process3.exit)(0);
}
return deployments;
}
async function listDeploymentsAndChoose(deployments, args = {}) {
const ips = /* @__PURE__ */ __name((d6) => {
const ipsList = [];
if (d6.network?.ipv4 !== void 0) {
ipsList.push(`IPV4: ${dim(d6.network.ipv4)}`);
}
ipsList.push(`IPV6: ${dim(ipv6(d6.current_placement))}`);
return ipsList;
}, "ips");
const deployment = await processArgument(args, "deploymentId", {
type: "list",
question: "Deployments",
helpText: "Choose one by pressing the enter/return key",
options: deployments.map((d6) => ({
label: "Deployment " + d6.id,
value: d6.id,
details: [
`ID: ${dim(`${d6.id}`)}`,
`Uptime: ${dim(`${uptime(d6.current_placement)}`)}`,
`Version: ${dim(`${d6.version}`)}`,
`Location: ${dim(`${idToLocationName(d6.location.name)}`)}`,
`Image: ${dim(d6.image)}`,
...ips(d6),
`Current Placement${version2(d6)}: ${health(d6.current_placement)}`
]
})),
label: "deployment"
});
return deployments.find((d6) => d6.id === deployment);
}
async function pickDeployment(deploymentIdPrefix) {
const deployments = await loadDeployments(deploymentIdPrefix);
const deploymentId = deployments.length === 1 ? deployments[0].id : void 0;
const deployment = await listDeploymentsAndChoose(deployments, {
deploymentId
});
if (!deployment) {
cancel("Cancelling deployment selection");
(0, import_process3.exit)(0);
}
return deployment;
}
function logDeployment(deployment) {
log(`${brandColor("image")} ${dim(deployment.image)}`);
log(
`${brandColor("location")} ${dim(idToLocationName(deployment.location.name))}`
);
log(`${brandColor("version")} ${dim(`${deployment.version}`)}`);
newline();
}
var import_process3;
var init_deployments = __esm({
"src/cloudchamber/cli/deployments.ts"() {
init_import_meta_url();
import_process3 = require("process");
init_cli();
init_args();
init_colors();
init_interactive();
init_containers_shared();
init_errors();
init_wrap();
init_locations();
init_util();
__name(ipv6, "ipv6");
__name(uptime, "uptime");
__name(version2, "version");
__name(health, "health");
__name(loadDeployments, "loadDeployments");
__name(listDeploymentsAndChoose, "listDeploymentsAndChoose");
__name(pickDeployment, "pickDeployment");
__name(logDeployment, "logDeployment");
}
});
// src/cloudchamber/delete.ts
function deleteCommandOptionalYargs(yargs) {
return yargs.positional("deploymentId", {
type: "string",
demandOption: false,
describe: "deployment you want to delete"
});
}
async function deleteCommand2(deleteArgs, config) {
if (isNonInteractiveOrCI()) {
if (!deleteArgs.deploymentId) {
throw new Error(
"there needs to be a deploymentId when you can't interact with the wrangler cli"
);
}
const deployment = await DeploymentsService.deleteDeploymentV2(
deleteArgs.deploymentId
);
logger.json(deployment);
return;
}
await handleDeleteCommand(deleteArgs, config);
}
async function handleDeleteCommand(args, _config) {
startSection("Delete your deployment");
const deployment = await pickDeployment(args.deploymentId);
logDeployment(deployment);
const yes = await inputPrompt({
question: "Are you sure that you want to delete this deployment?",
type: "confirm",
label: ""
});
if (!yes) {
cancel("The operation has been cancelled");
return;
}
const [, err] = await wrap2(
DeploymentsService.deleteDeploymentV2(deployment.id)
);
if (err) {
throw new UserError(
`There has been an internal error deleting your deployment.
${err.message}`
);
}
endSection("Your container has been deleted");
}
var init_delete = __esm({
"src/cloudchamber/delete.ts"() {
init_import_meta_url();
init_cli();
init_interactive();
init_containers_shared();
init_errors();
init_is_interactive();
init_logger();
init_deployments();
init_wrap();
__name(deleteCommandOptionalYargs, "deleteCommandOptionalYargs");
__name(deleteCommand2, "deleteCommand");
__name(handleDeleteCommand, "handleDeleteCommand");
}
});
// src/cloudchamber/images/registries.ts
function configureImageRegistryOptionalYargs(yargs) {
return yargs.option("domain", {
description: "Domain of your registry. Don't include the proto part of the URL, like 'http://'",
type: "string"
}).option("public", {
description: "If the registry is public and you don't want credentials configured, set this to true",
type: "boolean"
});
}
function removeImageRegistryYargs(yargs) {
return yargs.positional("domain", {
type: "string",
demandOption: true
});
}
async function handleListImageRegistriesCommand(_args, _config) {
startSection("Registries", "", false);
const [registries, err] = await wrap2(
promiseSpinner(pollRegistriesUntilCondition(() => true))
);
if (err) {
throw err;
}
if (registries.length === 0) {
endSection(
"No registries added to your account!",
"You can add one with\n" + brandColor("wrangler cloudchamber registry configure")
);
return;
}
for (const registry of registries) {
newline();
updateStatus(
`${registry.domain}
public_key: ${dim(
(registry.public_key ?? "").trim()
)}`,
false
);
}
endSection("");
}
async function handleConfigureImageRegistryCommand(args, _config) {
startSection("Configure a Docker registry in Cloudflare");
const domain2 = await processArgument({ domain: args.domain }, "domain", {
type: "text",
question: "What is the domain of your registry?",
validate: /* @__PURE__ */ __name((text) => {
const t7 = text?.toString();
if (t7?.includes("://")) {
return "a proto like https:// shouldn't be included";
}
}, "validate"),
label: "domain",
defaultValue: "",
helpText: "example.com, example-with-port:8080. Remember to not include https!"
});
const isPublic = await processArgument({ public: args.public }, "public", {
type: "confirm",
question: "Is the domain public?",
label: "is public",
helpText: "if the domain is not owned by you or you want it to be public, mark as yes"
});
const [registry, err] = await wrap2(
promiseSpinner(
ImageRegistriesService.createImageRegistry({
domain: domain2,
is_public: isPublic
})
)
);
if (err instanceof ApiError) {
const { error: errString } = err.body;
switch (errString) {
case ImageRegistryAlreadyExistsError.error.IMAGE_REGISTRY_ALREADY_EXISTS:
throw new UserError("The domain already exists!");
case ImageRegistryNotAllowedError.error.IMAGE_REGISTRY_NOT_ALLOWED:
throw new UserError("This domain is not allowed!");
default:
throw new UserError(
"An unexpected error happened, please try again or send us the error for troubleshooting\n" + errString
);
}
}
if (err) {
throw new UserError(
"There has been an internal error: " + JSON.stringify(err)
);
}
endSection(
`Docker registry configured`,
registry?.public_key && "set the following public key in the registry if necessary:\n" + registry?.public_key
);
}
var registriesCommand;
var init_registries = __esm({
"src/cloudchamber/images/registries.ts"() {
init_import_meta_url();
init_cli();
init_args();
init_colors();
init_containers_shared();
init_errors();
init_is_interactive();
init_logger();
init_cli2();
init_common();
init_wrap();
__name(configureImageRegistryOptionalYargs, "configureImageRegistryOptionalYargs");
registriesCommand = /* @__PURE__ */ __name((yargs, scope) => {
return yargs.command(
"configure",
"Configure Cloudchamber to pull from specific registries",
(args) => configureImageRegistryOptionalYargs(args),
(args) => handleFailure(
`wrangler cloudchamber registries configure`,
async (imageArgs, config) => {
if (isNonInteractiveOrCI()) {
const body = checkEverythingIsSet(imageArgs, [
"domain",
"public"
]);
const registry = await ImageRegistriesService.createImageRegistry(
{
domain: body.domain,
is_public: body.public
}
);
logger.log(JSON.stringify(registry, null, 4));
return;
}
await handleConfigureImageRegistryCommand(args, config);
},
scope
)(args)
).command(
"credentials [domain]",
"get a temporary password for a specific domain",
(args) => args.positional("domain", {
type: "string",
demandOption: true
}).option("expiration-minutes", {
type: "number",
default: 15
}).option("push", {
type: "boolean",
description: "If you want these credentials to be able to push"
}).option("pull", {
type: "boolean",
description: "If you want these credentials to be able to pull"
}),
(args) => {
args.json = true;
return handleFailure(
`wrangler cloudchamber registries credentials`,
async (imageArgs, _config) => {
if (!imageArgs.pull && !imageArgs.push) {
throw new UserError(
"You have to specify either --push or --pull in the command."
);
}
const credentials = await ImageRegistriesService.generateImageRegistryCredentials(
imageArgs.domain,
{
expiration_minutes: imageArgs.expirationMinutes,
permissions: [
...imageArgs.push ? ["push"] : [],
...imageArgs.pull ? ["pull"] : []
]
}
);
logger.log(credentials.password);
},
scope
)(args);
}
).command(
"remove [domain]",
"removes the registry at the given domain",
(args) => removeImageRegistryYargs(args),
(args) => {
args.json = true;
return handleFailure(
`wrangler cloudchamber registries remove`,
async (imageArgs, _config) => {
const registry = await ImageRegistriesService.deleteImageRegistry(
imageArgs.domain
);
logger.log(JSON.stringify(registry, null, 4));
},
scope
)(args);
}
).command(
"list",
"list registries configured for this account",
(args) => args,
(args) => handleFailure(
`wrangler cloudchamber registries list`,
async (_4, config) => {
if (isNonInteractiveOrCI()) {
const registries = await ImageRegistriesService.listImageRegistries();
logger.log(JSON.stringify(registries, null, 4));
return;
}
await handleListImageRegistriesCommand(args, config);
},
scope
)(args)
);
}, "registriesCommand");
__name(removeImageRegistryYargs, "removeImageRegistryYargs");
__name(handleListImageRegistriesCommand, "handleListImageRegistriesCommand");
__name(handleConfigureImageRegistryCommand, "handleConfigureImageRegistryCommand");
}
});
// src/cloudchamber/list.ts
function listDeploymentsYargs(args) {
return args.option("location", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Filter deployments by location"
}).option("image", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Filter deployments by image"
}).option("state", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Filter deployments by deployment state"
}).option("ipv4", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "Filter deployments by ipv4 address"
}).option("label", {
requiresArg: true,
type: "array",
demandOption: false,
describe: "Filter deployments by labels",
coerce: /* @__PURE__ */ __name((arg) => arg.map((a5) => a5?.toString() ?? ""), "coerce")
}).positional("deploymentIdPrefix", {
describe: "Optional deploymentId to filter deployments\nThis means that 'list' will only showcase deployments that contain this ID prefix",
type: "string"
});
}
async function listCommand2(deploymentArgs, config) {
const prefix = deploymentArgs.deploymentIdPrefix ?? "";
if (isNonInteractiveOrCI()) {
const deployments = (await DeploymentsService.listDeploymentsV2(
void 0,
deploymentArgs.location,
deploymentArgs.image,
deploymentArgs.state,
deploymentArgs.ipv4,
deploymentArgs.label
)).filter((deployment) => deployment.id.startsWith(prefix));
if (deployments.length === 1) {
const placements = await PlacementsService.listPlacements(
deployments[0].id
);
logger.json({
...deployments[0],
placements
});
return;
}
logger.json(deployments);
return;
}
await listCommandHandle2(prefix, deploymentArgs, config);
}
function eventMessage(event, lastEvent) {
let { message } = event;
message = capitalize(message);
const name2 = event.name;
const health2 = event.statusChange["health"];
if (health2 === "failed") {
message = `${bgRed(" X ")} ${dim(message)}`;
} else if (lastEvent && name2 === "VMStopped") {
message = `${yellow(message)}`;
} else if (lastEvent && name2 === "VMStarted" || name2 === "SSHStarted") {
message = `${green(message)}`;
} else if (lastEvent) {
message = `${brandColor(message)}`;
} else {
message = dim(message);
}
return `${message} (${event.time})`;
}
var listCommandHandle2;
var init_list2 = __esm({
"src/cloudchamber/list.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_interactive();
init_containers_shared();
init_is_interactive();
init_logger();
init_deployments();
init_util();
init_common();
__name(listDeploymentsYargs, "listDeploymentsYargs");
__name(listCommand2, "listCommand");
__name(eventMessage, "eventMessage");
listCommandHandle2 = /* @__PURE__ */ __name(async (deploymentIdPrefix, args, _config) => {
const keepListIter = true;
while (keepListIter) {
logRaw(gray(shapes.bar));
const deployments = await loadDeployments(deploymentIdPrefix, args);
const deployment = await listDeploymentsAndChoose(deployments);
const placementToOptions = /* @__PURE__ */ __name((p6) => {
return {
label: `Placement ${p6.id.slice(0, 6)} (${p6.created_at})`,
details: [
`ID: ${dim(p6.id)}`,
`Version: ${dim(`${p6.deployment_version}`)}`,
`Status: ${statusToColored(p6.status["health"])}`,
`${bgCyan(white(`Events`))}`,
...p6.events.map(
(event, i5) => space(1) + eventMessage(event, i5 === p6.events.length - 1)
)
],
value: p6.id
};
}, "placementToOptions");
const loadPlacements = /* @__PURE__ */ __name(() => {
return PlacementsService.listPlacements(deployment.id);
}, "loadPlacements");
const placements = await promiseSpinner(loadPlacements(), {
message: "Loading placements"
});
const { start, stop } = spinner();
let refresh = false;
await inputPrompt({
type: "list",
question: "Placements",
helpText: "Hint: Press R to refresh! Or press return to go back",
options: placements.map(placementToOptions),
label: "going back",
onRefresh: /* @__PURE__ */ __name(async () => {
start("Refreshing placements");
const options = (await loadPlacements()).map(placementToOptions);
if (refresh) {
return [];
}
stop();
if (options.length) {
options[0].label += ", last refresh: " + (/* @__PURE__ */ new Date()).toLocaleString();
}
return options;
}, "onRefresh")
});
refresh = true;
stop();
}
}, "listCommandHandle");
}
});
// src/cloudchamber/modify.ts
function modifyCommandOptionalYargs(yargs) {
return yargs.positional("deploymentId", {
type: "string",
demandOption: false,
describe: "The deployment you want to modify"
}).option("var", {
requiresArg: true,
type: "array",
demandOption: false,
describe: "Container environment variables",
coerce: /* @__PURE__ */ __name((arg) => arg.map((a5) => a5?.toString() ?? ""), "coerce")
}).option("label", {
requiresArg: true,
type: "array",
demandOption: false,
describe: "Deployment labels",
coerce: /* @__PURE__ */ __name((arg) => arg.map((a5) => a5?.toString() ?? ""), "coerce")
}).option("ssh-public-key-id", {
requiresArg: true,
type: "string",
array: true,
demandOption: false,
describe: "Public SSH key IDs to include in this container. You can add one to your account with `wrangler cloudchamber ssh create"
}).option("image", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "The new image that the deployment will have from now on"
}).option("location", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "The new location that the deployment will have from now on"
}).option("instance-type", {
requiresArg: true,
choices: ["dev", "basic", "standard"],
demandOption: false,
describe: "The new instance type that the deployment will have from now on"
}).option("vcpu", {
requiresArg: true,
type: "number",
demandOption: false,
describe: "The new vcpu that the deployment will have from now on"
}).option("memory", {
requiresArg: true,
type: "string",
demandOption: false,
describe: "The new memory that the deployment will have from now on"
});
}
async function modifyCommand(modifyArgs, config) {
if (isNonInteractiveOrCI()) {
if (!modifyArgs.deploymentId) {
throw new Error(
"there needs to be a deploymentId when you can't interact with the wrangler cli"
);
}
const environmentVariables = collectEnvironmentVariables(
[],
config,
modifyArgs.var
);
const labels = collectLabels(modifyArgs.label);
const memoryMib = resolveMemory(modifyArgs, config.cloudchamber);
const vcpu = modifyArgs.vcpu ?? config.cloudchamber.vcpu;
const instanceType = checkInstanceType(modifyArgs, config.cloudchamber);
const modifyRequest = {
image: modifyArgs.image ?? config.cloudchamber.image,
location: modifyArgs.location ?? config.cloudchamber.location,
environment_variables: environmentVariables,
labels,
ssh_public_key_ids: modifyArgs.sshPublicKeyId,
instance_type: instanceType,
vcpu: void 0,
memory_mib: void 0
};
if (instanceType === void 0) {
modifyRequest.vcpu = vcpu;
modifyRequest.memory_mib = memoryMib;
}
const deployment = await DeploymentsService.modifyDeploymentV2(
modifyArgs.deploymentId,
modifyRequest
);
logger.json(deployment);
return;
}
await handleModifyCommand(modifyArgs, config);
}
async function handleSSH(args, config, deployment) {
if (args.sshPublicKeyId !== void 0) {
return args.sshPublicKeyId;
}
await sshPrompts(args);
const keys = await pollSSHKeysUntilCondition(() => true);
let keysToAdd = [...deployment.ssh_public_key_ids ?? []];
const yes = await inputPrompt({
type: "confirm",
question: "Do you want to modify existing ssh keys from the deployment?",
label: "",
defaultValue: false
});
if (!yes) {
return void 0;
}
if ((deployment.ssh_public_key_ids?.length || 0) > 0) {
const keysSelected = await inputPrompt({
type: "multiselect",
question: "Select the keys you want to remove from the deployment",
helpText: "You can select pressing 'space'. Submit with 'enter'",
options: keys.filter((k6) => deployment.ssh_public_key_ids?.includes(k6.id)).map((key) => ({ label: key.name, value: key.id })),
label: "removing"
});
keysToAdd = keys.filter((key) => deployment.ssh_public_key_ids?.includes(key.id)).filter((key) => !keysSelected.includes(key.id)).map((k6) => k6.id);
}
const addKeysOptions = keys.filter((k6) => !deployment.ssh_public_key_ids?.includes(k6.id)).map((key) => ({ label: key.name, value: key.id }));
if (addKeysOptions.length > 0) {
const newKeys = await inputPrompt({
type: "multiselect",
question: "Select the keys you want to add to the deployment",
options: addKeysOptions,
label: "adding",
defaultValue: []
});
keysToAdd = [...newKeys, ...keysToAdd];
}
return keysToAdd;
}
async function handleModifyCommand(args, config) {
startSection("Modify deployment");
const deployment = await pickDeployment(args.deploymentId);
const keys = await handleSSH(args, config, deployment);
const givenImage = args.image ?? config.cloudchamber.image;
const image = await processArgument({ image: givenImage }, "image", {
question: modifyImageQuestion,
label: "",
validate: /* @__PURE__ */ __name((value) => {
if (typeof value !== "string") {
return "Unknown error";
}
const { err: err2 } = parseImageName(value);
return err2;
}, "validate"),
defaultValue: givenImage ?? deployment.image,
initialValue: givenImage ?? deployment.image,
helpText: "press Return to leave unchanged",
type: "text"
});
const locationPick = await getLocation2(
{ location: args.location ?? config.cloudchamber.location },
{ skipLocation: true }
);
const location = locationPick === "Skip" ? void 0 : locationPick;
const environmentVariables = collectEnvironmentVariables(
deployment.environment_variables,
config,
args.var
);
const selectedEnvironmentVariables = await promptForEnvironmentVariables(
environmentVariables,
(deployment.environment_variables ?? []).map((v7) => v7.name),
true
);
const labels = collectLabels(args.label);
const selectedLabels = await promptForLabels(
labels,
(deployment.labels ?? []).map((v7) => v7.name),
true
);
const memoryMib = resolveMemory(args, config.cloudchamber);
const instanceType = await promptForInstanceType(true);
renderDeploymentConfiguration("modify", {
image,
location: location ?? deployment.location.name,
instanceType,
vcpu: args.vcpu ?? config.cloudchamber.vcpu ?? deployment.vcpu,
memoryMib: memoryMib ?? deployment.memory_mib,
env: args.env,
environmentVariables: selectedEnvironmentVariables !== void 0 ? selectedEnvironmentVariables : deployment.environment_variables,
// show the existing environment variables if any
labels: selectedLabels !== void 0 ? selectedLabels : deployment.labels
// show the existing labels if any
});
const yesOrNo = await inputPrompt({
question: "Modify the deployment?",
label: "",
type: "confirm"
});
if (!yesOrNo) {
cancel("Not modifying the deployment");
return;
}
const { start, stop } = spinner();
start(
"Modifying your container",
"shortly your container will be modified to a new version"
);
const modifyRequest = {
image,
location,
ssh_public_key_ids: keys,
environment_variables: selectedEnvironmentVariables,
labels: selectedLabels,
instance_type: instanceType
};
if (instanceType === void 0) {
modifyRequest.vcpu = args.vcpu ?? config.cloudchamber.vcpu;
modifyRequest.memory_mib = memoryMib;
}
const [newDeployment, err] = await wrap2(
DeploymentsService.modifyDeploymentV2(deployment.id, modifyRequest)
);
stop();
if (err) {
renderDeploymentMutationError(await loadAccount(), err);
return;
}
await waitForPlacement(newDeployment);
}
var modifyImageQuestion;
var init_modify = __esm({
"src/cloudchamber/modify.ts"() {
init_import_meta_url();
init_cli();
init_args();
init_interactive();
init_containers_shared();
init_is_interactive();
init_logger();
init_cli2();
init_deployments();
init_locations2();
init_common();
init_wrap();
init_instance_type();
init_locations();
init_ssh();
__name(modifyCommandOptionalYargs, "modifyCommandOptionalYargs");
__name(modifyCommand, "modifyCommand");
__name(handleSSH, "handleSSH");
__name(handleModifyCommand, "handleModifyCommand");
modifyImageQuestion = "URL of the image to use in your deployment";
}
});
// src/cloudchamber/index.ts
function internalCommands(args) {
try {
const cloudchamberInternalRequireEntry = require("./internal/index");
return cloudchamberInternalRequireEntry.internalCommands(args);
} catch {
return args;
}
}
var cloudchamber;
var init_cloudchamber = __esm({
"src/cloudchamber/index.ts"() {
init_import_meta_url();
init_apply();
init_build2();
init_common();
init_create2();
init_curl();
init_delete();
init_images2();
init_registries();
init_list2();
init_modify();
init_ssh();
__name(internalCommands, "internalCommands");
cloudchamber = /* @__PURE__ */ __name((yargs, subHelp) => {
yargs = internalCommands(yargs);
return yargs.command(
"delete [deploymentId]",
"Delete an existing deployment that is running in the Cloudflare edge",
(args) => deleteCommandOptionalYargs(args),
(args) => handleFailure(
`wrangler cloudchamber delete`,
deleteCommand2,
cloudchamberScope
)(args)
).command(
"create",
"Create a new deployment",
(args) => createCommandOptionalYargs(args),
(args) => handleFailure(
`wrangler cloudchamber create`,
createCommand2,
cloudchamberScope
)(args)
).command(
"list [deploymentIdPrefix]",
"List and view status of deployments",
(args) => listDeploymentsYargs(args),
(args) => handleFailure(
`wrangler cloudchamber list`,
listCommand2,
cloudchamberScope
)(args)
).command(
"modify [deploymentId]",
"Modify an existing deployment",
(args) => modifyCommandOptionalYargs(args),
(args) => handleFailure(
`wrangler cloudchamber modify`,
modifyCommand,
cloudchamberScope
)(args)
).command(
"ssh",
"Manage the ssh keys of your account",
(args) => sshCommand(args, cloudchamberScope).command(subHelp)
).command(
"registries",
"Configure registries via Cloudchamber",
(args) => registriesCommand(args, cloudchamberScope).command(subHelp)
).command(
"curl <path>",
"Send a request to an arbitrary Cloudchamber endpoint",
(args) => yargsCurl(args),
(args) => handleFailure(
`wrangler cloudchamber curl`,
curlCommand,
cloudchamberScope
)(args)
).command(
"apply",
"Apply the changes in the container applications to deploy",
(args) => applyCommandOptionalYargs(args),
(args) => handleFailure(
`wrangler cloudchamber apply`,
applyCommand,
cloudchamberScope
)(args)
).command(
"build [PATH]",
"Build a container image",
(args) => buildYargs(args),
(args) => handleFailure(
`wrangler cloudchamber build`,
buildCommand,
cloudchamberScope
)(args)
).command(
"push [TAG]",
"Push a tagged image to a Cloudflare managed registry",
(args) => pushYargs(args),
(args) => handleFailure(
`wrangler cloudchamber push`,
pushCommand,
cloudchamberScope
)(args)
).command(
"images",
"Perform operations on images in your Cloudchamber registry",
(args) => imagesCommand(args, cloudchamberScope).command(subHelp)
);
}, "cloudchamber");
}
});
// ../../node_modules/.pnpm/dotenv@16.3.1/node_modules/dotenv/package.json
var require_package = __commonJS({
"../../node_modules/.pnpm/dotenv@16.3.1/node_modules/dotenv/package.json"(exports2, module3) {
module3.exports = {
name: "dotenv",
version: "16.3.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",
"lint-readme": "standard-markdown",
pretest: "npm run lint && npm run dts-check",
test: "tap tests/*.js --100 -Rspec",
prerelease: "npm test",
release: "standard-version"
},
repository: {
type: "git",
url: "git://github.com/motdotla/dotenv.git"
},
funding: "https://github.com/motdotla/dotenv?sponsor=1",
keywords: [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
readmeFilename: "README.md",
license: "BSD-2-Clause",
devDependencies: {
"@definitelytyped/dtslint": "^0.0.133",
"@types/node": "^18.11.3",
decache: "^4.6.1",
sinon: "^14.0.1",
standard: "^17.0.0",
"standard-markdown": "^7.1.0",
"standard-version": "^9.5.0",
tap: "^16.3.0",
tar: "^6.1.11",
typescript: "^4.8.4"
},
engines: {
node: ">=12"
},
browser: {
fs: false
}
};
}
});
// ../../node_modules/.pnpm/dotenv@16.3.1/node_modules/dotenv/lib/main.js
var require_main = __commonJS({
"../../node_modules/.pnpm/dotenv@16.3.1/node_modules/dotenv/lib/main.js"(exports2, module3) {
init_import_meta_url();
var fs24 = require("fs");
var path72 = require("path");
var os12 = require("os");
var crypto8 = require("crypto");
var packageJson = require_package();
var version5 = packageJson.version;
var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
function parse7(src) {
const obj = {};
let lines = src.toString();
lines = lines.replace(/\r\n?/mg, "\n");
let match2;
while ((match2 = LINE.exec(lines)) != null) {
const key = match2[1];
let value = match2[2] || "";
value = value.trim();
const maybeQuote = value[0];
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
if (maybeQuote === '"') {
value = value.replace(/\\n/g, "\n");
value = value.replace(/\\r/g, "\r");
}
obj[key] = value;
}
return obj;
}
__name(parse7, "parse");
function _parseVault(options) {
const vaultPath = _vaultPath(options);
const result = DotenvModule.configDotenv({ path: vaultPath });
if (!result.parsed) {
throw new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
}
const keys = _dotenvKey(options).split(",");
const length = keys.length;
let decrypted;
for (let i5 = 0; i5 < length; i5++) {
try {
const key = keys[i5].trim();
const attrs = _instructions(result, key);
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
break;
} catch (error2) {
if (i5 + 1 >= length) {
throw error2;
}
}
}
return DotenvModule.parse(decrypted);
}
__name(_parseVault, "_parseVault");
function _log2(message) {
console.log(`[dotenv@${version5}][INFO] ${message}`);
}
__name(_log2, "_log");
function _warn(message) {
console.log(`[dotenv@${version5}][WARN] ${message}`);
}
__name(_warn, "_warn");
function _debug(message) {
console.log(`[dotenv@${version5}][DEBUG] ${message}`);
}
__name(_debug, "_debug");
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 "";
}
__name(_dotenvKey, "_dotenvKey");
function _instructions(result, dotenvKey) {
let uri;
try {
uri = new URL(dotenvKey);
} catch (error2) {
if (error2.code === "ERR_INVALID_URL") {
throw new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development");
}
throw error2;
}
const key = uri.password;
if (!key) {
throw new Error("INVALID_DOTENV_KEY: Missing key part");
}
const environment = uri.searchParams.get("environment");
if (!environment) {
throw new Error("INVALID_DOTENV_KEY: Missing environment part");
}
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
const ciphertext = result.parsed[environmentKey];
if (!ciphertext) {
throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
}
return { ciphertext, key };
}
__name(_instructions, "_instructions");
function _vaultPath(options) {
let dotenvPath = path72.resolve(process.cwd(), ".env");
if (options && options.path && options.path.length > 0) {
dotenvPath = options.path;
}
return dotenvPath.endsWith(".vault") ? dotenvPath : `${dotenvPath}.vault`;
}
__name(_vaultPath, "_vaultPath");
function _resolveHome(envPath) {
return envPath[0] === "~" ? path72.join(os12.homedir(), envPath.slice(1)) : envPath;
}
__name(_resolveHome, "_resolveHome");
function _configVault(options) {
_log2("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 };
}
__name(_configVault, "_configVault");
function configDotenv(options) {
let dotenvPath = path72.resolve(process.cwd(), ".env");
let encoding = "utf8";
const debug = Boolean(options && options.debug);
if (options) {
if (options.path != null) {
dotenvPath = _resolveHome(options.path);
}
if (options.encoding != null) {
encoding = options.encoding;
}
}
try {
const parsed = DotenvModule.parse(fs24.readFileSync(dotenvPath, { encoding }));
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsed, options);
return { parsed };
} catch (e7) {
if (debug) {
_debug(`Failed to load ${dotenvPath} ${e7.message}`);
}
return { error: e7 };
}
}
__name(configDotenv, "configDotenv");
function config(options) {
const vaultPath = _vaultPath(options);
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options);
}
if (!fs24.existsSync(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);
}
__name(config, "config");
function decrypt(encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), "hex");
let ciphertext = Buffer.from(encrypted, "base64");
const nonce = ciphertext.slice(0, 12);
const authTag = ciphertext.slice(-16);
ciphertext = ciphertext.slice(12, -16);
try {
const aesgcm = crypto8.createDecipheriv("aes-256-gcm", key, nonce);
aesgcm.setAuthTag(authTag);
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
} catch (error2) {
const isRange = error2 instanceof RangeError;
const invalidKeyLength = error2.message === "Invalid key length";
const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
if (isRange || invalidKeyLength) {
const msg = "INVALID_DOTENV_KEY: It must be 64 characters long (or more)";
throw new Error(msg);
} else if (decryptionFailed) {
const msg = "DECRYPTION_FAILED: Please check your DOTENV_KEY";
throw new Error(msg);
} else {
console.error("Error: ", error2.code);
console.error("Error: ", error2.message);
throw error2;
}
}
}
__name(decrypt, "decrypt");
function populate(processEnv, parsed, options = {}) {
const debug = Boolean(options && options.debug);
const override = Boolean(options && options.override);
if (typeof parsed !== "object") {
throw new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
}
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key];
}
if (debug) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`);
} else {
_debug(`"${key}" is already defined and was NOT overwritten`);
}
}
} else {
processEnv[key] = parsed[key];
}
}
}
__name(populate, "populate");
var DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse: parse7,
populate
};
module3.exports.configDotenv = DotenvModule.configDotenv;
module3.exports._configVault = DotenvModule._configVault;
module3.exports._parseVault = DotenvModule._parseVault;
module3.exports.config = DotenvModule.config;
module3.exports.decrypt = DotenvModule.decrypt;
module3.exports.parse = DotenvModule.parse;
module3.exports.populate = DotenvModule.populate;
module3.exports = DotenvModule;
}
});
// ../../node_modules/.pnpm/dotenv-expand@12.0.2/node_modules/dotenv-expand/lib/main.js
var require_main2 = __commonJS({
"../../node_modules/.pnpm/dotenv-expand@12.0.2/node_modules/dotenv-expand/lib/main.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function _resolveEscapeSequences(value) {
return value.replace(/\\\$/g, "$");
}
__name(_resolveEscapeSequences, "_resolveEscapeSequences");
function expandValue(value, processEnv, runningParsed) {
const env6 = { ...runningParsed, ...processEnv };
const regex2 = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
let result = value;
let match2;
const seen = /* @__PURE__ */ new Set();
while ((match2 = regex2.exec(result)) !== null) {
seen.add(result);
const [template, bracedExpression, unbracedExpression] = match2;
const expression = bracedExpression || unbracedExpression;
const opRegex = /(:\+|\+|:-|-)/;
const opMatch = expression.match(opRegex);
const splitter = opMatch ? opMatch[0] : null;
const r7 = expression.split(splitter);
let defaultValue;
let value2;
const key = r7.shift();
if ([":+", "+"].includes(splitter)) {
defaultValue = env6[key] ? r7.join(splitter) : "";
value2 = null;
} else {
defaultValue = r7.join(splitter);
value2 = env6[key];
}
if (value2) {
if (seen.has(value2)) {
result = result.replace(template, defaultValue);
} else {
result = result.replace(template, value2);
}
} else {
result = result.replace(template, defaultValue);
}
if (result === runningParsed[key]) {
break;
}
regex2.lastIndex = 0;
}
return result;
}
__name(expandValue, "expandValue");
function expand(options) {
const runningParsed = {};
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
for (const key in options.parsed) {
let value = options.parsed[key];
if (processEnv[key] && processEnv[key] !== value) {
value = processEnv[key];
} else {
value = expandValue(value, processEnv, runningParsed);
}
options.parsed[key] = _resolveEscapeSequences(value);
runningParsed[key] = _resolveEscapeSequences(value);
}
for (const processKey in options.parsed) {
processEnv[processKey] = options.parsed[processKey];
}
return options;
}
__name(expand, "expand");
module3.exports.expand = expand;
}
});
// src/config/dot-env.ts
function getDefaultEnvFiles(env6) {
const envFiles = [".env", ".env.local"];
if (env6 !== void 0) {
envFiles.push(`.env.${env6}`);
envFiles.push(`.env.${env6}.local`);
}
return envFiles;
}
function loadDotEnv(envPaths, { includeProcessEnv, silent }) {
const parsedEnv = {};
for (const envPath of envPaths) {
const { error: error3, parsed } = import_dotenv.default.config({
path: envPath,
processEnv: parsedEnv,
override: true
});
if (error3) {
if ("code" in error3 && error3.code === "ENOENT") {
logger.debug(
`.env file not found at "${envPath}". Continuing... For more details, refer to https://developers.cloudflare.com/workers/wrangler/system-environment-variables/`
);
} else {
logger.debug(`Failed to load .env file "${envPath}":`, error3);
}
} else if (parsed && !silent) {
const relativePath = import_path12.default.relative(process.cwd(), envPath);
logger.log(`Using vars defined in ${relativePath}`);
}
}
const expandedEnv = {};
if (includeProcessEnv) {
Object.assign(expandedEnv, process.env);
if (!silent) {
logger.log("Using vars defined in process.env");
}
}
const { error: error2 } = import_dotenv_expand.default.expand({
processEnv: expandedEnv,
parsed: parsedEnv
});
if (error2) {
logger.debug(`Failed to expand .env values:`, error2);
}
return expandedEnv;
}
var import_path12, import_dotenv, import_dotenv_expand;
var init_dot_env = __esm({
"src/config/dot-env.ts"() {
init_import_meta_url();
import_path12 = __toESM(require("path"));
import_dotenv = __toESM(require_main());
import_dotenv_expand = __toESM(require_main2());
init_logger();
__name(getDefaultEnvFiles, "getDefaultEnvFiles");
__name(loadDotEnv, "loadDotEnv");
}
});
// src/core/index.ts
var init_core2 = __esm({
"src/core/index.ts"() {
init_import_meta_url();
init_helpers3();
}
});
// src/utils/is-local.ts
function isLocal(args, defaultValue = true) {
if (args.local === void 0 && args.remote === void 0) {
return defaultValue;
}
return args.local === true || args.remote === false;
}
function printResourceLocation(location) {
logger.log(source_default.hex("#BD5B08").bold("Resource location:"), location);
}
var init_is_local = __esm({
"src/utils/is-local.ts"() {
init_import_meta_url();
init_source();
init_logger();
__name(isLocal, "isLocal");
__name(printResourceLocation, "printResourceLocation");
}
});
// src/core/register-yargs-command.ts
function createRegisterYargsCommand(yargs, subHelp) {
return /* @__PURE__ */ __name(function registerCommand(segment, def, registerSubTreeCallback) {
yargs.command(
segment,
def.metadata?.hidden ? false : def.metadata?.description,
// Cast to satisfy TypeScript overload selection
(subYargs) => {
if (def.type === "command") {
const args = def.args ?? {};
const positionalArgs = new Set(def.positionalArgs);
const nonPositional = Object.fromEntries(
Object.entries(args).filter(([key]) => !positionalArgs.has(key)).map(([name2, opts]) => [
name2,
{
...opts,
group: "group" in opts ? source_default.bold(opts.group) : void 0
}
])
);
subYargs.options(nonPositional).epilogue(def.metadata?.epilogue ?? "").example(
def.metadata.examples?.map((ex) => [
ex.command,
ex.description
]) ?? []
);
for (const hide of def.metadata.hideGlobalFlags ?? []) {
subYargs.hide(hide);
}
for (const [key, opt] of Object.entries(args)) {
if (!opt.array && opt.type !== "array") {
subYargs.check(demandSingleValue(key));
}
}
for (const key of def.positionalArgs ?? []) {
subYargs.positional(key, args[key]);
}
} else if (def.type === "namespace") {
for (const hide of def.metadata.hideGlobalFlags ?? []) {
subYargs.hide(hide);
}
subYargs.command(subHelp);
}
registerSubTreeCallback();
},
// Only attach the handler for commands, not namespaces
def.type === "command" ? createHandler(def, def.command) : void 0
);
}, "registerCommand");
}
function createHandler(def, commandName) {
return /* @__PURE__ */ __name(async function handler(args) {
try {
const shouldPrintBanner = def.behaviour?.printBanner;
if (
/* No defautl behaviour override: show the banner */
shouldPrintBanner === void 0 || /* Explicit opt in: show the banner */
typeof shouldPrintBanner === "boolean" && shouldPrintBanner !== false || /* Hook resolves to true */
typeof shouldPrintBanner === "function" && shouldPrintBanner(args) === true
) {
await printWranglerBanner();
}
if (def.metadata.deprecated) {
logger.warn(def.metadata.deprecatedMessage);
}
if (def.metadata.statusMessage) {
logger.warn(def.metadata.statusMessage);
}
await def.validateArgs?.(args);
const shouldPrintResourceLocation = typeof def.behaviour?.printResourceLocation === "function" ? def.behaviour?.printResourceLocation(args) : def.behaviour?.printResourceLocation;
if (shouldPrintResourceLocation) {
const remote = "remote" in args && typeof args.remote === "boolean" ? args.remote : void 0;
const local = "local" in args && typeof args.local === "boolean" ? args.local : void 0;
const resourceIsLocal = isLocal({ remote, local });
if (resourceIsLocal) {
printResourceLocation("local");
logger.log(
`Use --remote if you want to access the remote instance.
`
);
} else {
printResourceLocation("remote");
}
}
const experimentalFlags = def.behaviour?.overrideExperimentalFlags ? def.behaviour?.overrideExperimentalFlags(args) : {
MULTIWORKER: false,
RESOURCES_PROVISION: args.experimentalProvision ?? false,
REMOTE_BINDINGS: args.experimentalRemoteBindings ?? false,
DEPLOY_REMOTE_DIFF_CHECK: false
};
await run(experimentalFlags, () => {
const config = def.behaviour?.provideConfig ?? true ? readConfig(args, {
hideWarnings: !(def.behaviour?.printConfigWarnings ?? true),
useRedirectIfAvailable: def.behaviour?.useConfigRedirectIfAvailable
}) : defaultWranglerConfig;
if (def.behaviour?.warnIfMultipleEnvsConfiguredButNoneSpecified) {
if (!("env" in args) && config.configPath) {
const { rawConfig } = experimental_readRawConfig(
{
config: config.configPath
},
{ hideWarnings: true }
);
const availableEnvs = Object.keys(rawConfig.env ?? {});
if (availableEnvs.length > 0) {
logger.warn(
dedent2`
Multiple environments are defined in the Wrangler configuration file, but no target environment was specified for the ${commandName.replace(/^wrangler\s+/, "")} command.
To avoid unintentional changes to the wrong environment, it is recommended to explicitly specify the target environment using the \`-e|--env\` flag.
If your intention is to use the top-level environment of your configuration simply pass an empty string to the flag to target such environment. For example \`--env=""\`.
`
);
}
}
}
return def.handler(args, {
config,
errors: { UserError, FatalError },
logger,
fetchResult
});
});
} catch (err) {
throw err;
}
}, "handler");
}
var init_register_yargs_command = __esm({
"src/core/register-yargs-command.ts"() {
init_import_meta_url();
init_source();
init_cfetch();
init_config2();
init_config();
init_errors();
init_experimental_flags();
init_logger();
init_dedent();
init_is_local();
init_wrangler_banner();
init_helpers3();
__name(createRegisterYargsCommand, "createRegisterYargsCommand");
__name(createHandler, "createHandler");
}
});
// src/d1/index.ts
var d1Namespace;
var init_d1 = __esm({
"src/d1/index.ts"() {
init_import_meta_url();
init_create_command();
d1Namespace = createNamespace({
metadata: {
description: "\u{1F5C4} Manage Workers D1 databases",
status: "stable",
owner: "Product: D1"
}
});
}
});
// src/d1/delete.ts
var d1DeleteCommand;
var init_delete2 = __esm({
"src/d1/delete.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_dialogs();
init_logger();
init_user2();
init_utils3();
d1DeleteCommand = createCommand({
metadata: {
description: "Delete D1 database",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: true
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
"skip-confirmation": {
type: "boolean",
description: "Skip confirmation",
alias: "y",
default: false
}
},
positionalArgs: ["name"],
async handler({ name: name2, skipConfirmation }, { config }) {
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(
config,
accountId,
name2
);
logger.log(`About to delete DB '${name2}' (${db.uuid}).`);
if (!skipConfirmation) {
const response = await confirm(`Ok to proceed?`);
if (!response) {
logger.log(`Not deleting.`);
return;
}
}
logger.log("Deleting...");
await fetchResult(config, `/accounts/${accountId}/d1/database/${db.uuid}`, {
method: "DELETE"
});
logger.log(`Deleted '${name2}' successfully.`);
}
});
}
});
// ../../node_modules/.pnpm/md5-file@5.0.0/node_modules/md5-file/index.js
var require_md5_file = __commonJS({
"../../node_modules/.pnpm/md5-file@5.0.0/node_modules/md5-file/index.js"(exports2, module3) {
init_import_meta_url();
var crypto8 = require("crypto");
var fs24 = require("fs");
var BUFFER_SIZE = 8192;
function md5FileSync(path72) {
const fd = fs24.openSync(path72, "r");
const hash = crypto8.createHash("md5");
const buffer = Buffer.alloc(BUFFER_SIZE);
try {
let bytesRead;
do {
bytesRead = fs24.readSync(fd, buffer, 0, BUFFER_SIZE);
hash.update(buffer.slice(0, bytesRead));
} while (bytesRead === BUFFER_SIZE);
} finally {
fs24.closeSync(fd);
}
return hash.digest("hex");
}
__name(md5FileSync, "md5FileSync");
function md5File2(path72) {
return new Promise((resolve25, reject) => {
const output = crypto8.createHash("md5");
const input = fs24.createReadStream(path72);
input.on("error", (err) => {
reject(err);
});
output.once("readable", () => {
resolve25(output.read().toString("hex"));
});
input.pipe(output);
});
}
__name(md5File2, "md5File");
module3.exports = md5File2;
module3.exports.sync = md5FileSync;
}
});
// src/d1/trimmer.ts
function trimSqlQuery(sql) {
if (!mayContainTransaction(sql)) {
return sql;
}
const trimmedSql = sql.replace("BEGIN TRANSACTION;", "").replace("COMMIT;", "");
if (mayContainTransaction(trimmedSql)) {
throw new UserError(
"Wrangler could not process the provided SQL file, as it contains several transactions.\nD1 runs your SQL in a transaction for you.\nPlease export an SQL file from your SQLite database and try again."
);
}
return trimmedSql;
}
function mayContainTransaction(sql) {
return sql.includes("BEGIN TRANSACTION");
}
var init_trimmer = __esm({
"src/d1/trimmer.ts"() {
init_import_meta_url();
init_errors();
__name(trimSqlQuery, "trimSqlQuery");
__name(mayContainTransaction, "mayContainTransaction");
}
});
// src/d1/splitter.ts
function mayContainMultipleStatements(sql) {
const trimmed = sql.trimEnd();
const semiColonIndex = trimmed.indexOf(";");
return semiColonIndex !== -1 && semiColonIndex !== trimmed.length - 1;
}
function splitSqlQuery(sql) {
const trimmedSql = trimSqlQuery(sql);
if (!mayContainMultipleStatements(trimmedSql)) {
return [trimmedSql];
}
const split = splitSqlIntoStatements(trimmedSql);
if (split.length === 0) {
return [trimmedSql];
} else {
return split;
}
}
function splitSqlIntoStatements(sql) {
const statements = [];
let str = "";
const compoundStatementStack = [];
const iterator = sql[Symbol.iterator]();
let next = iterator.next();
while (!next.done) {
const char = next.value;
if (compoundStatementStack[0]?.(str + char)) {
compoundStatementStack.shift();
}
switch (char) {
case `'`:
case `"`:
case "`":
str += char + consumeUntilMarker(iterator, char);
break;
case `$`: {
const dollarQuote = "$" + consumeWhile(iterator, isDollarQuoteIdentifier);
str += dollarQuote;
if (dollarQuote.endsWith("$")) {
str += consumeUntilMarker(iterator, dollarQuote);
}
break;
}
case `-`:
next = iterator.next();
if (!next.done && next.value === "-") {
consumeUntilMarker(iterator, "\n");
str += "\n";
break;
} else {
str += char;
continue;
}
case `/`:
next = iterator.next();
if (!next.done && next.value === "*") {
consumeUntilMarker(iterator, "*/");
break;
} else {
str += char;
continue;
}
case `;`:
if (compoundStatementStack.length === 0) {
statements.push(str);
str = "";
} else {
str += char;
}
break;
default:
str += char;
break;
}
if (isCompoundStatementStart(str)) {
compoundStatementStack.unshift(isCompoundStatementEnd);
}
next = iterator.next();
}
statements.push(str);
return statements.map((statement) => statement.trim()).filter((statement) => statement.length > 0);
}
function consumeWhile(iterator, predicate) {
let next = iterator.next();
let str = "";
while (!next.done) {
str += next.value;
if (!predicate(str)) {
break;
}
next = iterator.next();
}
return str;
}
function consumeUntilMarker(iterator, endMarker) {
return consumeWhile(iterator, (str) => !str.endsWith(endMarker));
}
function isDollarQuoteIdentifier(str) {
const lastChar = str.slice(-1);
return (
// The $ marks the end of the identifier
lastChar !== "$" && // we allow numbers, underscore and letters with diacritical marks
(/[0-9_]/i.test(lastChar) || lastChar.toLowerCase() !== lastChar.toUpperCase())
);
}
function isCompoundStatementStart(str) {
return /\s(BEGIN|CASE)\s$/i.test(str);
}
function isCompoundStatementEnd(str) {
return /\sEND[;\s]$/.test(str);
}
var init_splitter = __esm({
"src/d1/splitter.ts"() {
init_import_meta_url();
init_trimmer();
__name(mayContainMultipleStatements, "mayContainMultipleStatements");
__name(splitSqlQuery, "splitSqlQuery");
__name(splitSqlIntoStatements, "splitSqlIntoStatements");
__name(consumeWhile, "consumeWhile");
__name(consumeUntilMarker, "consumeUntilMarker");
__name(isDollarQuoteIdentifier, "isDollarQuoteIdentifier");
__name(isCompoundStatementStart, "isCompoundStatementStart");
__name(isCompoundStatementEnd, "isCompoundStatementEnd");
}
});
// src/d1/execute.ts
async function executeSql({
local,
remote,
config,
name: name2,
shouldPrompt,
persistTo,
file,
command: command2,
json,
preview
}) {
const existingLogLevel = logger.loggerLevel;
if (json) {
logger.loggerLevel = "error";
}
const input = file ? { file } : command2 ? { command: command2 } : null;
if (!input) {
throw new UserError(`Error: must provide --command or --file.`);
}
if (local && remote) {
throw new UserError(
`Error: can't use --local and --remote at the same time`
);
}
if (preview && !remote) {
throw new UserError(`Error: can't use --preview without --remote`);
}
if (persistTo && !local) {
throw new UserError(`Error: can't use --persist-to without --local`);
}
if (input.file) {
await checkForSQLiteBinary(input.file);
}
const result = remote || preview ? await executeRemotely({
config,
name: name2,
shouldPrompt,
input,
preview
}) : await executeLocally({
config,
name: name2,
input,
persistTo
});
if (json) {
logger.loggerLevel = existingLogLevel;
}
return result;
}
async function executeLocally({
config,
name: name2,
input,
persistTo
}) {
const localDB = getDatabaseInfoFromConfig(config, name2);
if (!localDB) {
throw new UserError(
`Couldn't find a D1 DB with the name or binding '${name2}' in your ${configFileName(config.configPath)} file.`
);
}
const id = localDB.previewDatabaseUuid ?? localDB.uuid;
const persistencePath = getLocalPersistencePath(persistTo, config);
const d1Persist = import_node_path28.default.join(persistencePath, "v3", "d1");
logger.log(
`\u{1F300} Executing on local database ${name2} (${id}) from ${readableRelative(
d1Persist
)}:`
);
logger.log(
"\u{1F300} To execute on your remote database, add a --remote flag to your wrangler command."
);
const mf = new import_miniflare12.Miniflare({
modules: true,
script: "",
d1Persist,
d1Databases: { DATABASE: id }
});
const db = await mf.getD1Database("DATABASE");
const sql = input.file ? readFileSync6(input.file) : input.command;
const queries = splitSqlQuery(sql);
let results;
try {
results = await db.batch(queries.map((query) => db.prepare(query)));
} catch (e7) {
throw e7?.cause ?? e7;
} finally {
await mf.dispose();
}
(0, import_node_assert17.default)(Array.isArray(results));
const allResults = results.map((result) => ({
results: (result.results ?? []).map(
(row) => Object.fromEntries(
Object.entries(row).map(([key, value]) => {
if (Array.isArray(value)) {
value = `[${value.join(", ")}]`;
}
if (value === null) {
value = "null";
}
return [key, value];
})
)
),
success: result.success,
meta: { duration: result.meta?.duration }
}));
if (allResults.every((r7) => r7.success)) {
logger.log(
`\u{1F6A3} ${allResults.length} command${allResults.length === 1 ? "" : "s"} executed successfully.`
);
}
return allResults;
}
async function executeRemotely({
config,
name: name2,
shouldPrompt,
input,
preview
}) {
if (input.file) {
const warning = `\u26A0\uFE0F This process may take some time, during which your D1 database will be unavailable to serve queries.`;
if (shouldPrompt) {
const ok = await confirm(`${warning}
Ok to proceed?`);
if (!ok) {
return null;
}
} else {
logger.warn(warning);
}
}
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(
config,
accountId,
name2
);
if (preview) {
if (!db.previewDatabaseUuid) {
throw new UserError(
`Please define a \`preview_database_id\` in your ${configFileName(config.configPath)} file to execute your queries against a preview database`
);
}
db.uuid = db.previewDatabaseUuid;
}
logger.log(
`\u{1F300} Executing on ${db.previewDatabaseUuid ? "preview" : "remote"} database ${name2} (${db.uuid}):`
);
logger.log(
"\u{1F300} To execute on your local development database, remove the --remote flag from your wrangler command."
);
if (input.file) {
const etag = await (0, import_md5_file.default)(input.file);
logger.log(
source_default.gray(
`Note: if the execution fails to complete, your DB will return to its original state and you can safely retry.`
)
);
const initResponse = await spinnerWhile({
promise: d1ApiPost(config, accountId, db, "import", { action: "init", etag }),
startMessage: "Checking if file needs uploading"
});
const uploadRequired = "upload_url" in initResponse;
if (!uploadRequired) {
logger.log(`\u{1F300} File already uploaded. Processing.`);
}
const firstPollResponse = uploadRequired ? (
// Upload the file to R2, then inform D1 to start processing it. The server delays before responding
// in case the file is quite small and can be processed without a second round-trip.
await uploadAndBeginIngestion(
config,
accountId,
db,
input.file,
etag,
initResponse
)
) : initResponse;
const finalResponse = await pollUntilComplete(
firstPollResponse,
config,
accountId,
db
);
if (finalResponse.status !== "complete") {
throw new APIError({ text: `D1 reset before execute completed!` });
}
const {
result: { num_queries, final_bookmark, meta }
} = finalResponse;
logger.log(
`\u{1F6A3} Executed ${num_queries} queries in ${(meta.duration / 1e3).toFixed(
2
)} seconds (${meta.rows_read} rows read, ${meta.rows_written} rows written)
` + source_default.gray(` Database is currently at bookmark ${final_bookmark}.`)
);
return [
{
results: [
{
"Total queries executed": num_queries,
"Rows read": meta.rows_read,
"Rows written": meta.rows_written,
"Database size (MB)": (meta.size_after / 1e6).toFixed(2)
}
],
success: true,
finalBookmark: final_bookmark,
meta
}
];
} else {
const result = await d1ApiPost(
config,
accountId,
db,
"query",
{
sql: input.command
}
);
logResult(result);
return result;
}
}
async function uploadAndBeginIngestion(complianceConfig, accountId, db, file, etag, initResponse) {
const { upload_url, filename } = initResponse;
const { size } = await import_fs16.promises.stat(file);
const uploadResponse = await spinnerWhile({
promise: (0, import_undici8.fetch)(upload_url, {
method: "PUT",
headers: {
"Content-length": `${size}`
},
body: (0, import_fs16.createReadStream)(file),
duplex: "half"
// required for NodeJS streams over .fetch ?
}),
startMessage: `\u{1F300} Uploading ${filename}`,
endMessage: `\u{1F300} Uploading complete.`
});
if (uploadResponse.status !== 200) {
throw new UserError(
`File could not be uploaded. Please retry.
Got response: ${await uploadResponse.text()}`
);
}
const etagResponse = uploadResponse.headers.get("etag");
if (!etagResponse) {
throw new UserError(`File did not upload successfully. Please retry.`);
}
if (etag !== etagResponse.replace(/^"|"$/g, "")) {
throw new UserError(
`File contents did not upload successfully. Please retry.`
);
}
return await d1ApiPost(
complianceConfig,
accountId,
db,
"import",
{ action: "ingest", filename, etag }
);
}
async function pollUntilComplete(response, complianceConfig, accountId, db) {
if (!response.success) {
throw new Error(response.error);
}
response.messages.forEach((line) => {
logger.log(`\u{1F300} ${line}`);
});
if (response.status === "complete") {
return response;
} else if (response.status === "error") {
throw new APIError({
text: response.errors?.join("\n"),
notes: response.messages.map((text) => ({ text }))
});
} else {
const newResponse = await d1ApiPost(
complianceConfig,
accountId,
db,
"import",
{
action: "poll",
current_bookmark: response.at_bookmark
}
);
return await pollUntilComplete(
newResponse,
complianceConfig,
accountId,
db
);
}
}
async function d1ApiPost(complianceConfig, accountId, db, action, body) {
try {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database/${db.uuid}/${action}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
...db.internal_env ? { "x-d1-internal-env": db.internal_env } : {}
},
body: JSON.stringify(body)
}
);
} catch (x6) {
if (x6 instanceof APIError) {
x6.preventReport();
}
throw x6;
}
}
function logResult(r7) {
logger.log(
`\u{1F6A3} Executed ${Array.isArray(r7) && r7.length !== 1 ? `${r7.length} commands` : "1 command"} in ${Array.isArray(r7) ? r7.map((d6) => d6.meta?.duration || 0).reduce((a5, b6) => a5 + b6, 0) : r7.meta?.duration}ms`
);
}
function shorten(query, length) {
return query && query.length > length ? query.slice(0, length) + "..." : query;
}
async function checkForSQLiteBinary(filename) {
const buffer = Buffer.alloc(15);
try {
const fd = await import_fs16.promises.open(filename, "r");
await fd.read(buffer, 0, 15);
} catch {
throw new UserError(
`Unable to read SQL text file "${filename}". Please check the file path and try again.`
);
}
if (buffer.toString("utf8") === "SQLite format 3") {
throw new UserError(
"Provided file is a binary SQLite database file instead of an SQL text file. The execute command can only process SQL text files. Please export an SQL file from your SQLite database and try again."
);
}
}
var import_fs16, import_node_assert17, import_node_path28, import_md5_file, import_miniflare12, import_undici8, d1ExecuteCommand;
var init_execute = __esm({
"src/d1/execute.ts"() {
init_import_meta_url();
import_fs16 = require("fs");
import_node_assert17 = __toESM(require("assert"));
import_node_path28 = __toESM(require("path"));
init_interactive();
init_source();
import_md5_file = __toESM(require_md5_file());
import_miniflare12 = require("miniflare");
import_undici8 = __toESM(require_undici());
init_cfetch();
init_config2();
init_create_command();
init_get_local_persistence_path();
init_dialogs();
init_errors();
init_logger();
init_parse();
init_paths();
init_user2();
init_splitter();
init_utils3();
d1ExecuteCommand = createCommand({
metadata: {
description: "Execute a command or SQL file",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
database: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
yes: {
type: "boolean",
description: 'Answer "yes" to any prompts',
alias: "y"
},
local: {
type: "boolean",
description: "Execute commands/files against a local DB for use with wrangler dev"
},
remote: {
type: "boolean",
description: "Execute commands/files against a remote DB for use with wrangler dev"
},
file: {
type: "string",
description: "A .sql file to ingest"
},
command: {
type: "string",
description: "A single SQL statement to execute"
},
"persist-to": {
type: "string",
description: "Specify directory to use for local persistence (for --local)",
requiresArg: true
},
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
},
preview: {
type: "boolean",
description: "Execute commands/files against a preview D1 DB",
default: false
}
},
positionalArgs: ["database"],
async handler(args, { config }) {
const {
local,
remote,
database,
yes,
persistTo,
file,
command: command2,
json,
preview
} = args;
const existingLogLevel = logger.loggerLevel;
if (json) {
logger.loggerLevel = "error";
}
if (file && command2) {
throw createFatalError(
`Error: can't provide both --command and --file.`,
json,
void 0,
{ telemetryMessage: true }
);
}
const isInteractive3 = process.stdout.isTTY;
try {
const response = await executeSql({
local,
remote,
config,
name: database,
shouldPrompt: isInteractive3 && !yes && !json,
persistTo,
file,
command: command2,
json,
preview
});
if (!response) {
return;
}
if (isInteractive3 && !json) {
for (const result of response) {
if (!Array.isArray(result)) {
const { results, query } = result;
if (Array.isArray(results) && results.length > 0) {
const shortQuery = shorten(query, 48);
if (shortQuery) {
logger.log(source_default.dim(shortQuery));
}
logger.table(
results.map(
(r7) => Object.fromEntries(
Object.entries(r7).map(([k6, v7]) => [k6, String(v7)])
)
)
);
}
}
}
} else {
logger.loggerLevel = existingLogLevel;
logger.log(JSON.stringify(response, null, 2));
}
} catch (error2) {
if (json && error2 instanceof Error) {
logger.loggerLevel = existingLogLevel;
const messageToDisplay = error2.name === "APIError" ? error2 : { text: error2.message };
throw new JsonFriendlyFatalError(
JSON.stringify({ error: messageToDisplay }, null, 2)
);
} else {
throw error2;
}
}
}
});
__name(executeSql, "executeSql");
__name(executeLocally, "executeLocally");
__name(executeRemotely, "executeRemotely");
__name(uploadAndBeginIngestion, "uploadAndBeginIngestion");
__name(pollUntilComplete, "pollUntilComplete");
__name(d1ApiPost, "d1ApiPost");
__name(logResult, "logResult");
__name(shorten, "shorten");
__name(checkForSQLiteBinary, "checkForSQLiteBinary");
}
});
// src/d1/export.ts
async function exportLocal(config, name2, output, tables, noSchema, noData) {
const localDB = getDatabaseInfoFromConfig(config, name2);
if (!localDB) {
throw new UserError(
`Couldn't find a D1 DB with the name or binding '${name2}' in your ${configFileName(config.configPath)} file.`
);
}
const id = localDB.previewDatabaseUuid ?? localDB.uuid;
const persistencePath = getLocalPersistencePath(void 0, config);
const d1Persist = import_node_path29.default.join(persistencePath, "v3", "d1");
logger.log(
`\u{1F300} Exporting local database ${name2} (${id}) from ${readableRelative(
d1Persist
)}:`
);
logger.log(
"\u{1F300} To export your remote database, add a --remote flag to your wrangler command."
);
const mf = new import_miniflare13.Miniflare({
modules: true,
script: "export default {}",
d1Persist,
d1Databases: { DATABASE: id }
});
const db = await mf.getD1Database("DATABASE");
logger.log(`\u{1F300} Exporting SQL to ${output}...`);
try {
const dump = await db.prepare(`PRAGMA miniflare_d1_export(?,?,?);`).bind(noSchema, noData, ...tables).raw();
await import_promises13.default.writeFile(output, dump[0].join("\n"));
} catch (e7) {
throw new UserError(e7.message);
} finally {
await mf.dispose();
}
logger.log(`Done!`);
}
async function exportRemotely(config, name2, output, tables, noSchema, noData) {
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(
config,
accountId,
name2
);
logger.log(`\u{1F300} Executing on remote database ${name2} (${db.uuid}):`);
const dumpOptions = {
no_schema: noSchema,
no_data: noData,
tables
};
const s5 = spinner();
const finalResponse = await spinnerWhile({
spinner: s5,
promise: /* @__PURE__ */ __name(() => pollExport(s5, config, accountId, db, dumpOptions, void 0), "promise"),
startMessage: `Creating export`
});
if (finalResponse.status !== "complete") {
throw new APIError({ text: `D1 reset before export completed!` });
}
logger.log(
source_default.gray(
`You can also download your export from the following URL manually. This link will be valid for one hour: ${finalResponse.result.signed_url}`
)
);
await spinnerWhile({
startMessage: `Downloading SQL to ${output}`,
async promise() {
const contents = await (0, import_undici9.fetch)(finalResponse.result.signed_url);
if (!contents.ok) {
throw new Error(
`There was an error while downloading from the presigned URL with status code: ${contents.status}`
);
}
await import_promises13.default.writeFile(output, contents.body || "");
}
});
logger.log(`\u{1F300} Downloaded to ${output} successfully!`);
}
async function pollExport(s5, complianceConfig, accountId, db, dumpOptions, currentBookmark, num_parts_uploaded = 0) {
const response = await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database/${db.uuid}/export`,
{
method: "POST",
headers: {
...db.internal_env ? { "x-d1-internal-env": db.internal_env } : {},
"content-type": "application/json"
},
body: JSON.stringify({
output_format: "polling",
dump_options: dumpOptions,
current_bookmark: currentBookmark
})
}
);
if (!response.success) {
throw new Error(response.error);
}
response.messages.forEach((line) => {
if (line.startsWith(`Uploaded part`)) {
s5.update(`Uploaded part ${++num_parts_uploaded}`);
} else {
s5.update(line);
}
});
if (response.status === "complete") {
return response;
} else if (response.status === "error") {
throw new APIError({
text: response.error,
notes: response.messages.map((text) => ({ text }))
});
} else {
return await pollExport(
s5,
complianceConfig,
accountId,
db,
dumpOptions,
response.at_bookmark,
num_parts_uploaded
);
}
}
var import_promises13, import_node_path29, import_miniflare13, import_undici9, d1ExportCommand;
var init_export = __esm({
"src/d1/export.ts"() {
init_import_meta_url();
import_promises13 = __toESM(require("fs/promises"));
import_node_path29 = __toESM(require("path"));
init_interactive();
init_source();
import_miniflare13 = require("miniflare");
import_undici9 = __toESM(require_undici());
init_cfetch();
init_config2();
init_create_command();
init_get_local_persistence_path();
init_errors();
init_logger();
init_parse();
init_paths();
init_user2();
init_utils3();
d1ExportCommand = createCommand({
metadata: {
description: "Export the contents or schema of your database as a .sql file",
status: "stable",
owner: "Product: D1"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the DB"
},
local: {
type: "boolean",
description: "Export from your local DB you use with wrangler dev",
conflicts: "remote"
},
remote: {
type: "boolean",
description: "Export from your live D1",
conflicts: "local"
},
"no-schema": {
type: "boolean",
description: "Only output table contents, not the DB schema",
conflicts: "no-data"
},
"no-data": {
type: "boolean",
description: "Only output table schema, not the contents of the DBs themselves",
conflicts: "no-schema"
},
// For --no-schema and --no-data to work, we need their positive versions
// to be defined. But keep them hidden as they default to true
schema: {
type: "boolean",
hidden: true,
default: true
},
data: {
type: "boolean",
hidden: true,
default: true
},
table: {
type: "string",
description: "Specify which tables to include in export"
},
output: {
type: "string",
description: "Which .sql file to output to",
demandOption: true
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const { remote, name: name2, output, schema, data, table } = args;
if (!schema && !data) {
throw new UserError(`You cannot specify both --no-schema and --no-data`);
}
const tables = table ? Array.isArray(table) ? table : [table] : [];
if (remote) {
return await exportRemotely(config, name2, output, tables, !schema, !data);
} else {
return await exportLocal(config, name2, output, tables, !schema, !data);
}
}
});
__name(exportLocal, "exportLocal");
__name(exportRemotely, "exportRemotely");
__name(pollExport, "pollExport");
}
});
// src/d1/info.ts
var d1InfoCommand;
var init_info = __esm({
"src/d1/info.ts"() {
init_import_meta_url();
init_pretty_bytes();
init_cfetch();
init_create_command();
init_logger();
init_user2();
init_utils3();
d1InfoCommand = createCommand({
metadata: {
description: "Get information about a D1 database, including the current database size and state",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the DB"
},
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
positionalArgs: ["name"],
async handler({ name: name2, json }, { config }) {
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(
config,
accountId,
name2
);
const result = await getDatabaseInfoFromIdOrName(
config,
accountId,
db.uuid
);
const output = { ...result };
if (output["file_size"]) {
output["database_size"] = output["file_size"];
delete output["file_size"];
}
if (output["version"] !== "alpha") {
delete output["version"];
}
if (result.version !== "alpha") {
const today = /* @__PURE__ */ new Date();
const yesterday = new Date(new Date(today).setDate(today.getDate() - 1));
const graphqlResult = await fetchGraphqlResult(
config,
{
method: "POST",
body: JSON.stringify({
query: `query getD1MetricsOverviewQuery($accountTag: string, $filter: ZoneWorkersRequestsFilter_InputObject) {
viewer {
accounts(filter: {accountTag: $accountTag}) {
d1AnalyticsAdaptiveGroups(limit: 10000, filter: $filter) {
sum {
readQueries
writeQueries
rowsRead
rowsWritten
}
dimensions {
datetimeHour
}
}
}
}
}`,
operationName: "getD1MetricsOverviewQuery",
variables: {
accountTag: accountId,
filter: {
AND: [
{
datetimeHour_geq: yesterday.toISOString(),
datetimeHour_leq: today.toISOString(),
databaseId: db.uuid
}
]
}
}
}),
headers: {
"Content-Type": "application/json"
}
}
);
const metrics = {
readQueries: 0,
writeQueries: 0,
rowsRead: 0,
rowsWritten: 0
};
if (graphqlResult) {
graphqlResult.data?.viewer?.accounts[0]?.d1AnalyticsAdaptiveGroups?.forEach(
(row) => {
metrics.readQueries += row?.sum?.readQueries ?? 0;
metrics.writeQueries += row?.sum?.writeQueries ?? 0;
metrics.rowsRead += row?.sum?.rowsRead ?? 0;
metrics.rowsWritten += row?.sum?.rowsWritten ?? 0;
}
);
output.read_queries_24h = metrics.readQueries;
output.write_queries_24h = metrics.writeQueries;
output.rows_read_24h = metrics.rowsRead;
output.rows_written_24h = metrics.rowsWritten;
}
}
if (json) {
logger.log(JSON.stringify(output, null, 2));
} else {
if (result.read_replication) {
output["read_replication.mode"] = result.read_replication.mode;
delete output["read_replication"];
}
const entries = Object.entries(output).filter(
// also remove any version that isn't "alpha"
([k6, v7]) => k6 !== "uuid" && !(k6 === "version" && v7 !== "alpha")
);
const data = entries.map(([k6, v7]) => {
let value;
if (k6 === "database_size") {
value = prettyBytes(Number(v7));
} else if (k6 === "read_queries_24h" || k6 === "write_queries_24h" || k6 === "rows_read_24h" || k6 === "rows_written_24h") {
value = v7.toLocaleString();
} else if (typeof v7 === "object") {
value = JSON.stringify(v7);
} else {
value = String(v7);
}
return {
[db.binding || ""]: k6,
[db.uuid]: value
};
});
logger.table(data);
}
}
});
}
});
// src/d1/insights.ts
function getDurationDates(durationString) {
const endDate = /* @__PURE__ */ new Date();
const durationValue = parseInt(durationString.slice(0, -1));
const durationUnit = durationString.slice(-1);
let startDate;
switch (durationUnit) {
case "d":
if (durationValue > 31) {
throw new Error("Duration cannot be greater than 31 days");
}
startDate = new Date(
endDate.getTime() - durationValue * 24 * 60 * 60 * 1e3
);
break;
case "m":
if (durationValue > 31 * 24 * 60) {
throw new Error(
`Duration cannot be greater than ${31 * 24 * 60} minutes (31 days)`
);
}
startDate = new Date(endDate.getTime() - durationValue * 60 * 1e3);
break;
case "h":
if (durationValue > 31 * 24) {
throw new Error(
`Duration cannot be greater than ${31 * 24} hours (31 days)`
);
}
startDate = new Date(endDate.getTime() - durationValue * 60 * 60 * 1e3);
break;
default:
throw new Error("Invalid duration unit");
}
return [startDate.toISOString(), endDate.toISOString()];
}
var cliOptionToGraphQLOption, d1InsightsCommand;
var init_insights = __esm({
"src/d1/insights.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
init_utils3();
cliOptionToGraphQLOption = {
time: "queryDurationMs",
reads: "rowsRead",
writes: "rowsWritten",
count: "count"
};
__name(getDurationDates, "getDurationDates");
d1InsightsCommand = createCommand({
metadata: {
description: "Get information about the queries run on a D1 database.",
status: "experimental",
owner: "Product: D1"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the DB"
},
timePeriod: {
type: "string",
description: "Fetch data from now to the provided time period",
default: "1d"
},
"sort-type": {
type: "string",
description: "Choose the operation you want to sort insights by",
choices: ["sum", "avg"],
default: "sum"
},
"sort-by": {
type: "string",
description: "Choose the field you want to sort insights by",
choices: ["time", "reads", "writes", "count"],
default: "time"
},
"sort-direction": {
type: "string",
description: "Choose a sort direction",
choices: ["ASC", "DESC"],
default: "DESC"
},
limit: {
type: "number",
description: "fetch insights about the first X queries",
default: 5
},
count: {
type: "number",
description: "Same as --limit",
default: 5,
deprecated: true,
hidden: true
},
json: {
type: "boolean",
description: "return output as clean JSON",
default: false
}
},
positionalArgs: ["name"],
async handler({ name: name2, json, limit, timePeriod, sortType, sortBy, sortDirection }, { config }) {
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(
config,
accountId,
name2
);
const result = await getDatabaseInfoFromIdOrName(
config,
accountId,
db.uuid
);
const output = [];
if (result.version !== "alpha") {
const [startDate, endDate] = getDurationDates(timePeriod);
const parsedSortBy = cliOptionToGraphQLOption[sortBy];
const orderByClause = parsedSortBy === "count" ? `${parsedSortBy}_${sortDirection}` : `${sortType}_${parsedSortBy}_${sortDirection}`;
const graphqlQueriesResult = await fetchGraphqlResult(config, {
method: "POST",
body: JSON.stringify({
query: `query getD1QueriesOverviewQuery($accountTag: string, $filter: ZoneWorkersRequestsFilter_InputObject) {
viewer {
accounts(filter: {accountTag: $accountTag}) {
d1QueriesAdaptiveGroups(limit: ${limit}, filter: $filter, orderBy: [${orderByClause}]) {
sum {
queryDurationMs
rowsRead
rowsWritten
rowsReturned
}
avg {
queryDurationMs
rowsRead
rowsWritten
rowsReturned
}
count
dimensions {
query
}
}
}
}
}`,
operationName: "getD1QueriesOverviewQuery",
variables: {
accountTag: accountId,
filter: {
AND: [
{
datetimeHour_geq: startDate,
datetimeHour_leq: endDate,
databaseId: db.uuid
}
]
}
}
}),
headers: {
"Content-Type": "application/json"
}
});
graphqlQueriesResult?.data?.viewer?.accounts[0]?.d1QueriesAdaptiveGroups?.forEach(
(row) => {
if (!row.dimensions.query) {
return;
}
output.push({
query: row.dimensions.query,
avgRowsRead: row?.avg?.rowsRead ?? 0,
totalRowsRead: row?.sum?.rowsRead ?? 0,
avgRowsWritten: row?.avg?.rowsWritten ?? 0,
totalRowsWritten: row?.sum?.rowsWritten ?? 0,
avgDurationMs: row?.avg?.queryDurationMs ?? 0,
totalDurationMs: row?.sum?.queryDurationMs ?? 0,
numberOfTimesRun: row?.count ?? 0,
queryEfficiency: row?.avg?.rowsReturned && row?.avg?.rowsRead ? row?.avg?.rowsReturned / row?.avg?.rowsRead : 0
});
}
);
}
if (json) {
logger.log(JSON.stringify(output, null, 2));
} else {
logger.log(JSON.stringify(output, null, 2));
}
}
});
}
});
// src/d1/migrations/index.ts
var d1MigrationsNamespace;
var init_migrations = __esm({
"src/d1/migrations/index.ts"() {
init_import_meta_url();
init_create_command();
d1MigrationsNamespace = createNamespace({
metadata: {
description: "Interact with D1 migrations",
status: "stable",
owner: "Product: D1"
}
});
}
});
// src/d1/migrations/helpers.ts
async function getMigrationsPath({
projectPath,
migrationsFolderPath,
createIfMissing,
configPath
}) {
const dir = import_path13.default.resolve(projectPath, migrationsFolderPath);
if (import_node_fs16.default.existsSync(dir)) {
return dir;
}
const warning = `No migrations folder found.${migrationsFolderPath === DEFAULT_MIGRATION_PATH ? ` Set \`migrations_dir\` in your ${configFileName(configPath)} file to choose a different path.` : ""}`;
if (createIfMissing && await confirm(`${warning}
Ok to create ${dir}?`)) {
import_node_fs16.default.mkdirSync(dir, { recursive: true });
return dir;
} else {
logger.warn(warning);
}
throw new UserError(`No migrations present at ${dir}.`);
}
async function getUnappliedMigrations({
migrationsTableName,
migrationsPath,
local,
remote,
config,
name: name2,
persistTo,
preview
}) {
const appliedMigrations = (await listAppliedMigrations({
migrationsTableName,
local,
remote,
config,
name: name2,
persistTo,
preview
})).map((migration) => {
return migration.name;
});
const projectMigrations = getMigrationNames(migrationsPath);
const unappliedMigrations = [];
for (const migration of projectMigrations) {
if (!appliedMigrations.includes(migration)) {
unappliedMigrations.push(migration);
}
}
return unappliedMigrations;
}
function getMigrationNames(migrationsPath) {
const migrations = [];
const dir = import_node_fs16.default.opendirSync(migrationsPath);
let dirent;
while ((dirent = dir.readSync()) !== null) {
if (dirent.name.endsWith(".sql")) {
migrations.push(dirent.name);
}
}
dir.closeSync();
return migrations;
}
function getNextMigrationNumber(migrationsPath) {
const migrationNumbers = getMigrationNames(migrationsPath).map(
(migration) => parseInt(migration.split("_")[0])
);
const highestMigrationNumber = Math.max(...migrationNumbers, 0);
return highestMigrationNumber + 1;
}
var import_node_fs16, import_path13, listAppliedMigrations, initMigrationsTable;
var init_helpers6 = __esm({
"src/d1/migrations/helpers.ts"() {
init_import_meta_url();
import_node_fs16 = __toESM(require("fs"));
import_path13 = __toESM(require("path"));
init_config2();
init_dialogs();
init_errors();
init_is_interactive();
init_logger();
init_constants4();
init_execute();
__name(getMigrationsPath, "getMigrationsPath");
__name(getUnappliedMigrations, "getUnappliedMigrations");
listAppliedMigrations = /* @__PURE__ */ __name(async ({
migrationsTableName,
local,
remote,
config,
name: name2,
persistTo,
preview
}) => {
const response = await executeSql({
local,
remote,
config,
name: name2,
shouldPrompt: !isNonInteractiveOrCI(),
persistTo,
command: `SELECT *
FROM ${migrationsTableName}
ORDER BY id`,
file: void 0,
json: true,
preview
});
if (!response || response[0].results.length === 0) {
return [];
}
return response[0].results;
}, "listAppliedMigrations");
__name(getMigrationNames, "getMigrationNames");
__name(getNextMigrationNumber, "getNextMigrationNumber");
initMigrationsTable = /* @__PURE__ */ __name(async ({
migrationsTableName,
local,
remote,
config,
name: name2,
persistTo,
preview
}) => {
return executeSql({
local,
remote,
config,
name: name2,
shouldPrompt: !isNonInteractiveOrCI(),
persistTo,
command: `CREATE TABLE IF NOT EXISTS ${migrationsTableName}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);`,
file: void 0,
json: true,
preview
});
}, "initMigrationsTable");
}
});
// src/d1/migrations/apply.ts
var import_node_fs17, import_path14, d1MigrationsApplyCommand;
var init_apply2 = __esm({
"src/d1/migrations/apply.ts"() {
init_import_meta_url();
import_node_fs17 = __toESM(require("fs"));
import_path14 = __toESM(require("path"));
init_config2();
init_create_command();
init_dialogs();
init_errors();
init_is_interactive();
init_logger();
init_constants4();
init_execute();
init_utils3();
init_helpers6();
d1MigrationsApplyCommand = createCommand({
metadata: {
description: "Apply D1 migrations",
status: "stable",
owner: "Product: D1"
},
args: {
database: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
local: {
type: "boolean",
description: "Execute commands/files against a local DB for use with wrangler dev"
},
remote: {
type: "boolean",
description: "Execute commands/files against a remote DB for use with wrangler dev --remote"
},
preview: {
type: "boolean",
description: "Execute commands/files against a preview D1 DB",
default: false
},
"persist-to": {
type: "string",
description: "Specify directory to use for local persistence (you must use --local with this flag)",
requiresArg: true
}
},
positionalArgs: ["database"],
async handler({ database, local, remote, persistTo, preview }, { config }) {
const databaseInfo = getDatabaseInfoFromConfig(config, database);
if (!databaseInfo && remote) {
throw new UserError(
`Couldn't find a D1 DB with the name or binding '${database}' in your ${configFileName(config.configPath)} file.`
);
}
if (!config.configPath) {
return;
}
const migrationsPath = await getMigrationsPath({
projectPath: import_path14.default.dirname(config.configPath),
migrationsFolderPath: databaseInfo?.migrationsFolderPath ?? DEFAULT_MIGRATION_PATH,
createIfMissing: false,
configPath: config.configPath
});
const migrationsTableName = databaseInfo?.migrationsTableName ?? DEFAULT_MIGRATION_TABLE;
await initMigrationsTable({
migrationsTableName,
local,
remote,
config,
name: database,
persistTo,
preview
});
const unappliedMigrations = (await getUnappliedMigrations({
migrationsTableName,
migrationsPath,
local,
remote,
config,
name: database,
persistTo,
preview
})).map((migration) => {
return {
name: migration,
status: "\u{1F552}\uFE0F"
};
}).sort((a5, b6) => {
const migrationNumberA = parseInt(a5.name.split("_")[0]);
const migrationNumberB = parseInt(b6.name.split("_")[0]);
if (migrationNumberA < migrationNumberB) {
return -1;
}
if (migrationNumberA > migrationNumberB) {
return 1;
}
return 0;
});
if (unappliedMigrations.length === 0) {
logger.log("\u2705 No migrations to apply!");
return;
}
logger.log("Migrations to be applied:");
logger.table(unappliedMigrations.map((m6) => ({ name: m6.name })));
const ok = await confirm(
`About to apply ${unappliedMigrations.length} migration(s)
Your database may not be available to serve requests during the migration, continue?`
);
if (!ok) {
return;
}
for (const migration of unappliedMigrations) {
let query = import_node_fs17.default.readFileSync(
`${migrationsPath}/${migration.name}`,
"utf8"
);
query += `
INSERT INTO ${migrationsTableName} (name)
values ('${migration.name}');
`;
let success2 = true;
let errorNotes = [];
try {
const response = await executeSql({
local,
remote,
config,
name: database,
shouldPrompt: !isNonInteractiveOrCI(),
persistTo,
command: query,
file: void 0,
json: void 0,
preview
});
if (response === null) {
return;
}
for (const result of response) {
if (Array.isArray(result)) {
for (const subResult of result) {
if (!subResult.success) {
success2 = false;
}
}
} else {
if (!result.success) {
success2 = false;
}
}
}
} catch (e7) {
const err = e7;
const maybeCause = err.cause ?? err;
success2 = false;
errorNotes = err.notes?.map((msg) => msg.text) ?? [
maybeCause?.message ?? maybeCause.toString()
];
}
migration.status = success2 ? "\u2705" : "\u274C";
logger.table(
unappliedMigrations.map((m6) => ({ name: m6.name, status: m6.status }))
);
if (errorNotes.length > 0) {
logger.error(
`Migration ${migration.name} failed with the following errors:`
);
}
if (errorNotes.length > 0) {
throw new UserError(
errorNotes.map((err) => {
return err;
}).join("\n")
);
}
}
}
});
}
});
// src/d1/migrations/create.ts
function pad(num, size) {
let newNum = num.toString();
while (newNum.length < size) {
newNum = "0" + newNum;
}
return newNum;
}
var import_node_fs18, import_path15, d1MigrationsCreateCommand;
var init_create3 = __esm({
"src/d1/migrations/create.ts"() {
init_import_meta_url();
import_node_fs18 = __toESM(require("fs"));
import_path15 = __toESM(require("path"));
init_config2();
init_create_command();
init_errors();
init_logger();
init_constants4();
init_utils3();
init_helpers6();
d1MigrationsCreateCommand = createCommand({
metadata: {
description: "Create a new migration",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: true
},
args: {
database: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
message: {
type: "string",
demandOption: true,
description: "The Migration message"
}
},
positionalArgs: ["database", "message"],
async handler({ database, message }, { config }) {
const databaseInfo = getDatabaseInfoFromConfig(config, database);
if (!databaseInfo) {
throw new UserError(
`Couldn't find a D1 DB with the name or binding '${database}' in your ${configFileName(config.configPath)} file.`
);
}
if (!config.configPath) {
return;
}
const migrationsPath = await getMigrationsPath({
projectPath: import_path15.default.dirname(config.configPath),
migrationsFolderPath: databaseInfo.migrationsFolderPath ?? DEFAULT_MIGRATION_PATH,
createIfMissing: true,
configPath: config.configPath
});
const nextMigrationNumber = pad(getNextMigrationNumber(migrationsPath), 4);
const migrationName = message.replaceAll(" ", "_");
const newMigrationName = `${nextMigrationNumber}_${migrationName}.sql`;
import_node_fs18.default.writeFileSync(
`${migrationsPath}/${newMigrationName}`,
`-- Migration number: ${nextMigrationNumber} ${(/* @__PURE__ */ new Date()).toISOString()}
`
);
logger.log(`\u2705 Successfully created Migration '${newMigrationName}'!
`);
logger.log(`The migration is available for editing here`);
logger.log(`${migrationsPath}/${newMigrationName}`);
}
});
__name(pad, "pad");
}
});
// src/d1/migrations/list.ts
var import_path16, d1MigrationsListCommand;
var init_list3 = __esm({
"src/d1/migrations/list.ts"() {
init_import_meta_url();
import_path16 = __toESM(require("path"));
init_config2();
init_create_command();
init_errors();
init_logger();
init_user2();
init_constants4();
init_utils3();
init_helpers6();
d1MigrationsListCommand = createCommand({
metadata: {
description: "List your D1 migrations",
status: "stable",
owner: "Product: D1"
},
args: {
database: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
local: {
type: "boolean",
description: "Execute commands/files against a local DB for use with wrangler dev"
},
remote: {
type: "boolean",
description: "Execute commands/files against a remote DB for use with wrangler dev --remote"
},
preview: {
type: "boolean",
description: "Execute commands/files against a preview D1 DB",
default: false
},
"persist-to": {
type: "string",
description: "Specify directory to use for local persistence (you must use --local with this flag)",
requiresArg: true
}
},
positionalArgs: ["database"],
async handler({ database, local, remote, persistTo, preview }, { config }) {
if (remote) {
await requireAuth({});
}
const databaseInfo = getDatabaseInfoFromConfig(config, database);
if (!databaseInfo && remote) {
throw new UserError(
`Couldn't find a D1 DB with the name or binding '${database}' in your ${configFileName(config.configPath)} file.`
);
}
if (!config.configPath) {
return;
}
const migrationsPath = await getMigrationsPath({
projectPath: import_path16.default.dirname(config.configPath),
migrationsFolderPath: databaseInfo?.migrationsFolderPath ?? DEFAULT_MIGRATION_PATH,
createIfMissing: false,
configPath: config.configPath
});
const migrationsTableName = databaseInfo?.migrationsTableName ?? DEFAULT_MIGRATION_TABLE;
await initMigrationsTable({
migrationsTableName,
local,
remote,
config,
name: database,
persistTo,
preview
});
const unappliedMigrations = (await getUnappliedMigrations({
migrationsTableName,
migrationsPath,
local,
remote,
config,
name: database,
persistTo,
preview
})).map((migration) => {
return {
Name: migration
};
});
if (unappliedMigrations.length === 0) {
logger.log("\u2705 No migrations to apply!");
return;
}
logger.log("Migrations to be applied:");
logger.table(unappliedMigrations.map((m6) => ({ Name: m6.Name })));
}
});
}
});
// src/d1/timeTravel/index.ts
var d1TimeTravelNamespace;
var init_timeTravel = __esm({
"src/d1/timeTravel/index.ts"() {
init_import_meta_url();
init_create_command();
d1TimeTravelNamespace = createNamespace({
metadata: {
description: "Use Time Travel to restore, fork or copy a database at a specific point-in-time",
status: "stable",
owner: "Product: D1"
}
});
}
});
// src/d1/timeTravel/utils.ts
function isISODate(date) {
return ISO_DATE_REG_EXP.test(date);
}
function getLocalISOString(date) {
const offset = date.getTimezoneOffset();
const offsetAbs = Math.abs(offset);
const isoString = new Date(date.getTime() - offset * 60 * 1e3).toISOString();
return `${isoString.slice(0, -1)}${offset > 0 ? "-" : "+"}${String(
Math.floor(offsetAbs / 60)
).padStart(2, "0")}:${String(offsetAbs % 60).padStart(2, "0")}`;
}
var getBookmarkIdFromTimestamp, throwIfDatabaseIsAlpha, ISO_DATE_REG_EXP, convertTimestampToISO;
var init_utils5 = __esm({
"src/d1/timeTravel/utils.ts"() {
init_import_meta_url();
init_cfetch();
init_errors();
init_utils3();
getBookmarkIdFromTimestamp = /* @__PURE__ */ __name(async (complianceConfig, accountId, databaseId, timestamp) => {
const searchParams = new URLSearchParams();
if (timestamp) {
searchParams.append("timestamp", convertTimestampToISO(timestamp));
}
const bookmarkResult = await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database/${databaseId}/time_travel/bookmark?${searchParams.toString()}`,
{
headers: {
"Content-Type": "application/json"
}
}
);
return bookmarkResult;
}, "getBookmarkIdFromTimestamp");
throwIfDatabaseIsAlpha = /* @__PURE__ */ __name(async (complianceConfig, accountId, databaseId) => {
const dbInfo = await getDatabaseInfoFromIdOrName(
complianceConfig,
accountId,
databaseId
);
if (dbInfo.version === "alpha") {
throw new UserError(
"Time travel is not available for alpha D1 databases. You will need to migrate to a new database for access to this feature."
);
}
}, "throwIfDatabaseIsAlpha");
ISO_DATE_REG_EXP = new RegExp(
/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/
);
__name(isISODate, "isISODate");
__name(getLocalISOString, "getLocalISOString");
convertTimestampToISO = /* @__PURE__ */ __name((timestamp) => {
const parsedTimestamp = isISODate(timestamp) ? new Date(timestamp) : new Date(Number(timestamp.length === 10 ? timestamp + "000" : timestamp));
if (parsedTimestamp.toString() === "Invalid Date") {
throw new UserError(
`Invalid timestamp '${timestamp}'. Please provide a valid Unix timestamp or ISO string, for example: ${getLocalISOString(
/* @__PURE__ */ new Date()
)}
For accepted format, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format`
);
}
const now = /* @__PURE__ */ new Date();
const thirtyDaysAgo = /* @__PURE__ */ new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
if (parsedTimestamp > now) {
throw new UserError(
`Invalid timestamp '${timestamp}'. Please provide a timestamp in the past`
);
}
if (parsedTimestamp < thirtyDaysAgo) {
throw new UserError(
`Invalid timestamp '${timestamp}'. Please provide a timestamp within the last 30 days`
);
}
return parsedTimestamp.toISOString();
}, "convertTimestampToISO");
}
});
// src/d1/timeTravel/info.ts
var d1TimeTravelInfoCommand;
var init_info2 = __esm({
"src/d1/timeTravel/info.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_utils3();
init_utils5();
d1TimeTravelInfoCommand = createCommand({
metadata: {
description: "Retrieve information about a database at a specific point-in-time using Time Travel",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
database: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
timestamp: {
type: "string",
description: "Accepts a Unix (seconds from epoch) or RFC3339 timestamp (e.g. 2023-07-13T08:46:42.228Z) to retrieve a bookmark for"
},
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
positionalArgs: ["database"],
async handler({ database, json, timestamp }, { config }) {
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(config, accountId, database);
await throwIfDatabaseIsAlpha(config, accountId, db.uuid);
const result = await getBookmarkIdFromTimestamp(
config,
accountId,
db.uuid,
timestamp
);
if (json) {
logger.log(JSON.stringify(result, null, 2));
} else {
logger.log("\u{1F6A7} Time Traveling...");
logger.log(
timestamp ? `\u26A0\uFE0F Timestamp '${timestamp}' corresponds with bookmark '${result.bookmark}'` : `\u26A0\uFE0F The current bookmark is '${result.bookmark}'`
);
logger.log(`\u26A1\uFE0F To restore to this specific bookmark, run:
\`wrangler d1 time-travel restore ${database} --bookmark=${result.bookmark}\`
`);
}
}
});
}
});
// src/d1/timeTravel/restore.ts
var d1TimeTravelRestoreCommand, handleRestore;
var init_restore = __esm({
"src/d1/timeTravel/restore.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_user2();
init_utils3();
init_utils5();
d1TimeTravelRestoreCommand = createCommand({
metadata: {
description: "Restore a database back to a specific point-in-time",
status: "stable",
owner: "Product: D1"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
database: {
type: "string",
demandOption: true,
description: "The name or binding of the DB"
},
bookmark: {
type: "string",
description: "Bookmark to use for time travel"
},
timestamp: {
type: "string",
description: "Accepts a Unix (seconds from epoch) or RFC3339 timestamp (e.g. 2023-07-13T08:46:42.228Z) to retrieve a bookmark for"
},
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
positionalArgs: ["database"],
validateArgs(args) {
if (args.timestamp && args.bookmark) {
throw new UserError(
"Provide either a timestamp, or a bookmark - not both."
);
} else if (!args.timestamp && !args.bookmark) {
throw new UserError("Provide either a timestamp or a bookmark");
}
},
async handler({ database, json, timestamp, bookmark }, { config }) {
const accountId = await requireAuth(config);
const db = await getDatabaseByNameOrBinding(config, accountId, database);
await throwIfDatabaseIsAlpha(config, accountId, db.uuid);
const searchParams = new URLSearchParams();
if (timestamp) {
const bookmarkResult = await getBookmarkIdFromTimestamp(
config,
accountId,
db.uuid,
timestamp
);
searchParams.set("bookmark", bookmarkResult.bookmark);
} else if (bookmark) {
searchParams.set("bookmark", bookmark);
}
if (json) {
const result = await handleRestore(
config,
accountId,
db.uuid,
searchParams
);
logger.log(JSON.stringify(result, null, 2));
} else {
logger.log(`\u{1F6A7} Restoring database ${database} from bookmark ${searchParams.get(
"bookmark"
)}
`);
logger.log(`\u26A0\uFE0F This will overwrite all data in database ${database}.
In-flight queries and transactions will be cancelled.
`);
if (await confirm("OK to proceed (y/N)", { defaultValue: false })) {
logger.log("\u26A1\uFE0F Time travel in progress...");
const result = await handleRestore(
config,
accountId,
db.uuid,
searchParams
);
logger.log(`\u2705 Database ${database} restored back to bookmark ${result.bookmark}
`);
logger.log(
`\u21A9\uFE0F To undo this operation, you can restore to the previous bookmark: ${result.previous_bookmark}`
);
}
}
}
});
handleRestore = /* @__PURE__ */ __name(async (complianceConfig, accountId, databaseId, searchParams) => {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/d1/database/${databaseId}/time_travel/restore?${searchParams.toString()}`,
{
headers: {
"Content-Type": "application/json"
},
method: "POST"
}
);
}, "handleRestore");
}
});
// src/utils/getScriptName.ts
function getScriptName(args, config) {
return args.name ?? config.name;
}
var init_getScriptName = __esm({
"src/utils/getScriptName.ts"() {
init_import_meta_url();
__name(getScriptName, "getScriptName");
}
});
// src/delete.ts
async function deleteSiteNamespaceIfExisting(complianceConfig, scriptName, accountId) {
const title = `__${scriptName}-workers_sites_assets`;
const previewTitle = `__${scriptName}-workers_sites_assets_preview`;
const allNamespaces = await listKVNamespaces(complianceConfig, accountId);
const namespacesToDelete = allNamespaces.filter(
(ns) => ns.title === title || ns.title === previewTitle
);
for (const ns of namespacesToDelete) {
await deleteKVNamespace(complianceConfig, accountId, ns.id);
logger.log(`\u{1F300} Deleted asset namespace for Workers Site "${ns.title}"`);
}
}
function renderScriptName(details) {
let service;
let environment;
if ("script" in details) {
service = details.script;
} else {
service = details.service;
environment = details.environment;
}
return environment ? `${service} (${environment})` : service;
}
function isUsedAsServiceBinding(references) {
return (references.services?.incoming.length || 0) > 0;
}
function isUsedByPagesFunction(references) {
return references.services?.pages_function === true;
}
function isUsedAsDurableObjectNamespace(references, scriptName) {
return (references.durable_objects?.filter((ref) => ref.service !== scriptName)?.length || 0) > 0;
}
function isUsedAsDispatchOutbound(references) {
return references.dispatch_outbounds?.length || 0;
}
function isUsedAsTailConsumer(tailProducers) {
return tailProducers.length > 0;
}
async function checkAndConfirmForceDeleteIfNecessary(complianceConfig, scriptName, accountId) {
const references = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/scripts/${scriptName}/references`
);
const tailProducers = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/tails/by-consumer/${scriptName}`
);
const isDependentService = isUsedAsServiceBinding(references) || isUsedByPagesFunction(references) || isUsedAsDurableObjectNamespace(references, scriptName) || isUsedAsDispatchOutbound(references) || isUsedAsTailConsumer(tailProducers);
if (!isDependentService) {
return false;
}
const dependentMessages = [];
for (const serviceBindingReference of references.services?.incoming || []) {
const dependentScript = renderScriptName(serviceBindingReference);
dependentMessages.push(
`- Worker ${dependentScript} uses this Worker as a Service Binding`
);
}
if (isUsedByPagesFunction(references)) {
dependentMessages.push(
`- A Pages project has a Service Binding to this Worker`
);
}
for (const implementedDOBindingReference of references.durable_objects || []) {
if (implementedDOBindingReference.service === scriptName) {
continue;
}
const dependentScript = renderScriptName(implementedDOBindingReference);
dependentMessages.push(
`- Worker ${dependentScript} has a binding to the Durable Object Namespace "${implementedDOBindingReference.durable_object_namespace_name}" implemented by this Worker`
);
}
for (const dispatchNamespaceOutboundReference of references.dispatch_outbounds || []) {
const dependentScript = renderScriptName(
dispatchNamespaceOutboundReference
);
dependentMessages.push(
`- Worker ${dependentScript} uses this Worker as an Outbound Worker for the Dynamic Dispatch Namespace "${dispatchNamespaceOutboundReference.namespace}"`
);
}
for (const consumingTail of tailProducers) {
const dependentScript = renderScriptName(consumingTail.producer);
dependentMessages.push(
`- Worker ${dependentScript} uses this Worker as a Tail Worker`
);
}
const extraConfirmed = await confirm(`${scriptName} is currently in use by other Workers:
${dependentMessages.join("\n")}
You can still delete this Worker, but doing so WILL BREAK the Workers that depend on it. This will cause unexpected failures, and cannot be undone.
Are you sure you want to continue?`);
return extraConfirmed ? true : null;
}
var import_assert4, deleteCommand3;
var init_delete3 = __esm({
"src/delete.ts"() {
init_import_meta_url();
import_assert4 = __toESM(require("assert"));
init_cfetch();
init_config2();
init_create_command();
init_dialogs();
init_errors();
init_helpers4();
init_logger();
init_metrics();
init_user2();
init_getScriptName();
deleteCommand3 = createCommand({
metadata: {
description: "\u{1F5D1} Delete a Worker from Cloudflare",
owner: "Workers: Authoring and Testing",
status: "stable"
},
args: {
script: {
describe: "The path to an entry point for your worker",
type: "string",
requiresArg: true
},
name: {
describe: "Name of the worker",
type: "string",
requiresArg: true
},
"dry-run": {
describe: "Don't actually delete",
type: "boolean"
},
force: {
describe: "Delete even if doing so will break other Workers that depend on this one",
type: "boolean"
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
positionalArgs: ["script"],
async handler(args, { config }) {
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages project delete` instead.",
{ telemetryMessage: true }
);
}
sendMetricsEvent(
"delete worker script",
{},
{ sendMetrics: config.send_metrics }
);
const accountId = args.dryRun ? void 0 : await requireAuth(config);
const scriptName = getScriptName(args, config);
if (!scriptName) {
throw new UserError(
`A worker name must be defined, either via --name, or in your ${configFileName(config.configPath)} file`,
{
telemetryMessage: "`A worker name must be defined, either via --name, or in your config file"
}
);
}
if (args.dryRun) {
logger.log(`--dry-run: exiting now.`);
return;
}
(0, import_assert4.default)(accountId, "Missing accountId");
const confirmed = args.force || await confirm(
`Are you sure you want to delete ${scriptName}? This action cannot be undone.`
);
if (confirmed) {
const needsForceDelete = args.force || await checkAndConfirmForceDeleteIfNecessary(
config,
scriptName,
accountId
);
if (needsForceDelete === null) {
return;
}
await fetchResult(
config,
`/accounts/${accountId}/workers/services/${scriptName}`,
{ method: "DELETE" },
new URLSearchParams({ force: needsForceDelete.toString() })
);
await deleteSiteNamespaceIfExisting(config, scriptName, accountId);
logger.log("Successfully deleted", scriptName);
}
}
});
__name(deleteSiteNamespaceIfExisting, "deleteSiteNamespaceIfExisting");
__name(renderScriptName, "renderScriptName");
__name(isUsedAsServiceBinding, "isUsedAsServiceBinding");
__name(isUsedByPagesFunction, "isUsedByPagesFunction");
__name(isUsedAsDurableObjectNamespace, "isUsedAsDurableObjectNamespace");
__name(isUsedAsDispatchOutbound, "isUsedAsDispatchOutbound");
__name(isUsedAsTailConsumer, "isUsedAsTailConsumer");
__name(checkAndConfirmForceDeleteIfNecessary, "checkAndConfirmForceDeleteIfNecessary");
}
});
// src/deployment-bundle/guess-worker-format.ts
async function guessWorkerFormat(entryFile, entryWorkingDirectory, tsconfig) {
const parsedEntryPath = import_node_path30.default.parse(entryFile);
if (parsedEntryPath.ext == ".py") {
logger.warn(
`The entrypoint ${import_node_path30.default.relative(
process.cwd(),
entryFile
)} defines a Python worker, support for Python workers is currently experimental.`
);
return { format: "modules", exports: [] };
}
const result = await esbuild2.build({
...COMMON_ESBUILD_OPTIONS,
entryPoints: [entryFile],
absWorkingDir: entryWorkingDirectory,
metafile: true,
bundle: false,
write: false,
...tsconfig && { tsconfig },
logLevel: "silent"
});
const metafile = result.metafile;
const { exports: exports2 } = getEntryPointFromMetafile(entryFile, metafile);
let guessedWorkerFormat;
if (exports2.length > 0) {
if (exports2.includes("default")) {
guessedWorkerFormat = "modules";
} else {
logger.warn(
`The entrypoint ${import_node_path30.default.relative(
process.cwd(),
entryFile
)} has exports like an ES Module, but hasn't defined a default export like a module worker normally would. Building the worker using "service-worker" format...`
);
guessedWorkerFormat = "service-worker";
}
} else {
guessedWorkerFormat = "service-worker";
}
return { format: guessedWorkerFormat, exports: exports2 };
}
var import_node_path30, esbuild2;
var init_guess_worker_format = __esm({
"src/deployment-bundle/guess-worker-format.ts"() {
init_import_meta_url();
import_node_path30 = __toESM(require("path"));
esbuild2 = __toESM(require("esbuild"));
init_logger();
init_bundle();
init_entry_point_from_metafile();
__name(guessWorkerFormat, "guessWorkerFormat");
}
});
// src/deployment-bundle/resolve-entry.ts
function resolveEntryWithScript(script) {
const file = import_path17.default.resolve(script);
const relativePath = import_path17.default.relative(process.cwd(), file) || ".";
return { absolutePath: file, relativePath };
}
function resolveEntryWithMain(main2, config) {
const projectRoot = import_path17.default.resolve(import_path17.default.dirname(config.userConfigPath ?? "."));
const entryRoot = import_path17.default.resolve(import_path17.default.dirname(config.configPath ?? "."));
const absolutePath = import_path17.default.resolve(entryRoot, main2);
const relativePath = import_path17.default.relative(entryRoot, absolutePath) || ".";
return { absolutePath, relativePath, projectRoot };
}
function resolveEntryWithEntryPoint(entryPoint, config) {
const projectRoot = import_path17.default.resolve(import_path17.default.dirname(config.userConfigPath ?? "."));
const entryRoot = import_path17.default.resolve(import_path17.default.dirname(config.configPath ?? "."));
const file = import_path17.default.extname(entryPoint) ? import_path17.default.resolve(entryPoint) : import_path17.default.resolve(entryPoint, "index.js");
const relativePath = import_path17.default.relative(entryRoot, file) || ".";
return { absolutePath: file, relativePath, projectRoot };
}
function resolveEntryWithAssets() {
const file = import_path17.default.resolve(getBasePath(), "templates/no-op-worker.js");
const relativePath = import_path17.default.relative(process.cwd(), file) || ".";
return { absolutePath: file, relativePath };
}
var import_path17;
var init_resolve_entry = __esm({
"src/deployment-bundle/resolve-entry.ts"() {
init_import_meta_url();
import_path17 = __toESM(require("path"));
init_paths();
__name(resolveEntryWithScript, "resolveEntryWithScript");
__name(resolveEntryWithMain, "resolveEntryWithMain");
__name(resolveEntryWithEntryPoint, "resolveEntryWithEntryPoint");
__name(resolveEntryWithAssets, "resolveEntryWithAssets");
}
});
// src/deployment-bundle/entry.ts
async function getEntry(args, config, command2) {
const entryPoint = config.site?.["entry-point"];
let paths;
if (args.script) {
paths = resolveEntryWithScript(args.script);
} else if (config.main !== void 0) {
paths = resolveEntryWithMain(config.main, config);
} else if (entryPoint) {
paths = resolveEntryWithEntryPoint(entryPoint, config);
} else if (args.assets || config.assets) {
paths = resolveEntryWithAssets();
} else {
if (config.pages_build_output_dir && command2 === "dev") {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages dev` instead.",
{ telemetryMessage: true }
);
}
const compatibilityDateStr = formatCompatibilityDate(/* @__PURE__ */ new Date());
const updateConfigMessage = /* @__PURE__ */ __name((snippet) => esm_default2`
${config.configPath ? `add the following to your "${configFileName(config.configPath)}" file:` : `create a "wrangler.jsonc" file containing:`}
\`\`\`
${formatConfigSnippet(
{
...config.name ? {} : { name: "worker-name" },
...config.compatibility_date ? {} : { compatibility_date: compatibilityDateStr },
...snippet
},
config.configPath
)}
\`\`\`
`, "updateConfigMessage");
const fullCommand = `${getNpxEquivalent()} wrangler ${command2}`;
throw new UserError(
esm_default2`
Missing entry-point to Worker script or to assets directory
If there is code to deploy, you can either:
- Specify an entry-point to your Worker script via the command line (ex: \`${fullCommand} src/index.ts\`)
- Or ${updateConfigMessage({ main: "src/index.ts" })}
If are uploading a directory of assets, you can either:
- Specify the path to the directory of assets via the command line: (ex: \`${fullCommand} --assets=./dist\`)
- Or ${updateConfigMessage({ assets: { directory: "./dist" } })}`,
{ telemetryMessage: "missing worker entrypoint or assets directory" }
);
}
await runCustomBuild(
paths.absolutePath,
paths.relativePath,
config.build,
config.configPath
);
const projectRoot = paths.projectRoot ?? process.cwd();
const { format: format9, exports: exports2 } = await guessWorkerFormat(
paths.absolutePath,
projectRoot,
config.tsconfig
);
const { localBindings } = partitionDurableObjectBindings(config);
if (format9 === "service-worker" && localBindings.length > 0) {
const errorMessage = "You seem to be trying to use Durable Objects in a Worker written as a service-worker.";
const addScriptName = `You can use Durable Objects defined in other Workers by specifying a \`script_name\` in your ${configFileName(config.configPath)} file, where \`script_name\` is the name of the Worker that implements that Durable Object. For example:`;
const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
const migrateText = "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
const migrateUrl = "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
throw new UserError(
`${errorMessage}
${addScriptName}
${addScriptNameExamples}
${migrateText}
${migrateUrl}`,
{ telemetryMessage: "tried to use DO with service worker" }
);
}
return {
file: paths.absolutePath,
projectRoot,
configPath: config.configPath,
format: format9,
moduleRoot: args.moduleRoot ?? config.base_dir ?? import_node_path31.default.dirname(paths.absolutePath),
name: config.name ?? "worker",
exports: exports2
};
}
function partitionDurableObjectBindings(config) {
const localBindings = [];
const remoteBindings = [];
for (const binding of config.durable_objects.bindings) {
if (binding.script_name === void 0 || binding.script_name === config.name) {
localBindings.push(binding);
} else {
remoteBindings.push(binding);
}
}
return { localBindings, remoteBindings };
}
function generateAddScriptNameExamples(localBindings) {
function exampleScriptName(binding_name) {
return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
}
__name(exampleScriptName, "exampleScriptName");
return localBindings.map(({ name: name2, class_name }) => {
const script_name = exampleScriptName(name2);
const currentBinding = `{ name = ${name2}, class_name = ${class_name} }`;
const fixedBinding = `{ name = ${name2}, class_name = ${class_name}, script_name = ${script_name} }`;
return `${currentBinding} ==> ${fixedBinding}`;
}).join("\n");
}
function getNpxEquivalent() {
switch (sniffUserAgent()) {
case "pnpm":
return "pnpm";
case "yarn":
return "yarn";
case "npm":
default:
return "npx";
}
}
var import_node_path31;
var init_entry = __esm({
"src/deployment-bundle/entry.ts"() {
init_import_meta_url();
import_node_path31 = __toESM(require("path"));
init_esm2();
init_config2();
init_errors();
init_package_manager();
init_compatibility_date();
init_guess_worker_format();
init_resolve_entry();
init_run_custom_build();
__name(getEntry, "getEntry");
__name(partitionDurableObjectBindings, "partitionDurableObjectBindings");
__name(generateAddScriptNameExamples, "generateAddScriptNameExamples");
__name(getNpxEquivalent, "getNpxEquivalent");
}
});
// src/match-tag.ts
async function verifyWorkerMatchesCITag(complianceConfig, accountId, workerName, configPath) {
const matchTag = getCIMatchTag();
logger.debug(
`Starting verifyWorkerMatchesCITag() with tag: ${matchTag}, name: ${workerName}`
);
if (!matchTag) {
logger.debug(
"No WRANGLER_CI_MATCH_TAG variable provided, aborting verifyWorkerMatchesCITag()"
);
return;
}
const envAccountID = getCloudflareAccountIdFromEnv();
if (accountId !== envAccountID) {
throw new FatalError(
`The \`account_id\` in your ${configFileName(configPath)} file must match the \`account_id\` for this account. Please update your ${configFileName(configPath)} file with \`${formatConfigSnippet({ account_id: envAccountID }, configPath, false)}\``
);
}
let tag;
try {
const worker = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/services/${workerName}`
);
tag = worker.default_environment.script.tag;
logger.debug(`API returned with tag: ${tag} for worker: ${workerName}`);
} catch (e7) {
logger.debug(e7);
if (e7.code === 10090) {
throw new FatalError(
`The name in your ${configFileName(configPath)} file (${workerName}) must match the name of your Worker. Please update the name field in your ${configFileName(configPath)} file.`
);
} else if (e7 instanceof APIError) {
throw new FatalError(
"An error occurred while trying to validate that the Worker name matches what is expected by the build system.\n" + e7.message + "\n" + e7.notes.map((note) => note.text).join("\n")
);
} else {
throw new FatalError(
"Wrangler cannot validate that your Worker name matches what is expected by the build system. Please retry the build. If the problem persists, please contact support."
);
}
}
if (tag !== matchTag) {
logger.debug(
`Failed to match Worker tag. The API returned "${tag}", but the CI system expected "${matchTag}"`
);
throw new FatalError(
`The name in your ${configFileName(configPath)} file (${workerName}) must match the name of your Worker. Please update the name field in your ${configFileName(configPath)} file.`
);
}
}
var init_match_tag = __esm({
"src/match-tag.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_misc_variables();
init_errors();
init_logger();
init_parse();
init_auth_variables();
__name(verifyWorkerMatchesCITag, "verifyWorkerMatchesCITag");
}
});
// src/output.ts
function writeOutput(entry) {
if (outputFilePath === void 0) {
outputFilePath = getOutputFilePath();
}
if (outputFilePath !== null) {
ensureDirectoryExistsSync(outputFilePath);
const entryJSON = JSON.stringify({
...entry,
timestamp: (/* @__PURE__ */ new Date()).toISOString()
});
(0, import_node_fs19.appendFileSync)(outputFilePath, entryJSON + "\n");
}
}
function getOutputFilePath() {
const outputFilePathFromEnv = getOutputFilePathFromEnv();
if (outputFilePathFromEnv) {
return outputFilePathFromEnv;
}
const outputFileDirectoryFromEnv = getOutputFileDirectoryFromEnv();
if (outputFileDirectoryFromEnv) {
const date = (/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-").replace(".", "_").replace("T", "_").replace("Z", "");
return (0, import_node_path32.resolve)(
outputFileDirectoryFromEnv,
`wrangler-output-${date}-${(0, import_node_crypto6.randomBytes)(3).toString("hex")}.json`
);
}
return null;
}
var import_node_crypto6, import_node_fs19, import_node_path32, outputFilePath;
var init_output = __esm({
"src/output.ts"() {
init_import_meta_url();
import_node_crypto6 = require("crypto");
import_node_fs19 = require("fs");
import_node_path32 = require("path");
init_misc_variables();
init_filesystem();
__name(writeOutput, "writeOutput");
outputFilePath = void 0;
__name(getOutputFilePath, "getOutputFilePath");
}
});
// src/utils/collectKeyValues.ts
function collectKeyValues(array) {
return array?.reduce((recordsToCollect, v7) => {
const [key, ...value] = v7.split(":");
recordsToCollect[key] = value.join(":");
return recordsToCollect;
}, {}) || {};
}
function collectPlainTextVars(array) {
return array?.reduce(
(recordsToCollect, v7) => {
const [key, ...value] = v7.split(":");
recordsToCollect[key] = { type: "plain_text", value: value.join(":") };
return recordsToCollect;
},
{}
) || {};
}
var init_collectKeyValues = __esm({
"src/utils/collectKeyValues.ts"() {
init_import_meta_url();
__name(collectKeyValues, "collectKeyValues");
__name(collectPlainTextVars, "collectPlainTextVars");
}
});
// src/utils/getRules.ts
function getRules(config) {
return config.rules ?? [];
}
var init_getRules = __esm({
"src/utils/getRules.ts"() {
init_import_meta_url();
__name(getRules, "getRules");
}
});
// src/deploy/index.ts
async function handleMaybeAssetsDeployment(assetDirectory, args) {
if (isNonInteractiveOrCI()) {
return args;
}
logger.log("");
if (!args.assets) {
const deployAssets = await confirm(
"It looks like you are trying to deploy a directory of static assets only. Is this correct?",
{ defaultValue: true }
);
logger.log("");
if (deployAssets) {
args.assets = assetDirectory;
args.script = void 0;
} else {
return args;
}
}
if (!args.name) {
const defaultName = process.cwd().split(import_node_path33.default.sep).pop()?.replace("_", "-");
const isValidName2 = defaultName && /^[a-zA-Z0-9-]+$/.test(defaultName);
const projectName = await prompt("What do you want to name your project?", {
defaultValue: isValidName2 ? defaultName : "my-project"
});
args.name = projectName;
logger.log("");
}
if (!args.compatibilityDate) {
const compatibilityDate = formatCompatibilityDate(/* @__PURE__ */ new Date());
args.compatibilityDate = compatibilityDate;
logger.log(
`${source_default.bold("No compatibility date found")} Defaulting to today:`,
compatibilityDate
);
logger.log("");
}
const writeConfig = await confirm(
`Do you want Wrangler to write a wrangler.json config file to store this configuration?
${source_default.dim("This will allow you to simply run `wrangler deploy` on future deployments.")}`
);
if (writeConfig) {
const configPath = import_node_path33.default.join(process.cwd(), "wrangler.jsonc");
const jsonString = JSON.stringify(
{
name: args.name,
compatibility_date: args.compatibilityDate,
assets: { directory: args.assets }
},
null,
2
);
(0, import_node_fs20.writeFileSync)(configPath, jsonString);
logger.log(`Wrote
${jsonString}
to ${source_default.bold(configPath)}.`);
logger.log(
`Please run ${source_default.bold("`wrangler deploy`")} instead of ${source_default.bold(`\`wrangler deploy ${args.assets}\``)} next time. Wrangler will automatically use the configuration saved to wrangler.jsonc.`
);
} else {
logger.log(
`You should run ${source_default.bold(
`wrangler deploy --name ${args.name} --compatibility-date ${args.compatibilityDate} --assets ${args.assets}`
)} next time to deploy this Worker without going through this flow again.`
);
}
logger.log("\nProceeding with deployment...\n");
return args;
}
var import_node_assert18, import_node_fs20, import_node_path33, deployCommand;
var init_deploy4 = __esm({
"src/deploy/index.ts"() {
init_import_meta_url();
import_node_assert18 = __toESM(require("assert"));
import_node_fs20 = require("fs");
import_node_path33 = __toESM(require("path"));
init_source();
init_assets();
init_config2();
init_create_command();
init_entry();
init_dialogs();
init_misc_variables();
init_errors();
init_is_interactive();
init_logger();
init_match_tag();
init_metrics();
init_output();
init_sites();
init_user2();
init_collectKeyValues();
init_compatibility_date();
init_getRules();
init_getScriptName();
init_isLegacyEnv();
init_deploy8();
deployCommand = createCommand({
metadata: {
description: "\u{1F199} Deploy a Worker to Cloudflare",
owner: "Workers: Deploy and Config",
status: "stable"
},
positionalArgs: ["script"],
args: {
script: {
describe: "The path to an entry point for your Worker",
type: "string",
requiresArg: true
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
// We want to have a --no-bundle flag, but yargs requires that
// we also have a --bundle flag (that it adds the --no to by itself)
// So we make a --bundle flag, but hide it, and then add a --no-bundle flag
// that's visible to the user but doesn't "do" anything.
bundle: {
describe: "Run Wrangler's compilation step before publishing",
type: "boolean",
hidden: true
},
"no-bundle": {
describe: "Skip internal build steps and directly deploy Worker",
type: "boolean",
default: false
},
outdir: {
describe: "Output directory for the bundled Worker",
type: "string",
requiresArg: true
},
outfile: {
describe: "Output file for the bundled worker",
type: "string",
requiresArg: true
},
"compatibility-date": {
describe: "Date to use for compatibility checks",
type: "string",
requiresArg: true
},
"compatibility-flags": {
describe: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
requiresArg: true,
array: true
},
latest: {
describe: "Use the latest version of the Workers runtime",
type: "boolean",
default: false
},
assets: {
describe: "Static assets to be served. Replaces Workers Sites.",
type: "string",
requiresArg: true
},
site: {
describe: "Root folder of static assets for Workers Sites",
type: "string",
requiresArg: true,
hidden: true,
deprecated: true
},
"site-include": {
describe: "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
type: "string",
requiresArg: true,
array: true,
hidden: true,
deprecated: true
},
"site-exclude": {
describe: "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
type: "string",
requiresArg: true,
array: true,
hidden: true,
deprecated: true
},
var: {
describe: "A key-value pair to be injected into the script as a variable",
type: "string",
requiresArg: true,
array: true
},
define: {
describe: "A key-value pair to be substituted in the script",
type: "string",
requiresArg: true,
array: true
},
alias: {
describe: "A module pair to be substituted in the script",
type: "string",
requiresArg: true,
array: true
},
triggers: {
describe: "cron schedules to attach",
alias: ["schedule", "schedules"],
type: "string",
requiresArg: true,
array: true
},
routes: {
describe: "Routes to upload",
alias: "route",
type: "string",
requiresArg: true,
array: true
},
domains: {
describe: "Custom domains to deploy to",
alias: "domain",
type: "string",
requiresArg: true,
array: true
},
"jsx-factory": {
describe: "The function that is called for each JSX element",
type: "string",
requiresArg: true
},
"jsx-fragment": {
describe: "The function that is called for each JSX fragment",
type: "string",
requiresArg: true
},
tsconfig: {
describe: "Path to a custom tsconfig.json file",
type: "string",
requiresArg: true
},
minify: {
describe: "Minify the Worker",
type: "boolean"
},
"node-compat": {
describe: "Enable Node.js compatibility",
type: "boolean",
hidden: true,
deprecated: true
},
"dry-run": {
describe: "Don't actually deploy",
type: "boolean"
},
metafile: {
describe: "Path to output build metadata from esbuild. If flag is used without a path, defaults to 'bundle-meta.json' inside the directory specified by --outdir.",
type: "string",
coerce: /* @__PURE__ */ __name((v7) => !v7 ? true : v7, "coerce")
},
"keep-vars": {
describe: "When not used (or set to false), Wrangler will delete all vars before setting those found in the Wrangler configuration.\nWhen used (and set to true), the environment variables are not deleted before the deployment.\nIf you set variables via the dashboard you probably want to use this flag.\nNote that secrets are never deleted by deployments.",
default: false,
type: "boolean"
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
},
logpush: {
type: "boolean",
describe: "Send Trace Events from this Worker to Workers Logpush.\nThis will not configure a corresponding Logpush job automatically."
},
"upload-source-maps": {
type: "boolean",
describe: "Include source maps when uploading this Worker."
},
"old-asset-ttl": {
describe: "Expire old assets in given seconds rather than immediate deletion.",
type: "number"
},
"dispatch-namespace": {
describe: "Name of a dispatch namespace to deploy the Worker to (Workers for Platforms)",
type: "string"
},
"experimental-auto-create": {
describe: "Automatically provision draft bindings with new resources",
type: "boolean",
default: true,
hidden: true,
alias: "x-auto-create"
},
"containers-rollout": {
describe: "Rollout strategy for Containers changes. If set to immediate, it will override `rollout_percentage_steps` if configured and roll out to 100% of instances in one step. ",
choices: ["immediate", "gradual"]
},
"experimental-deploy-remote-diff-check": {
describe: `Experimental: Enable The Deployment Remote Diff check`,
type: "boolean",
hidden: true,
alias: ["x-remote-diff-check"]
}
},
behaviour: {
useConfigRedirectIfAvailable: true,
overrideExperimentalFlags: /* @__PURE__ */ __name((args) => ({
MULTIWORKER: false,
RESOURCES_PROVISION: args.experimentalProvision ?? false,
REMOTE_BINDINGS: args.experimentalRemoteBindings ?? false,
DEPLOY_REMOTE_DIFF_CHECK: args.experimentalDeployRemoteDiffCheck ?? false
}), "overrideExperimentalFlags"),
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
validateArgs(args) {
if (args.nodeCompat) {
throw new UserError(
`The --node-compat flag is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`,
{ telemetryMessage: true }
);
}
},
async handler(args, { config }) {
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages deploy` instead.",
{ telemetryMessage: true }
);
}
const projectRoot = config.userConfigPath && import_node_path33.default.dirname(config.userConfigPath);
if (!config.configPath) {
if (args.script) {
try {
const stats = (0, import_node_fs20.statSync)(args.script);
if (stats.isDirectory()) {
args = await handleMaybeAssetsDeployment(args.script, args);
}
} catch (error2) {
if (error2 instanceof UserError) {
throw error2;
}
}
} else if (args.assets && (!args.compatibilityDate || !args.name)) {
args = await handleMaybeAssetsDeployment(args.assets, args);
}
}
const entry = await getEntry(args, config, "deploy");
validateAssetsArgsAndConfig(args, config);
const assetsOptions = getAssetsOptions(args, config);
if (args.latest) {
logger.warn(
`Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your ${configFileName(config.configPath)} file.`
);
}
const cliVars = collectKeyValues(args.var);
const cliDefines = collectKeyValues(args.define);
const cliAlias = collectKeyValues(args.alias);
const accountId = args.dryRun ? void 0 : await requireAuth(config);
const siteAssetPaths = getSiteAssetPaths(
config,
args.site,
args.siteInclude,
args.siteExclude
);
const beforeUpload = Date.now();
let name2 = getScriptName(args, config);
const ciOverrideName = getCIOverrideName();
let workerNameOverridden = false;
if (ciOverrideName !== void 0 && ciOverrideName !== name2) {
logger.warn(
`Failed to match Worker name. Your config file is using the Worker name "${name2}", but the CI system expected "${ciOverrideName}". Overriding using the CI provided Worker name. Workers Builds connected builds will attempt to open a pull request to resolve this config name mismatch.`
);
name2 = ciOverrideName;
workerNameOverridden = true;
}
if (!name2) {
throw new UserError(
'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
if (!args.dryRun) {
(0, import_node_assert18.default)(accountId, "Missing account ID");
await verifyWorkerMatchesCITag(
config,
accountId,
name2,
config.configPath
);
}
const { sourceMapSize, versionId, workerTag, targets } = await deploy({
config,
accountId,
name: name2,
rules: getRules(config),
entry,
env: args.env,
compatibilityDate: args.latest ? formatCompatibilityDate(/* @__PURE__ */ new Date()) : args.compatibilityDate,
compatibilityFlags: args.compatibilityFlags,
vars: cliVars,
defines: cliDefines,
alias: cliAlias,
triggers: args.triggers,
jsxFactory: args.jsxFactory,
jsxFragment: args.jsxFragment,
tsconfig: args.tsconfig,
routes: args.routes,
domains: args.domains,
assetsOptions,
legacyAssetPaths: siteAssetPaths,
legacyEnv: isLegacyEnv(config),
minify: args.minify,
isWorkersSite: Boolean(args.site || config.site),
outDir: args.outdir,
outFile: args.outfile,
dryRun: args.dryRun,
metafile: args.metafile,
noBundle: !(args.bundle ?? !config.no_bundle),
keepVars: args.keepVars,
logpush: args.logpush,
uploadSourceMaps: args.uploadSourceMaps,
oldAssetTtl: args.oldAssetTtl,
projectRoot,
dispatchNamespace: args.dispatchNamespace,
experimentalAutoCreate: args.experimentalAutoCreate,
containersRollout: args.containersRollout
});
writeOutput({
type: "deploy",
version: 1,
worker_name: name2 ?? null,
worker_tag: workerTag,
version_id: versionId,
targets,
wrangler_environment: args.env,
worker_name_overridden: workerNameOverridden
});
sendMetricsEvent(
"deploy worker script",
{
usesTypeScript: /\.tsx?$/.test(entry.file),
durationMs: Date.now() - beforeUpload,
sourceMapSize
},
{
sendMetrics: config.send_metrics
}
);
}
});
__name(handleMaybeAssetsDeployment, "handleMaybeAssetsDeployment");
}
});
// src/dispatch-namespace.ts
async function createWorkerNamespace(complianceConfig, accountId, name2) {
const namespace = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/dispatch/namespaces`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: name2 })
}
);
logger.log(
`Created dispatch namespace "${name2}" with ID "${namespace.namespace_id}"`
);
}
async function deleteWorkerNamespace(complianceConfig, accountId, name2) {
await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/dispatch/namespaces/${name2}`,
{ method: "DELETE" }
);
logger.log(`Deleted dispatch namespace "${name2}"`);
}
async function listWorkerNamespaces(complianceConfig, accountId) {
logger.log(
await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/dispatch/namespaces`,
{
headers: {
"Content-Type": "application/json"
}
}
)
);
}
async function getWorkerNamespaceInfo(complianceConfig, accountId, name2) {
logger.log(
await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/dispatch/namespaces/${name2}`,
{
headers: {
"Content-Type": "application/json"
}
}
)
);
}
async function renameWorkerNamespace(complianceConfig, accountId, oldName, newName) {
await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/dispatch/namespaces/${oldName}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: newName })
}
);
logger.log(`Renamed dispatch namespace "${oldName}" to "${newName}"`);
}
var dispatchNamespaceNamespace, dispatchNamespaceListCommand, dispatchNamespaceGetCommand, dispatchNamespaceCreateCommand, dispatchNamespaceDeleteCommand, dispatchNamespaceRenameCommand;
var init_dispatch_namespace = __esm({
"src/dispatch-namespace.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_metrics();
init_user2();
__name(createWorkerNamespace, "createWorkerNamespace");
__name(deleteWorkerNamespace, "deleteWorkerNamespace");
__name(listWorkerNamespaces, "listWorkerNamespaces");
__name(getWorkerNamespaceInfo, "getWorkerNamespaceInfo");
__name(renameWorkerNamespace, "renameWorkerNamespace");
dispatchNamespaceNamespace = createNamespace({
metadata: {
description: "\u{1F3D7}\uFE0F Manage dispatch namespaces",
owner: "Workers: Deploy and Config",
status: "stable"
}
});
dispatchNamespaceListCommand = createCommand({
metadata: {
description: "List all dispatch namespaces",
owner: "Workers: Deploy and Config",
status: "stable"
},
async handler(_4, { config }) {
const accountId = await requireAuth(config);
await listWorkerNamespaces(config, accountId);
sendMetricsEvent("list dispatch namespaces", {
sendMetrics: config.send_metrics
});
}
});
dispatchNamespaceGetCommand = createCommand({
metadata: {
description: "Get information about a dispatch namespace",
owner: "Workers: Deploy and Config",
status: "stable"
},
args: {
name: {
describe: "Name of the dispatch namespace",
type: "string",
demandOption: true
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
await getWorkerNamespaceInfo(config, accountId, args.name);
sendMetricsEvent("view dispatch namespace", {
sendMetrics: config.send_metrics
});
}
});
dispatchNamespaceCreateCommand = createCommand({
metadata: {
description: "Create a dispatch namespace",
owner: "Workers: Deploy and Config",
status: "stable"
},
args: {
name: {
describe: "Name of the dispatch namespace",
type: "string",
demandOption: true
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
await createWorkerNamespace(config, accountId, args.name);
sendMetricsEvent("create dispatch namespace", {
sendMetrics: config.send_metrics
});
}
});
dispatchNamespaceDeleteCommand = createCommand({
metadata: {
description: "Delete a dispatch namespace",
owner: "Workers: Deploy and Config",
status: "stable"
},
args: {
name: {
describe: "Name of the dispatch namespace",
type: "string",
demandOption: true
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
await deleteWorkerNamespace(config, accountId, args.name);
sendMetricsEvent("delete dispatch namespace", {
sendMetrics: config.send_metrics
});
}
});
dispatchNamespaceRenameCommand = createCommand({
metadata: {
description: "Rename a dispatch namespace",
owner: "Workers: Deploy and Config",
status: "stable"
},
args: {
oldName: {
describe: "Name of the dispatch namespace",
type: "string",
demandOption: true
},
newName: {
describe: "New name of the dispatch namespace",
type: "string",
demandOption: true
}
},
positionalArgs: ["oldName", "newName"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
await renameWorkerNamespace(config, accountId, args.oldName, args.newName);
sendMetricsEvent("rename dispatch namespace", {
sendMetrics: config.send_metrics
});
}
});
}
});
// src/docs/helpers.ts
async function runSearch(searchTerm) {
const id = "8MU1G3QO9P";
const index = "developers-cloudflare2";
const key = "045e8dbec8c137a52f0f56e196d7abe0";
const params = new URLSearchParams({
query: searchTerm,
hitsPerPage: "1",
getRankingInfo: "0"
});
(0, import_node_assert19.default)(id, "Missing Algolia App ID");
(0, import_node_assert19.default)(key, "Missing Algolia Key");
const searchResp = await (0, import_undici10.fetch)(
`https://${id}-dsn.algolia.net/1/indexes/${index}/query`,
{
method: "POST",
body: JSON.stringify({
params: params.toString()
}),
headers: {
"X-Algolia-API-Key": key,
"X-Algolia-Application-Id": id
}
}
);
if (!searchResp.ok) {
logger.error(`Could not search the docs. Please try again later.`);
return;
}
const searchData = await searchResp.json();
logger.debug("searchData: ", searchData);
if (searchData.hits[0]) {
return searchData.hits[0].url;
} else {
logger.error(
`Could not find docs for: ${searchTerm}. Please try again with another search term.`
);
return;
}
}
var import_node_assert19, import_undici10;
var init_helpers7 = __esm({
"src/docs/helpers.ts"() {
init_import_meta_url();
import_node_assert19 = __toESM(require("assert"));
import_undici10 = __toESM(require_undici());
init_logger();
__name(runSearch, "runSearch");
}
});
// src/docs/index.ts
var docs;
var init_docs = __esm({
"src/docs/index.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_metrics();
init_open_in_browser();
init_helpers7();
docs = createCommand({
metadata: {
description: "\u{1F4DA} Open Wrangler's command documentation in your browser\n",
owner: "Workers: Authoring and Testing",
status: "stable"
},
args: {
search: {
describe: "Enter search terms (e.g. the wrangler command) you want to know more about",
type: "string",
array: true
},
yes: {
alias: "y",
type: "boolean",
describe: "Takes you to the docs, even if search fails"
}
},
positionalArgs: ["search"],
async handler(args, { config }) {
let urlToOpen = args.yes || !args.search || args.search.length === 0 ? "https://developers.cloudflare.com/workers/wrangler/commands/" : "";
if (args.search && args.search.length > 0) {
const searchTerm = args.search.join(" ");
const searchResult = await runSearch(searchTerm);
urlToOpen = searchResult ?? urlToOpen;
}
if (!urlToOpen) {
return;
}
logger.log(`Opening a link in your default browser: ${urlToOpen}`);
await openInBrowser(urlToOpen);
sendMetricsEvent("view docs", {
sendMetrics: config.send_metrics
});
}
});
}
});
// src/hello-world/index.ts
async function usingLocalHelloWorldBinding(persistTo, config, closure) {
const persist = getLocalPersistencePath(persistTo, config);
const defaultPersistRoot = getDefaultPersistRoot(persist);
const mf = new import_miniflare14.Miniflare({
script: 'addEventListener("fetch", (e) => e.respondWith(new Response(null, { status: 404 })))',
defaultPersistRoot,
helloWorld: {
BINDING: {
enable_timer: false
}
}
});
const binding = await mf.getHelloWorldBinding("BINDING");
try {
return await closure(binding);
} finally {
await mf.dispose();
}
}
var import_miniflare14, helloWorldNamespace, helloWorldGetCommand, helloWorldSetCommand;
var init_hello_world = __esm({
"src/hello-world/index.ts"() {
init_import_meta_url();
import_miniflare14 = require("miniflare");
init_create_command();
init_get_local_persistence_path();
init_miniflare();
init_errors();
init_logger();
helloWorldNamespace = createNamespace({
metadata: {
description: `\u{1F44B} Example local commands. DO NOT USE`,
status: "experimental",
owner: "Workers: Authoring and Testing",
hidden: true
}
});
__name(usingLocalHelloWorldBinding, "usingLocalHelloWorldBinding");
helloWorldGetCommand = createCommand({
metadata: {
description: "Example local command - Get a value from the account",
status: "experimental",
owner: "Workers: Authoring and Testing",
hidden: true
},
positionalArgs: [],
args: {
remote: {
type: "boolean",
description: "Execute command against remote service",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
logger.log(`\u{1F44B} Getting value...`);
if (args.remote) {
throw new UserError("Not implemented", {
telemetryMessage: true
});
}
const value = await usingLocalHelloWorldBinding(
args.persistTo,
config,
async (helloWorld) => {
const result = await helloWorld.get();
return result.value;
}
);
if (!value) {
logger.log("Value not found");
} else {
logger.log(value);
}
}
});
helloWorldSetCommand = createCommand({
metadata: {
description: "Example local command - Set a value to the account",
status: "experimental",
owner: "Workers: Authoring and Testing",
hidden: true
},
positionalArgs: ["value"],
args: {
value: {
describe: "Value to set in the account",
type: "string",
demandOption: true,
requiresArg: true
},
remote: {
type: "boolean",
description: "Execute command against remote service",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
logger.log(`\u{1F44B} Updating value...`);
if (args.remote) {
throw new UserError("Not implemented", {
telemetryMessage: true
});
}
await usingLocalHelloWorldBinding(
args.persistTo,
config,
async (helloWorld) => {
await helloWorld.set(args.value);
}
);
logger.log("Updated");
}
});
}
});
// src/hyperdrive/client.ts
async function createConfig(config, body) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/hyperdrive/configs`,
{
method: "POST",
body: JSON.stringify(body)
}
);
}
async function deleteConfig(config, id) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/hyperdrive/configs/${id}`,
{
method: "DELETE"
}
);
}
async function getConfig(config, id) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/hyperdrive/configs/${id}`,
{
method: "GET"
}
);
}
async function listConfigs(config) {
const accountId = await requireAuth(config);
return await fetchPagedListResult(
config,
`/accounts/${accountId}/hyperdrive/configs`,
{
method: "GET"
}
);
}
async function patchConfig(config, id, body) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/hyperdrive/configs/${id}`,
{
method: "PATCH",
body: JSON.stringify(body)
}
);
}
var init_client3 = __esm({
"src/hyperdrive/client.ts"() {
init_import_meta_url();
init_cfetch();
init_user2();
__name(createConfig, "createConfig");
__name(deleteConfig, "deleteConfig");
__name(getConfig, "getConfig");
__name(listConfigs, "listConfigs");
__name(patchConfig, "patchConfig");
}
});
// src/hyperdrive/shared.ts
function capitalizeScheme(scheme) {
switch (scheme) {
case "mysql":
return "MySQL";
case "postgres":
case "postgresql":
return "PostgreSQL";
default:
return "";
}
}
function formatCachingOptions(cachingOptions) {
switch (cachingOptions?.disabled) {
case false: {
if (cachingOptions.stale_while_revalidate === 0) {
return `max_age: ${cachingOptions.max_age}, stale_while_revalidate: disabled`;
} else {
return `max_age: ${cachingOptions.max_age}, stale_while_revalidate: ${cachingOptions.stale_while_revalidate}`;
}
}
case void 0: {
return "enabled";
}
case true: {
return "disabled";
}
default:
return JSON.stringify(cachingOptions);
}
}
var init_shared = __esm({
"src/hyperdrive/shared.ts"() {
init_import_meta_url();
__name(capitalizeScheme, "capitalizeScheme");
__name(formatCachingOptions, "formatCachingOptions");
}
});
// src/hyperdrive/index.ts
function getOriginFromArgs(allowPartialOrigin, args) {
if (args.connectionString) {
const url4 = new URL(args.connectionString);
url4.protocol = url4.protocol.toLowerCase();
if (url4.port === "" && (url4.protocol == "postgresql:" || url4.protocol == "postgres:")) {
url4.port = "5432";
} else if (url4.port === "" && url4.protocol == "mysql:") {
url4.port = "3306";
}
if (url4.protocol === "") {
throw new UserError(
"You must specify the database protocol - e.g. 'postgresql'/'mysql'."
);
} else if (!url4.protocol.startsWith("postgresql") && !url4.protocol.startsWith("postgres") && !url4.protocol.startsWith("mysql")) {
throw new UserError(
"Only PostgreSQL-compatible or MySQL-compatible databases are currently supported."
);
} else if (url4.host === "") {
throw new UserError(
"You must provide a hostname or IP address in your connection string - e.g. 'user:password@database-hostname.example.com:5432/databasename"
);
} else if (url4.port === "") {
throw new UserError(
"You must provide a port number - e.g. 'user:password@database.example.com:port/databasename"
);
} else if (!url4.pathname) {
throw new UserError(
"You must provide a database name as the path component - e.g. example.com:port/databasename"
);
} else if (url4.username === "") {
throw new UserError(
"You must provide a username - e.g. 'user:password@database.example.com:port/databasename'"
);
} else if (url4.password === "") {
throw new UserError(
"You must provide a password - e.g. 'user:password@database.example.com:port/databasename' "
);
}
return {
host: url4.hostname,
port: parseInt(url4.port),
scheme: url4.protocol.replace(":", ""),
database: decodeURIComponent(url4.pathname.replace("/", "")),
user: decodeURIComponent(url4.username),
password: decodeURIComponent(url4.password)
};
}
if (!allowPartialOrigin) {
if (!args.originScheme) {
throw new UserError(
"You must specify the database protocol as --origin-scheme - e.g. 'postgresql'"
);
} else if (!args.database) {
throw new UserError("You must provide a database name");
} else if (!args.originUser) {
throw new UserError(
"You must provide a username for the origin database"
);
} else if (!args.originPassword) {
throw new UserError(
"You must provide a password for the origin database"
);
}
}
const databaseConfig = {
scheme: args.originScheme,
database: args.database,
user: args.originUser,
password: args.originPassword
};
let networkOrigin;
if (args.accessClientId || args.accessClientSecret) {
if (!args.accessClientId || !args.accessClientSecret) {
throw new UserError(
"You must provide both an Access Client ID and Access Client Secret when configuring Hyperdrive-over-Access"
);
}
if (!args.originHost || args.originHost == "") {
throw new UserError(
"You must provide an origin hostname for the database"
);
}
networkOrigin = {
access_client_id: args.accessClientId,
access_client_secret: args.accessClientSecret,
host: args.originHost
};
} else if (args.originHost || args.originPort) {
if (!args.originHost) {
throw new UserError(
"You must provide an origin hostname for the database"
);
}
if (!args.originPort) {
throw new UserError(
"You must provide a nonzero origin port for the database"
);
}
networkOrigin = {
host: args.originHost,
port: args.originPort
};
}
const origin = {
...databaseConfig,
...networkOrigin
};
if (JSON.stringify(origin) === "{}") {
return void 0;
} else {
return origin;
}
}
function getCacheOptionsFromArgs(args) {
const caching = {
disabled: args.cachingDisabled,
max_age: args.maxAge,
stale_while_revalidate: args.swr
};
if (JSON.stringify(caching) === "{}") {
return void 0;
} else {
return caching;
}
}
function getMtlsFromArgs(args) {
const mtls = {
ca_certificate_id: args.caCertificateId,
mtls_certificate_id: args.mtlsCertificateId,
sslmode: args.sslmode
};
if (JSON.stringify(mtls) === "{}") {
return void 0;
} else {
if (mtls.sslmode == "require" && mtls.ca_certificate_id?.trim()) {
throw new UserError("CA not allowed when sslmode = 'require' is set");
}
if ((mtls.sslmode == "verify-ca" || mtls.sslmode == "verify-full") && !mtls.ca_certificate_id?.trim()) {
throw new UserError(
"CA required when sslmode = 'verify-ca' or 'verify-full' is set"
);
}
return mtls;
}
}
function getOriginConnectionLimitFromArgs(args) {
return args.originConnectionLimit;
}
var hyperdriveNamespace, upsertOptions;
var init_hyperdrive = __esm({
"src/hyperdrive/index.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
hyperdriveNamespace = createNamespace({
metadata: {
description: "\u{1F680} Manage Hyperdrive databases",
status: "stable",
owner: "Product: Hyperdrive"
}
});
upsertOptions = /* @__PURE__ */ __name((defaultOriginScheme = void 0) => ({
"connection-string": {
type: "string",
description: "The connection string for the database you want Hyperdrive to connect to - ex: protocol://user:password@host:port/database",
group: "Configure using a connection string"
},
"origin-host": {
alias: "host",
type: "string",
description: "The host of the origin database",
conflicts: "connection-string",
group: "Configure using individual parameters [conflicts with --connection-string]"
},
"origin-port": {
alias: "port",
type: "number",
description: "The port number of the origin database",
conflicts: [
"connection-string",
"access-client-id",
"access-client-secret"
],
group: "Configure using individual parameters [conflicts with --connection-string]"
},
"origin-scheme": {
alias: "scheme",
type: "string",
choices: ["postgres", "postgresql", "mysql"],
description: "The scheme used to connect to the origin database",
group: "Configure using individual parameters [conflicts with --connection-string]",
default: defaultOriginScheme
},
database: {
type: "string",
description: "The name of the database within the origin database",
conflicts: "connection-string",
group: "Configure using individual parameters [conflicts with --connection-string]"
},
"origin-user": {
alias: "user",
type: "string",
description: "The username used to connect to the origin database",
conflicts: "connection-string",
group: "Configure using individual parameters [conflicts with --connection-string]"
},
"origin-password": {
alias: "password",
type: "string",
description: "The password used to connect to the origin database",
conflicts: "connection-string",
group: "Configure using individual parameters [conflicts with --connection-string]"
},
"access-client-id": {
type: "string",
description: "The Client ID of the Access token to use when connecting to the origin database",
conflicts: ["connection-string", "origin-port"],
implies: ["access-client-secret"],
group: "Hyperdrive over Access [conflicts with --connection-string, --origin-port]"
},
"access-client-secret": {
type: "string",
description: "The Client Secret of the Access token to use when connecting to the origin database",
conflicts: ["connection-string", "origin-port"],
group: "Hyperdrive over Access [conflicts with --connection-string, --origin-port]"
},
"caching-disabled": {
type: "boolean",
description: "Disables the caching of SQL responses",
group: "Caching Options"
},
"max-age": {
type: "number",
description: "Specifies max duration for which items should persist in the cache, cannot be set when caching is disabled",
group: "Caching Options"
},
swr: {
type: "number",
description: "Indicates the number of seconds cache may serve the response after it becomes stale, cannot be set when caching is disabled",
group: "Caching Options"
},
"ca-certificate-id": {
alias: "ca-certificate-uuid",
type: "string",
description: "Sets custom CA certificate when connecting to origin database. Must be valid UUID of already uploaded CA certificate."
},
"mtls-certificate-id": {
alias: "mtls-certificate-uuid",
type: "string",
description: "Sets custom mTLS client certificates when connecting to origin database. Must be valid UUID of already uploaded public/private key certificates."
},
sslmode: {
type: "string",
choices: ["require", "verify-ca", "verify-full"],
description: "Sets CA sslmode for connecting to database."
},
"origin-connection-limit": {
type: "number",
description: "The (soft) maximum number of connections that Hyperdrive may establish to the origin database"
}
}), "upsertOptions");
__name(getOriginFromArgs, "getOriginFromArgs");
__name(getCacheOptionsFromArgs, "getCacheOptionsFromArgs");
__name(getMtlsFromArgs, "getMtlsFromArgs");
__name(getOriginConnectionLimitFromArgs, "getOriginConnectionLimitFromArgs");
}
});
// src/hyperdrive/create.ts
var hyperdriveCreateCommand;
var init_create4 = __esm({
"src/hyperdrive/create.ts"() {
init_import_meta_url();
init_config2();
init_create_command();
init_logger();
init_getValidBindingName();
init_client3();
init_shared();
init_hyperdrive();
hyperdriveCreateCommand = createCommand({
metadata: {
description: "Create a Hyperdrive config",
status: "stable",
owner: "Product: Hyperdrive"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Hyperdrive config"
},
...upsertOptions("postgresql")
},
positionalArgs: ["name"],
async handler(args, { config }) {
const origin = getOriginFromArgs(false, args);
logger.log(`\u{1F6A7} Creating '${args.name}'`);
const database = await createConfig(config, {
name: args.name,
origin,
caching: getCacheOptionsFromArgs(args),
mtls: getMtlsFromArgs(args),
origin_connection_limit: getOriginConnectionLimitFromArgs(args)
});
logger.log(
`\u2705 Created new Hyperdrive ${capitalizeScheme(database.origin.scheme)} config: ${database.id}`
);
await updateConfigFile(
(name2) => ({
hyperdrive: [
{
binding: getValidBindingName(name2 ?? "HYPERDRIVE", "HYPERDRIVE"),
id: database.id
}
]
}),
config.configPath,
args.env
);
}
});
}
});
// src/hyperdrive/delete.ts
var hyperdriveDeleteCommand;
var init_delete4 = __esm({
"src/hyperdrive/delete.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client3();
hyperdriveDeleteCommand = createCommand({
metadata: {
description: "Delete a Hyperdrive config",
status: "stable",
owner: "Product: Hyperdrive"
},
args: {
id: {
type: "string",
demandOption: true,
description: "The ID of the Hyperdrive config"
}
},
positionalArgs: ["id"],
async handler({ id }, { config }) {
logger.log(`\u{1F5D1}\uFE0F Deleting Hyperdrive database config ${id}`);
await deleteConfig(config, id);
logger.log(`\u2705 Deleted`);
}
});
}
});
// src/hyperdrive/get.ts
var hyperdriveGetCommand;
var init_get = __esm({
"src/hyperdrive/get.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client3();
hyperdriveGetCommand = createCommand({
metadata: {
description: "Get a Hyperdrive config",
status: "stable",
owner: "Product: Hyperdrive"
},
args: {
id: {
type: "string",
demandOption: true,
description: "The ID of the Hyperdrive config"
}
},
positionalArgs: ["id"],
async handler({ id }, { config }) {
const database = await getConfig(config, id);
logger.log(JSON.stringify(database, null, 2));
}
});
}
});
// src/hyperdrive/list.ts
var hyperdriveListCommand;
var init_list4 = __esm({
"src/hyperdrive/list.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client3();
init_shared();
hyperdriveListCommand = createCommand({
metadata: {
description: "List Hyperdrive configs",
status: "stable",
owner: "Product: Hyperdrive"
},
args: {},
async handler(_4, { config }) {
logger.log(`\u{1F4CB} Listing Hyperdrive configs`);
const databases = await listConfigs(config);
logger.table(
databases.map((database) => ({
id: database.id,
name: database.name,
user: database.origin.user ?? "",
host: database.origin.host ?? "",
port: database.origin.port?.toString() ?? "",
scheme: capitalizeScheme(database.origin.scheme),
database: database.origin.database ?? "",
caching: formatCachingOptions(database.caching),
mtls: JSON.stringify(database.mtls),
origin_connection_limit: database.origin_connection_limit?.toString() ?? ""
}))
);
}
});
}
});
// src/hyperdrive/update.ts
var hyperdriveUpdateCommand;
var init_update = __esm({
"src/hyperdrive/update.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client3();
init_hyperdrive();
hyperdriveUpdateCommand = createCommand({
metadata: {
description: "Update a Hyperdrive config",
status: "stable",
owner: "Product: Hyperdrive"
},
args: {
id: {
type: "string",
demandOption: true,
description: "The ID of the Hyperdrive config"
},
name: {
type: "string",
description: "Give your config a new name"
},
...upsertOptions()
},
positionalArgs: ["id"],
async handler(args, { config }) {
const origin = getOriginFromArgs(true, args);
logger.log(`\u{1F6A7} Updating '${args.id}'`);
const updated = await patchConfig(config, args.id, {
name: args.name,
origin,
caching: getCacheOptionsFromArgs(args),
mtls: getMtlsFromArgs(args),
origin_connection_limit: getOriginConnectionLimitFromArgs(args)
});
logger.log(
`\u2705 Updated ${updated.id} Hyperdrive config
`,
JSON.stringify(updated, null, 2)
);
}
});
}
});
// src/kv/index.ts
var import_node_assert20, import_node_buffer4, import_consumers, import_node_string_decoder, kvNamespace, kvNamespaceNamespace, kvKeyNamespace, kvBulkNamespace, kvNamespaceCreateCommand, kvNamespaceListCommand, kvNamespaceDeleteCommand, kvNamespaceRenameCommand, kvKeyPutCommand, kvKeyListCommand, kvKeyGetCommand, kvKeyDeleteCommand, kvBulkGetCommand, kvBulkPutCommand, kvBulkDeleteCommand;
var init_kv = __esm({
"src/kv/index.ts"() {
init_import_meta_url();
import_node_assert20 = require("assert");
import_node_buffer4 = require("buffer");
import_consumers = require("stream/consumers");
import_node_string_decoder = require("string_decoder");
init_config2();
init_core2();
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_metrics();
init_parse();
init_user2();
init_getValidBindingName();
init_is_local();
init_helpers4();
kvNamespace = createNamespace({
metadata: {
description: "\u{1F5C2}\uFE0F Manage Workers KV Namespaces",
status: "stable",
owner: "Product: KV"
}
});
kvNamespaceNamespace = createNamespace({
metadata: {
description: `Interact with your Workers KV Namespaces`,
status: "stable",
owner: "Product: KV"
}
});
kvKeyNamespace = createNamespace({
metadata: {
description: `Individually manage Workers KV key-value pairs`,
status: "stable",
owner: "Product: KV"
}
});
kvBulkNamespace = createNamespace({
metadata: {
description: `Interact with multiple Workers KV key-value pairs at once`,
status: "stable",
owner: "Product: KV"
}
});
kvNamespaceCreateCommand = createCommand({
metadata: {
description: "Create a new namespace",
status: "stable",
owner: "Product: KV"
},
args: {
namespace: {
describe: "The name of the new namespace",
type: "string",
demandOption: true
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
}
},
positionalArgs: ["namespace"],
async handler(args) {
const config = readConfig(args);
const environment = args.env ? `${args.env}-` : "";
const preview = args.preview ? "_preview" : "";
const title = `${environment}${args.namespace}${preview}`;
const accountId = await requireAuth(config);
printResourceLocation("remote");
logger.log(`\u{1F300} Creating namespace with title "${title}"`);
const namespaceId = await createKVNamespace(config, accountId, title);
sendMetricsEvent("create kv namespace", {
sendMetrics: config.send_metrics
});
logger.log("\u2728 Success!");
const previewString = args.preview ? "preview_" : "";
await updateConfigFile(
(name2) => ({
kv_namespaces: [
{
binding: getValidBindingName(name2 ?? args.namespace, "KV"),
[`${previewString}id`]: namespaceId
}
]
}),
config.configPath,
args.env,
!args.preview
);
}
});
kvNamespaceListCommand = createCommand({
metadata: {
description: "Output a list of all KV namespaces associated with your account id",
status: "stable",
owner: "Product: KV"
},
args: {},
behaviour: { printBanner: false, printResourceLocation: false },
async handler(args) {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(
JSON.stringify(await listKVNamespaces(config, accountId), null, " ")
);
sendMetricsEvent("list kv namespaces", {
sendMetrics: config.send_metrics
});
}
});
kvNamespaceDeleteCommand = createCommand({
metadata: {
description: "Delete a given namespace.",
status: "stable",
owner: "Product: KV"
},
args: {
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to delete from"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to delete"
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
}
},
validateArgs(args) {
demandOneOfOption("binding", "namespace-id")(args);
},
async handler(args) {
const config = readConfig(args);
printResourceLocation("remote");
let id;
try {
id = getKVNamespaceId(args, config);
} catch (e7) {
throw new CommandLineArgsError(
"Not able to delete namespace.\n" + (e7.message ?? e7)
);
}
const accountId = await requireAuth(config);
logger.log(`Deleting KV namespace ${id}.`);
await deleteKVNamespace(config, accountId, id);
logger.log(`Deleted KV namespace ${id}.`);
sendMetricsEvent("delete kv namespace", {
sendMetrics: config.send_metrics
});
}
});
kvNamespaceRenameCommand = createCommand({
metadata: {
description: "Rename a KV namespace",
status: "stable",
owner: "Product: KV"
},
positionalArgs: ["old-name"],
args: {
"old-name": {
type: "string",
describe: "The current name (title) of the namespace to rename"
},
"namespace-id": {
type: "string",
describe: "The id of the namespace to rename"
},
"new-name": {
type: "string",
describe: "The new name for the namespace",
demandOption: true
}
},
validateArgs(args) {
if (args.oldName && args.namespaceId) {
throw new CommandLineArgsError(
"Cannot specify both old-name and --namespace-id. Use either old-name (as first argument) or --namespace-id flag, not both."
);
}
if (!args.namespaceId && !args.oldName) {
throw new CommandLineArgsError(
"Either old-name (as first argument) or --namespace-id must be specified"
);
}
if (args.newName && args.newName.length > 512) {
throw new CommandLineArgsError(
`new-name must be 512 characters or less (current: ${args.newName.length})`
);
}
},
async handler(args) {
const config = readConfig(args);
printResourceLocation("remote");
const accountId = await requireAuth(config);
let namespaceId = args.namespaceId;
if (!namespaceId && args.oldName) {
const namespaces = await listKVNamespaces(config, accountId);
const namespace = namespaces.find((ns) => ns.title === args.oldName);
if (!namespace) {
throw new UserError(
`No namespace found with the name "${args.oldName}". Use --namespace-id instead or check available namespaces with "wrangler kv namespace list".`
);
}
namespaceId = namespace.id;
}
(0, import_node_assert20.strict)(namespaceId, "namespaceId should be defined");
logger.log(`Renaming KV namespace ${namespaceId} to "${args.newName}".`);
const updatedNamespace = await updateKVNamespace(
config,
accountId,
namespaceId,
args.newName
);
logger.log(
`\u2728 Successfully renamed namespace to "${updatedNamespace.title}"`
);
}
});
kvKeyPutCommand = createCommand({
metadata: {
description: "Write a single key/value pair to the given namespace",
status: "stable",
owner: "Product: KV"
},
behaviour: {
printResourceLocation: true
},
positionalArgs: ["key", "value"],
args: {
key: {
type: "string",
describe: "The key to write to",
demandOption: true
},
value: {
type: "string",
describe: "The value to write"
},
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to write to"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to write to"
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
},
ttl: {
type: "number",
describe: "Time for which the entries should be visible"
},
expiration: {
type: "number",
describe: "Time since the UNIX epoch after which the entry expires"
},
metadata: {
type: "string",
describe: "Arbitrary JSON that is associated with a key",
coerce: /* @__PURE__ */ __name((jsonStr) => {
try {
return JSON.parse(jsonStr);
} catch {
}
}, "coerce")
},
path: {
type: "string",
requiresArg: true,
describe: "Read value from the file at a given path"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
validateArgs(args) {
demandOneOfOption("binding", "namespace-id")(args);
demandOneOfOption("value", "path")(args);
},
async handler({ key, ttl, expiration, metadata, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
const value = args.path ? readFileSyncToBuffer(args.path) : (
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
args.value
);
const metadataLog = metadata ? ` with metadata "${JSON.stringify(metadata)}"` : "";
if (args.path) {
logger.log(
`Writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}${metadataLog}.`
);
} else {
logger.log(
`Writing the value "${value}" to key "${key}" on namespace ${namespaceId}${metadataLog}.`
);
}
let metricEvent;
if (localMode) {
await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
(namespace) => namespace.put(key, new import_node_buffer4.Blob([value]).stream(), {
expiration,
expirationTtl: ttl,
metadata
})
);
metricEvent = "write kv key-value (local)";
} else {
const accountId = await requireAuth(config);
await putKVKeyValue(config, accountId, namespaceId, {
key,
value,
expiration,
expiration_ttl: ttl,
metadata
});
metricEvent = "write kv key-value";
}
sendMetricsEvent(metricEvent, {
sendMetrics: config.send_metrics
});
}
});
kvKeyListCommand = createCommand({
metadata: {
description: "Output a list of all keys in a given namespace",
status: "stable",
owner: "Product: KV"
},
behaviour: {
// implicitly expects to output JSON only
printResourceLocation: false,
printBanner: false
},
args: {
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to list"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to list"
},
preview: {
type: "boolean",
// In the case of listing keys we will default to non-preview mode
default: false,
describe: "Interact with a preview namespace"
},
prefix: {
type: "string",
requiresArg: true,
describe: "A prefix to filter listed keys"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
validateArgs(args) {
demandOneOfOption("binding", "namespace-id")(args);
},
async handler({ prefix, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
let result;
let metricEvent;
if (localMode) {
const listResult = await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
(namespace) => namespace.list({ prefix })
);
result = listResult.keys;
metricEvent = "list kv keys (local)";
} else {
const accountId = await requireAuth(config);
result = await listKVNamespaceKeys(
config,
accountId,
namespaceId,
prefix
);
metricEvent = "list kv keys";
}
logger.log(JSON.stringify(result, void 0, 2));
sendMetricsEvent(metricEvent, {
sendMetrics: config.send_metrics
});
}
});
kvKeyGetCommand = createCommand({
metadata: {
description: "Read a single value by key from the given namespace",
status: "stable",
owner: "Product: KV"
},
behaviour: {
printBanner: false,
printResourceLocation: false
},
positionalArgs: ["key"],
args: {
key: {
describe: "The key value to get.",
type: "string",
demandOption: true
},
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to get from"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to get from"
},
preview: {
type: "boolean",
// In the case of getting key values we will default to non-preview mode
default: false,
describe: "Interact with a preview namespace"
},
text: {
type: "boolean",
default: false,
describe: "Decode the returned value as a utf8 string"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
validateArgs(args) {
demandOneOfOption("binding", "namespace-id")(args);
},
async handler({ key, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
let bufferKVValue;
let metricEvent;
if (localMode) {
const val2 = await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
async (namespace) => {
const stream2 = await namespace.get(key, "stream");
return stream2 === null ? null : await (0, import_consumers.arrayBuffer)(stream2);
}
);
if (val2 === null) {
logger.log("Value not found");
return;
}
bufferKVValue = Buffer.from(val2);
metricEvent = "read kv value (local)";
} else {
const accountId = await requireAuth(config);
bufferKVValue = Buffer.from(
await getKVKeyValue(config, accountId, namespaceId, key)
);
metricEvent = "read kv value";
}
if (args.text) {
const decoder = new import_node_string_decoder.StringDecoder("utf8");
logger.log(decoder.write(bufferKVValue));
} else {
process.stdout.write(bufferKVValue);
}
sendMetricsEvent(metricEvent, {
sendMetrics: config.send_metrics
});
}
});
kvKeyDeleteCommand = createCommand({
metadata: {
description: "Remove a single key value pair from the given namespace",
status: "stable",
owner: "Product: KV"
},
behaviour: {
printResourceLocation: true
},
positionalArgs: ["key"],
args: {
key: {
describe: "The key value to delete.",
type: "string",
demandOption: true
},
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to delete from"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to delete from"
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler({ key, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
logger.log(`Deleting the key "${key}" on namespace ${namespaceId}.`);
let metricEvent;
if (localMode) {
await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
(namespace) => namespace.delete(key)
);
metricEvent = "delete kv key-value (local)";
} else {
const accountId = await requireAuth(config);
await deleteKVKeyValue(config, accountId, namespaceId, key);
metricEvent = "delete kv key-value";
}
sendMetricsEvent(metricEvent, {
sendMetrics: config.send_metrics
});
}
});
kvBulkGetCommand = createCommand({
metadata: {
description: "Gets multiple key-value pairs from a namespace",
status: "open-beta",
owner: "Product: KV"
},
behaviour: {
printBanner: false,
printResourceLocation: false
},
positionalArgs: ["filename"],
args: {
filename: {
describe: "The file containing the keys to get",
type: "string",
demandOption: true
},
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to get from"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to get from"
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler({ filename, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
const content = parseJSON(readFileSync6(filename), filename);
if (!Array.isArray(content)) {
throw new UserError(
`Unexpected JSON input from "${filename}".
Expected an array of strings but got:
${content}`
);
}
const errors = [];
const keysToGet = [];
for (const [index, item] of content.entries()) {
const key = typeof item !== "string" ? item?.name : item;
if (typeof key !== "string") {
errors.push(
`The item at index ${index} is type: "${typeof item}" - ${JSON.stringify(
item
)}`
);
continue;
}
keysToGet.push(key);
}
if (errors.length > 0) {
throw new UserError(
`Unexpected JSON input from "${filename}".
Expected an array of strings or objects with a "name" key.
` + errors.join("\n")
);
}
if (localMode) {
const result = await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
async (namespace) => {
const out = {};
for (const key of keysToGet) {
const value = await namespace.get(key, "text");
out[key] = {
value
};
}
return out;
}
);
logger.log(JSON.stringify(result, null, 2));
} else {
const accountId = await requireAuth(config);
logger.log(
JSON.stringify(
await getKVBulkKeyValue(config, accountId, namespaceId, keysToGet),
null,
2
)
);
}
logger.log("\nSuccess!");
}
});
kvBulkPutCommand = createCommand({
metadata: {
description: "Upload multiple key-value pairs to a namespace",
status: "stable",
owner: "Product: KV"
},
behaviour: {
printResourceLocation: true
},
positionalArgs: ["filename"],
args: {
filename: {
describe: "The file containing the key/value pairs to write",
type: "string",
demandOption: true
},
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to write to"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to write to"
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
},
ttl: {
type: "number",
describe: "Time for which the entries should be visible"
},
expiration: {
type: "number",
describe: "Time since the UNIX epoch after which the entry expires"
},
metadata: {
type: "string",
describe: "Arbitrary JSON that is associated with a key",
coerce: /* @__PURE__ */ __name((jsonStr) => {
try {
return JSON.parse(jsonStr);
} catch {
}
}, "coerce")
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler({ filename, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
const content = parseJSON(readFileSync6(filename), filename);
if (!Array.isArray(content)) {
throw new UserError(
`Unexpected JSON input from "${filename}".
Expected an array of key-value objects but got type "${typeof content}".`
);
}
let maxNumberOfErrorsReached = false;
const errors = [];
let maxNumberOfWarningsReached = false;
const warnings = [];
for (let i5 = 0; i5 < content.length; i5++) {
const keyValue = content[i5];
if (!isKVKeyValue(keyValue) && !maxNumberOfErrorsReached) {
if (errors.length === BATCH_MAX_ERRORS_WARNINGS) {
maxNumberOfErrorsReached = true;
errors.push("...");
} else {
errors.push(`The item at index ${i5} is ${JSON.stringify(keyValue)}`);
}
} else {
const props = unexpectedKVKeyValueProps(keyValue);
if (props.length > 0 && !maxNumberOfWarningsReached) {
if (warnings.length === BATCH_MAX_ERRORS_WARNINGS) {
maxNumberOfWarningsReached = true;
warnings.push("...");
} else {
warnings.push(
`The item at index ${i5} contains unexpected properties: ${JSON.stringify(
props
)}.`
);
}
}
}
}
if (warnings.length > 0) {
logger.warn(
`Unexpected key-value properties in "${filename}".
` + warnings.join("\n")
);
}
if (errors.length > 0) {
throw new UserError(
`Unexpected JSON input from "${filename}".
Each item in the array should be an object that matches:
interface KeyValue {
key: string;
value: string;
expiration?: number;
expiration_ttl?: number;
metadata?: object;
base64?: boolean;
}
` + errors.join("\n")
);
}
let metricEvent;
if (localMode) {
await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
async (namespace) => {
for (const value of content) {
let data = value.value;
if (value.base64) {
data = Buffer.from(data, "base64").toString();
}
await namespace.put(value.key, data, {
expiration: value.expiration,
expirationTtl: value.expiration_ttl,
metadata: value.metadata
});
}
}
);
metricEvent = "write kv key-values (bulk) (local)";
} else {
const accountId = await requireAuth(config);
await putKVBulkKeyValue(config, accountId, namespaceId, content);
metricEvent = "write kv key-values (bulk)";
}
sendMetricsEvent(metricEvent, {
sendMetrics: config.send_metrics
});
logger.log("Success!");
}
});
kvBulkDeleteCommand = createCommand({
metadata: {
description: "Delete multiple key-value pairs from a namespace",
status: "stable",
owner: "Product: KV"
},
behaviour: {
printResourceLocation: true
},
positionalArgs: ["filename"],
args: {
filename: {
describe: "The file containing the keys to delete",
type: "string",
demandOption: true
},
binding: {
type: "string",
requiresArg: true,
describe: "The binding name to the namespace to delete from"
},
"namespace-id": {
type: "string",
requiresArg: true,
describe: "The id of the namespace to delete from"
},
preview: {
type: "boolean",
describe: "Interact with a preview namespace"
},
force: {
type: "boolean",
alias: "f",
describe: "Do not ask for confirmation before deleting"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler({ filename, ...args }) {
const localMode = isLocal(args);
const config = readConfig(args);
const namespaceId = getKVNamespaceId(args, config);
if (!args.force) {
const result = await confirm(
`Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
);
if (!result) {
logger.log(`Not deleting keys read from "${filename}".`);
return;
}
}
const content = parseJSON(readFileSync6(filename), filename);
if (!Array.isArray(content)) {
throw new UserError(
`Unexpected JSON input from "${filename}".
Expected an array of strings but got:
${content}`
);
}
const errors = [];
const keysToDelete = [];
for (const [index, item] of content.entries()) {
const key = typeof item !== "string" ? item?.name : item;
if (typeof key !== "string") {
errors.push(
`The item at index ${index} is type: "${typeof item}" - ${JSON.stringify(
item
)}`
);
}
keysToDelete.push(key);
}
if (errors.length > 0) {
throw new UserError(
`Unexpected JSON input from "${filename}".
Expected an array of strings or objects with a "name" key.
` + errors.join("\n")
);
}
let metricEvent;
if (localMode) {
await usingLocalNamespace(
args.persistTo,
config,
namespaceId,
async (namespace) => {
for (const key of keysToDelete) {
await namespace.delete(key);
}
}
);
metricEvent = "delete kv key-values (bulk) (local)";
} else {
const accountId = await requireAuth(config);
await deleteKVBulkKeyValue(config, accountId, namespaceId, keysToDelete);
metricEvent = "delete kv key-values (bulk)";
}
sendMetricsEvent(metricEvent, {
sendMetrics: config.send_metrics
});
logger.log("Success!");
}
});
}
});
// src/metrics/commands.ts
var telemetryNamespace, metricsAlias, telemetryDisableCommand, telemetryEnableCommand, telemetryStatusCommand, logTelemetryStatus;
var init_commands = __esm({
"src/metrics/commands.ts"() {
init_import_meta_url();
init_source();
init_create_command();
init_misc_variables();
init_logger();
init_metrics_config();
telemetryNamespace = createNamespace({
metadata: {
description: "\u{1F4C8} Configure whether Wrangler collects telemetry",
owner: "Workers: Authoring and Testing",
status: "stable",
hidden: true
}
});
metricsAlias = createAlias({
aliasOf: "wrangler telemetry"
});
telemetryDisableCommand = createCommand({
metadata: {
description: "Disable Wrangler telemetry collection",
owner: "Workers: Authoring and Testing",
status: "stable"
},
async handler() {
updateMetricsPermission(false);
logTelemetryStatus(false);
logger.log(
"Wrangler is no longer collecting telemetry about your usage.\n"
);
}
});
telemetryEnableCommand = createCommand({
metadata: {
description: "Enable Wrangler telemetry collection",
owner: "Workers: Authoring and Testing",
status: "stable"
},
async handler() {
updateMetricsPermission(true);
logTelemetryStatus(true);
logger.log(
"Wrangler is now collecting telemetry about your usage. Thank you for helping make Wrangler better \u{1F9E1}\n"
);
}
});
telemetryStatusCommand = createCommand({
metadata: {
description: "Check whether Wrangler telemetry collection is enabled",
owner: "Workers: Authoring and Testing",
status: "stable"
},
async handler(_4, { config }) {
const savedConfig = readMetricsConfig();
const sendMetricsEnv = getWranglerSendMetricsFromEnv();
if (config.send_metrics !== void 0 || sendMetricsEnv !== void 0) {
const resolvedPermission = sendMetricsEnv ?? config.send_metrics;
logger.log(
`Status: ${resolvedPermission ? source_default.green("Enabled") : source_default.red("Disabled")} (set by ${sendMetricsEnv !== void 0 ? "environment variable" : "wrangler.toml"})
`
);
} else {
logTelemetryStatus(savedConfig.permission?.enabled ?? true);
}
logger.log(
"To configure telemetry globally on this machine, you can run `wrangler telemetry disable / enable`.\nYou can override this for individual projects with the environment variable `WRANGLER_SEND_METRICS=true/false`.\nLearn more at https://github.com/cloudflare/workers-sdk/tree/main/packages/wrangler/telemetry.md\n"
);
}
});
logTelemetryStatus = /* @__PURE__ */ __name((enabled) => {
logger.log(
`Status: ${enabled ? source_default.green("Enabled") : source_default.red("Disabled")}
`
);
}, "logTelemetryStatus");
}
});
// src/mtls-certificate/cli.ts
var mTlsCertificateUploadCommand, mTlsCertificateListCommand, mTlsCertificateDeleteCommand, mTlsCertificateNamespace;
var init_cli3 = __esm({
"src/mtls-certificate/cli.ts"() {
init_import_meta_url();
init_mtls_certificate();
init_create_command();
init_dialogs();
init_logger();
init_user2();
mTlsCertificateUploadCommand = createCommand({
metadata: {
description: "Upload an mTLS certificate",
owner: "Product: SSL",
status: "stable"
},
args: {
cert: {
describe: "The path to a certificate file (.pem) containing a chain of certificates to upload",
type: "string",
demandOption: true
},
key: {
describe: "The path to a file containing the private key for your leaf certificate",
type: "string",
demandOption: true
},
name: {
describe: "The name for the certificate",
type: "string"
}
},
async handler({ cert, key, name: name2 }, { config }) {
const accountId = await requireAuth(config);
logger.log(
name2 ? `Uploading mTLS Certificate ${name2}...` : `Uploading mTLS Certificate...`
);
const certResponse = await uploadMTlsCertificateFromFs(config, accountId, {
certificateChainFilename: cert,
privateKeyFilename: key,
name: name2
});
const expiresOn = new Date(certResponse.expires_on).toLocaleDateString();
logger.log(
name2 ? `Success! Uploaded mTLS Certificate ${name2}` : `Success! Uploaded mTLS Certificate`
);
logger.log(`ID: ${certResponse.id}`);
logger.log(`Issuer: ${certResponse.issuer}`);
logger.log(`Expires on ${expiresOn}`);
}
});
mTlsCertificateListCommand = createCommand({
metadata: {
description: "List uploaded mTLS certificates",
owner: "Product: SSL",
status: "stable"
},
async handler(_4, { config }) {
const accountId = await requireAuth(config);
const certificates = await listMTlsCertificates(config, accountId, {});
for (const certificate of certificates) {
logger.log(`ID: ${certificate.id}`);
if (certificate.name) {
logger.log(`Name: ${certificate.name}`);
}
logger.log(`Issuer: ${certificate.issuer}`);
logger.log(
`Created on: ${new Date(certificate.uploaded_on).toLocaleDateString()}`
);
logger.log(
`Expires on: ${new Date(certificate.expires_on).toLocaleDateString()}`
);
logger.log("\n");
}
}
});
mTlsCertificateDeleteCommand = createCommand({
metadata: {
description: "Delete an mTLS certificate",
owner: "Product: SSL",
status: "stable"
},
args: {
id: {
describe: "The id of the mTLS certificate to delete",
type: "string"
},
name: {
describe: "The name of the mTLS certificate record to delete",
type: "string"
}
},
async handler({ id, name: name2 }, { config }) {
const accountId = await requireAuth(config);
if (id && name2) {
return logger.error(`Error: can't provide both --id and --name.`);
} else if (!id && !name2) {
return logger.error(`Error: must provide --id or --name.`);
}
let certificate;
if (id) {
certificate = await getMTlsCertificate(config, accountId, id);
} else {
certificate = await getMTlsCertificateByName(
config,
accountId,
name2
);
}
const response = await confirm(
certificate.name ? `Are you sure you want to delete certificate ${certificate.id} (${certificate.name})?` : `Are you sure you want to delete certificate ${certificate.id}?`
);
if (!response) {
logger.log("Not deleting");
return;
}
await deleteMTlsCertificate(config, accountId, certificate.id);
logger.log(
certificate.name ? `Deleted certificate ${certificate.id} (${certificate.name}) successfully` : `Deleted certificate ${certificate.id} successfully`
);
}
});
mTlsCertificateNamespace = createNamespace({
metadata: {
description: "\u{1FAAA} Manage certificates used for mTLS connections",
owner: "Product: SSL",
status: "stable"
}
});
}
});
// src/pages/utils.ts
function isUrl(maybeUrl) {
if (!maybeUrl) {
return false;
}
try {
new URL(maybeUrl);
return true;
} catch {
return false;
}
}
function getPagesProjectRoot() {
const cwd2 = process.cwd();
if (projectRootCache !== void 0 && projectRootCacheCwd === cwd2) {
return projectRootCache;
}
const packagePath = findUpSync("package.json");
projectRootCache = packagePath ? import_node_path34.default.dirname(packagePath) : process.cwd();
projectRootCacheCwd = cwd2;
return projectRootCache;
}
function getPagesTmpDir() {
const projectRoot = getPagesProjectRoot();
if (tmpDirCache !== void 0 && tmpDirCacheProjectRoot === projectRoot) {
return tmpDirCache;
}
const tmpDir = getWranglerTmpDir(getPagesProjectRoot(), "pages");
tmpDirCache = tmpDir.path;
tmpDirCacheProjectRoot = projectRoot;
return tmpDirCache;
}
var import_node_path34, RUNNING_BUILDERS, CLEANUP_CALLBACKS, CLEANUP, projectRootCacheCwd, projectRootCache, tmpDirCacheProjectRoot, tmpDirCache;
var init_utils6 = __esm({
"src/pages/utils.ts"() {
init_import_meta_url();
import_node_path34 = __toESM(require("path"));
init_find_up();
init_paths();
RUNNING_BUILDERS = [];
CLEANUP_CALLBACKS = [];
CLEANUP = /* @__PURE__ */ __name(() => {
CLEANUP_CALLBACKS.forEach((callback) => callback());
RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
}, "CLEANUP");
__name(isUrl, "isUrl");
__name(getPagesProjectRoot, "getPagesProjectRoot");
__name(getPagesTmpDir, "getPagesTmpDir");
}
});
// src/pages/index.ts
var pagesNamespace, pagesFunctionsNamespace, pagesProjectNamespace, pagesDeploymentNamespace, pagesDownloadNamespace;
var init_pages = __esm({
"src/pages/index.ts"() {
init_import_meta_url();
init_create_command();
init_utils6();
pagesNamespace = createNamespace({
metadata: {
description: "\u26A1\uFE0F Configure Cloudflare Pages",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
}
});
pagesFunctionsNamespace = createNamespace({
metadata: {
description: "Helpers related to Pages Functions",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
}
});
pagesProjectNamespace = createNamespace({
metadata: {
description: "Interact with your Pages projects",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
}
});
pagesDeploymentNamespace = createNamespace({
metadata: {
description: "Interact with the deployments of a project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
}
});
pagesDownloadNamespace = createNamespace({
metadata: {
description: "Download settings from your project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
}
});
process.on("SIGINT", () => {
CLEANUP();
process.exit();
});
process.on("SIGTERM", () => {
CLEANUP();
process.exit();
});
}
});
// src/api/pages/create-worker-bundle-contents.ts
async function createUploadWorkerBundleContents(workerBundle, config) {
const workerBundleFormData = createWorkerBundleFormData(workerBundle, config);
const metadata = JSON.parse(workerBundleFormData.get("metadata"));
if (config === void 0) {
delete metadata.bindings;
}
workerBundleFormData.set("metadata", JSON.stringify(metadata));
return await new import_undici11.Response(workerBundleFormData).blob();
}
function createWorkerBundleFormData(workerBundle, config) {
const mainModule = {
name: import_node_path35.default.basename(workerBundle.resolvedEntryPointPath),
filePath: workerBundle.resolvedEntryPointPath,
content: (0, import_node_fs21.readFileSync)(workerBundle.resolvedEntryPointPath, {
encoding: "utf-8"
}),
type: workerBundle.bundleType || "esm"
};
const placement = config?.placement?.mode === "smart" ? { mode: "smart", hint: config.placement.hint } : void 0;
return createWorkerUploadForm({
name: mainModule.name,
main: mainModule,
modules: workerBundle.modules,
bindings: getBindings(config, { pages: true }),
migrations: void 0,
compatibility_date: config?.compatibility_date,
compatibility_flags: config?.compatibility_flags,
keepVars: void 0,
keepSecrets: void 0,
keepBindings: void 0,
logpush: void 0,
sourceMaps: config?.upload_source_maps ? loadSourceMaps(mainModule, workerBundle.modules, workerBundle) : void 0,
placement,
tail_consumers: void 0,
limits: config?.limits,
assets: void 0,
observability: void 0
});
}
var import_node_fs21, import_node_path35, import_undici11;
var init_create_worker_bundle_contents = __esm({
"src/api/pages/create-worker-bundle-contents.ts"() {
init_import_meta_url();
import_node_fs21 = require("fs");
import_node_path35 = __toESM(require("path"));
import_undici11 = __toESM(require_undici());
init_bindings();
init_create_worker_upload_form();
init_source_maps();
__name(createUploadWorkerBundleContents, "createUploadWorkerBundleContents");
__name(createWorkerBundleFormData, "createWorkerBundleFormData");
}
});
// src/pages/functions/buildWorker.ts
function buildWorkerFromFunctions({
routesModule,
outfile = (0, import_node_path36.join)(getPagesTmpDir(), `./functionsWorker-${Math.random()}.js`),
outdir,
minify = false,
keepNames = true,
sourcemap = false,
fallbackService = "ASSETS",
watch: watch2 = false,
onEnd = /* @__PURE__ */ __name(() => {
}, "onEnd"),
buildOutputDirectory,
nodejsCompatMode,
functionsDirectory,
local,
defineNavigatorUserAgent,
checkFetch,
external,
metafile
}) {
const entry = {
file: (0, import_node_path36.resolve)(getBasePath(), "templates/pages-template-worker.ts"),
projectRoot: functionsDirectory,
configPath: void 0,
format: "modules",
moduleRoot: functionsDirectory,
exports: []
};
const moduleCollector = createModuleCollector({
entry,
findAdditionalModules: false
});
return bundleWorker(entry, outdir ? (0, import_node_path36.resolve)(outdir) : (0, import_node_path36.resolve)(outfile), {
bundle: true,
additionalModules: [],
moduleCollector,
inject: [routesModule],
...outdir ? { entryName: "index" } : { entryName: void 0 },
minify,
keepNames,
sourcemap,
watch: watch2,
nodejsCompatMode,
compatibilityDate: void 0,
compatibilityFlags: void 0,
define: {
__FALLBACK_SERVICE__: JSON.stringify(fallbackService)
},
alias: {},
doBindings: [],
// Pages functions don't support internal Durable Objects
workflowBindings: [],
// Pages functions don't support internal Workflows
external,
plugins: [buildNotifierPlugin(onEnd), assetsPlugin(buildOutputDirectory)],
isOutfile: !outdir,
checkFetch: local && checkFetch,
targetConsumer: local ? "dev" : "deploy",
local,
projectRoot: getPagesProjectRoot(),
defineNavigatorUserAgent,
jsxFactory: void 0,
jsxFragment: void 0,
tsconfig: void 0,
testScheduled: void 0,
metafile
});
}
function buildRawWorker({
workerScriptPath,
outfile = (0, import_node_path36.join)(getPagesTmpDir(), `./functionsWorker-${Math.random()}.js`),
outdir,
directory,
bundle = true,
externalModules,
minify = false,
keepNames = true,
sourcemap = false,
watch: watch2 = false,
plugins = [],
onEnd = /* @__PURE__ */ __name(() => {
}, "onEnd"),
nodejsCompatMode,
local,
additionalModules = [],
defineNavigatorUserAgent,
checkFetch,
external,
metafile
}) {
const entry = {
file: workerScriptPath,
projectRoot: (0, import_node_path36.resolve)(directory),
configPath: void 0,
format: "modules",
moduleRoot: (0, import_node_path36.resolve)(directory),
exports: []
};
const moduleCollector = externalModules ? noopModuleCollector : createModuleCollector({ entry, findAdditionalModules: false });
return bundleWorker(entry, outdir ? (0, import_node_path36.resolve)(outdir) : (0, import_node_path36.resolve)(outfile), {
bundle,
moduleCollector,
additionalModules,
minify,
keepNames,
sourcemap,
watch: watch2,
nodejsCompatMode,
compatibilityDate: void 0,
compatibilityFlags: void 0,
define: {},
alias: {},
doBindings: [],
// Pages functions don't support internal Durable Objects
workflowBindings: [],
// Pages functions don't support internal Workflows
external,
plugins: [
...plugins,
buildNotifierPlugin(onEnd),
...externalModules ? [
// In some cases, we want to enable bundling in esbuild so that we can flatten a shim around the entrypoint, but we still don't want to actually bundle in all the chunks that a Worker references.
// This plugin allows us to mark those chunks as external so they are not inlined.
{
name: "external-fixer",
setup(pluginBuild) {
pluginBuild.onResolve({ filter: /.*/ }, async (args) => {
if (externalModules.includes(
(0, import_node_path36.resolve)(args.resolveDir, args.path)
)) {
return { path: args.path, external: true };
}
});
}
}
] : []
],
isOutfile: !outdir,
checkFetch: local && checkFetch,
targetConsumer: local ? "dev" : "deploy",
local,
projectRoot: getPagesProjectRoot(),
defineNavigatorUserAgent,
metafile,
jsxFactory: void 0,
jsxFragment: void 0,
tsconfig: void 0,
testScheduled: void 0,
entryName: void 0,
inject: void 0
});
}
async function produceWorkerBundleForWorkerJSDirectory({
workerJSDirectory,
bundle,
buildOutputDirectory,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
sourceMaps
}) {
const entrypoint = (0, import_node_path36.resolve)((0, import_node_path36.join)(workerJSDirectory, "index.js"));
const additionalModules = await findAdditionalModules(
{
file: entrypoint,
projectRoot: (0, import_node_path36.resolve)(workerJSDirectory),
configPath: void 0,
format: "modules",
moduleRoot: (0, import_node_path36.resolve)(workerJSDirectory),
exports: []
},
[
{
type: "ESModule",
globs: ["**/*.js", "**/*.mjs"]
}
],
sourceMaps
);
if (!bundle) {
return {
modules: additionalModules,
dependencies: {},
resolvedEntryPointPath: entrypoint,
bundleType: "esm",
stop: /* @__PURE__ */ __name(async () => {
}, "stop"),
sourceMapPath: void 0
};
}
const outfile = (0, import_node_path36.join)(
getPagesTmpDir(),
`./bundledWorker-${Math.random()}.mjs`
);
const bundleResult = await buildRawWorker({
workerScriptPath: entrypoint,
bundle: true,
externalModules: additionalModules.map(
(m6) => (0, import_node_path36.join)(workerJSDirectory, m6.name)
),
outfile,
directory: buildOutputDirectory,
local: false,
sourcemap: true,
watch: false,
onEnd: /* @__PURE__ */ __name(() => {
}, "onEnd"),
nodejsCompatMode,
additionalModules,
defineNavigatorUserAgent,
checkFetch
});
return {
modules: bundleResult.modules,
dependencies: bundleResult.dependencies,
resolvedEntryPointPath: bundleResult.resolvedEntryPointPath,
bundleType: bundleResult.bundleType,
stop: bundleResult.stop,
sourceMapPath: bundleResult.sourceMapPath
};
}
function buildNotifierPlugin(onEnd) {
return {
name: "wrangler notifier and monitor",
setup(pluginBuild) {
pluginBuild.onEnd((result) => {
if (result.errors.length > 0 || result.warnings.length > 0) {
logBuildFailure(result.errors, result.warnings);
} else {
logger.log("\u2728 Compiled Worker successfully");
}
onEnd();
});
}
};
}
async function checkRawWorker(scriptPath4, nodejsCompatMode, onEnd) {
await (0, import_esbuild3.build)({
entryPoints: [scriptPath4],
write: false,
// we need it to be bundled so that any imports that are used are affected by the blocker plugin
bundle: true,
plugins: [
blockWorkerJsImports(nodejsCompatMode),
buildNotifierPlugin(onEnd)
],
logLevel: "silent"
});
}
function blockWorkerJsImports(nodejsCompatMode) {
return {
name: "block-worker-js-imports",
setup(build5) {
build5.onResolve({ filter: /.*/ }, (args) => {
if (args.kind === "entry-point") {
return {
path: args.path
};
}
if ((nodejsCompatMode === "v1" || nodejsCompatMode === "v2") && args.path.startsWith("node:") || args.path.startsWith("cloudflare:")) {
return {
path: args.path,
external: true
};
}
throw new FatalError(
"_worker.js is not being bundled by Wrangler but it is importing from another file.\nThis will throw an error if deployed.\nYou should bundle the Worker in a pre-build step, remove the import if it is unused, or ask Wrangler to bundle it by setting `--bundle`.",
1
);
});
}
};
}
function assetsPlugin(buildOutputDirectory) {
return {
name: "Assets",
setup(pluginBuild) {
const identifiers = /* @__PURE__ */ new Map();
pluginBuild.onResolve({ filter: /^assets:/ }, async (args) => {
const directory = (0, import_node_path36.resolve)(
args.resolveDir,
args.path.slice("assets:".length)
);
const exists = await (0, import_promises14.access)(directory).then(() => true).catch(() => false);
const isDirectory2 = exists && (await (0, import_promises14.lstat)(directory)).isDirectory();
if (!isDirectory2) {
return {
errors: [
{
text: `'${directory}' does not exist or is not a directory.`
}
]
};
}
identifiers.set(directory, import_node_crypto7.default.randomUUID());
if (!buildOutputDirectory) {
logger.warn(
"You're attempting to import static assets as part of your Pages Functions, but have not specified a directory in which to put them. You must use 'wrangler pages dev <directory>' rather than 'wrangler pages dev -- <command>' to import static assets in Functions."
);
}
return { path: directory, namespace: "assets" };
});
pluginBuild.onLoad(
{ filter: /.*/, namespace: "assets" },
async (args) => {
const identifier = identifiers.get(args.path);
if (buildOutputDirectory) {
const staticAssetsOutputDirectory = (0, import_node_path36.join)(
buildOutputDirectory,
"cdn-cgi",
"pages-plugins",
identifier
);
await (0, import_promises14.rm)(staticAssetsOutputDirectory, {
force: true,
recursive: true
});
await (0, import_promises14.cp)(args.path, staticAssetsOutputDirectory, {
force: true,
recursive: true
});
return {
// TODO: Watch args.path for changes and re-copy when updated
contents: `export const onRequest = ({ request, env, functionPath }) => {
const url = new URL(request.url);
const relativePathname = \`/\${url.pathname.replace(functionPath, "") || ""}\`.replace(/^\\/\\//, '/');
url.pathname = '/cdn-cgi/pages-plugins/${identifier}' + relativePathname;
request = new Request(url.toString(), request);
return env.ASSETS.fetch(request);
}`
};
}
}
);
}
};
}
var import_node_crypto7, import_promises14, import_node_path36, import_esbuild3;
var init_buildWorker = __esm({
"src/pages/functions/buildWorker.ts"() {
init_import_meta_url();
import_node_crypto7 = __toESM(require("crypto"));
import_promises14 = require("fs/promises");
import_node_path36 = require("path");
import_esbuild3 = require("esbuild");
init_bundle();
init_find_additional_modules();
init_module_collection();
init_errors();
init_logger();
init_paths();
init_utils6();
__name(buildWorkerFromFunctions, "buildWorkerFromFunctions");
__name(buildRawWorker, "buildRawWorker");
__name(produceWorkerBundleForWorkerJSDirectory, "produceWorkerBundleForWorkerJSDirectory");
__name(buildNotifierPlugin, "buildNotifierPlugin");
__name(checkRawWorker, "checkRawWorker");
__name(blockWorkerJsImports, "blockWorkerJsImports");
__name(assetsPlugin, "assetsPlugin");
}
});
// src/pages/functions/buildPlugin.ts
function buildPluginFromFunctions({
routesModule,
outdir,
minify = false,
keepNames = true,
sourcemap = false,
watch: watch2 = false,
onEnd = /* @__PURE__ */ __name(() => {
}, "onEnd"),
nodejsCompatMode,
functionsDirectory,
local,
defineNavigatorUserAgent,
checkFetch,
external
}) {
const entry = {
file: (0, import_node_path37.resolve)(getBasePath(), "templates/pages-template-plugin.ts"),
projectRoot: functionsDirectory,
configPath: void 0,
format: "modules",
moduleRoot: functionsDirectory,
exports: []
};
const moduleCollector = createModuleCollector({
entry,
findAdditionalModules: false
});
return bundleWorker(entry, (0, import_node_path37.resolve)(outdir), {
bundle: true,
additionalModules: [],
moduleCollector,
inject: [routesModule],
entryName: "index",
minify,
keepNames,
sourcemap,
watch: watch2,
// We don't currently have a mechanism for Plugins 'requiring' a specific compat date/flag,
// but if someone wants to publish a Plugin which does require this new `nodejs_compat` flag
// and they document that on their README.md, we should let them.
nodejsCompatMode: nodejsCompatMode ?? "v1",
compatibilityDate: void 0,
compatibilityFlags: void 0,
define: {},
alias: {},
doBindings: [],
// Pages functions don't support internal Durable Objects
workflowBindings: [],
// Pages functions don't support internal Workflows
external,
plugins: [
buildNotifierPlugin(onEnd),
{
name: "Assets",
setup(pluginBuild) {
pluginBuild.onResolve({ filter: /^assets:/ }, async (args) => {
const directory = (0, import_node_path37.resolve)(
args.resolveDir,
args.path.slice("assets:".length)
);
const exists = await (0, import_promises15.access)(directory).then(() => true).catch(() => false);
const isDirectory2 = exists && (await (0, import_promises15.lstat)(directory)).isDirectory();
if (!isDirectory2) {
return {
errors: [
{
text: `'${directory}' does not exist or is not a directory.`
}
]
};
}
const path72 = `assets:./${(0, import_node_path37.relative)(outdir, directory)}`;
return { path: path72, external: true, namespace: "assets" };
});
}
},
// TODO: Replace this with a proper outdir solution for Plugins
// But for now, let's just mark all wasm/bin files as external
{
name: "Mark externals",
setup(pluginBuild) {
pluginBuild.onResolve({ filter: /.*\.(wasm|bin)$/ }, async (args) => {
return {
external: true,
path: `./${(0, import_node_path37.relative)(
outdir,
(0, import_node_path37.resolve)(args.resolveDir, args.path)
)}`
};
});
}
}
],
checkFetch: local && checkFetch,
targetConsumer: local ? "dev" : "deploy",
local,
projectRoot: getPagesProjectRoot(),
defineNavigatorUserAgent,
jsxFactory: void 0,
jsxFragment: void 0,
tsconfig: void 0,
testScheduled: void 0,
isOutfile: void 0,
metafile: void 0
});
}
var import_promises15, import_node_path37;
var init_buildPlugin = __esm({
"src/pages/functions/buildPlugin.ts"() {
init_import_meta_url();
import_promises15 = require("fs/promises");
import_node_path37 = require("path");
init_bundle();
init_module_collection();
init_paths();
init_utils6();
init_buildWorker();
__name(buildPluginFromFunctions, "buildPluginFromFunctions");
}
});
// src/pages/functions/filepath-routing.ts
async function generateConfigFromFileTree({
baseDir,
baseURL
}) {
let routeEntries = [];
if (!baseURL.startsWith("/")) {
baseURL = `/${baseURL}`;
}
if (baseURL.endsWith("/")) {
baseURL = baseURL.slice(0, -1);
}
await forEachFile(baseDir, async (filepath) => {
const ext = import_node_path38.default.extname(filepath);
if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
const { metafile } = await (0, import_esbuild4.build)({
metafile: true,
write: false,
bundle: false,
entryPoints: [import_node_path38.default.resolve(filepath)]
}).catch((e7) => {
throw new FunctionsBuildError(e7.message);
});
const exportNames = [];
if (metafile) {
for (const output in metafile?.outputs) {
exportNames.push(...metafile.outputs[output].exports);
}
}
for (const exportName of exportNames) {
const [match2, method = ""] = exportName.match(
/^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
) ?? [];
if (match2) {
const basename7 = import_node_path38.default.basename(filepath).slice(0, -ext.length);
const isIndexFile = basename7 === "index";
const isMiddlewareFile = basename7 === "_middleware" || basename7 === "_middleware_";
let routePath = import_node_path38.default.relative(baseDir, filepath).slice(0, -ext.length);
let mountPath = import_node_path38.default.dirname(routePath);
if (isIndexFile || isMiddlewareFile) {
routePath = import_node_path38.default.dirname(routePath);
}
if (routePath === ".") {
routePath = "";
}
if (mountPath === ".") {
mountPath = "";
}
routePath = `${baseURL}/${routePath}`;
mountPath = `${baseURL}/${mountPath}`;
routePath = convertCatchallParams(routePath);
routePath = convertSimpleParams(routePath);
mountPath = convertCatchallParams(mountPath);
mountPath = convertSimpleParams(mountPath);
const modulePath = toUrlPath(import_node_path38.default.relative(baseDir, filepath));
const routeEntry = {
routePath: toUrlPath(routePath),
mountPath: toUrlPath(mountPath),
method: method.toUpperCase(),
[isMiddlewareFile ? "middleware" : "module"]: [
`${modulePath}:${exportName}`
]
};
routeEntries.push(routeEntry);
}
}
}
});
routeEntries = routeEntries.reduce(
(acc, { routePath, ...rest }) => {
const existingRouteEntry = acc.find(
(routeEntry) => routeEntry.routePath === routePath && routeEntry.method === rest.method
);
if (existingRouteEntry !== void 0) {
Object.assign(existingRouteEntry, rest);
} else {
acc.push({ routePath, ...rest });
}
return acc;
},
[]
);
routeEntries.sort((a5, b6) => compareRoutes(a5, b6));
return {
routes: routeEntries
};
}
function compareRoutes({ routePath: routePathA, method: methodA }, { routePath: routePathB, method: methodB }) {
function parseRoutePath(routePath) {
return routePath.slice(1).split("/").filter(Boolean);
}
__name(parseRoutePath, "parseRoutePath");
const segmentsA = parseRoutePath(routePathA);
const segmentsB = parseRoutePath(routePathB);
if (segmentsA.length !== segmentsB.length) {
return segmentsB.length - segmentsA.length;
}
for (let i5 = 0; i5 < segmentsA.length; i5++) {
const isWildcardA = segmentsA[i5].includes("*");
const isWildcardB = segmentsB[i5].includes("*");
const isParamA = segmentsA[i5].includes(":");
const isParamB = segmentsB[i5].includes(":");
if (isWildcardA && !isWildcardB) {
return 1;
}
if (!isWildcardA && isWildcardB) {
return -1;
}
if (isParamA && !isParamB) {
return 1;
}
if (!isParamA && isParamB) {
return -1;
}
}
if (methodA && !methodB) {
return -1;
}
if (!methodA && methodB) {
return 1;
}
return routePathA.localeCompare(routePathB);
}
async function forEachFile(baseDir, fn2) {
const searchPaths = [baseDir];
const returnValues = [];
while (isNotEmpty(searchPaths)) {
const cwd2 = searchPaths.shift();
const dir = await import_promises16.default.readdir(cwd2, { withFileTypes: true });
for (const entry of dir) {
const pathname = import_node_path38.default.join(cwd2, entry.name);
if (entry.isDirectory()) {
searchPaths.push(pathname);
} else if (entry.isFile()) {
returnValues.push(await fn2(pathname));
}
}
}
return returnValues;
}
function isNotEmpty(array) {
return array.length > 0;
}
function convertCatchallParams(routePath) {
return routePath.replace(/\[\[([^\]]+)\]\]/g, (_4, param) => {
if (validParamNameRegExp.test(param)) {
return `:${param}*`;
} else {
throw new FatalError(
`Invalid Pages function route parameter - "[[${param}]]". Parameters names must only contain alphanumeric and underscore characters.`
);
}
});
}
function convertSimpleParams(routePath) {
return routePath.replace(/\[([^\]]+)\]/g, (_4, param) => {
if (validParamNameRegExp.test(param)) {
return `:${param}`;
} else {
throw new FatalError(
`Invalid Pages function route parameter - "[${param}]". Parameter names must only contain alphanumeric and underscore characters.`
);
}
});
}
var import_promises16, import_node_path38, import_esbuild4, validParamNameRegExp;
var init_filepath_routing = __esm({
"src/pages/functions/filepath-routing.ts"() {
init_import_meta_url();
import_promises16 = __toESM(require("fs/promises"));
import_node_path38 = __toESM(require("path"));
import_esbuild4 = require("esbuild");
init_errors();
init_paths();
init_errors3();
__name(generateConfigFromFileTree, "generateConfigFromFileTree");
__name(compareRoutes, "compareRoutes");
__name(forEachFile, "forEachFile");
__name(isNotEmpty, "isNotEmpty");
validParamNameRegExp = /^[A-Za-z0-9_]+$/;
__name(convertCatchallParams, "convertCatchallParams");
__name(convertSimpleParams, "convertSimpleParams");
}
});
// src/pages/functions/identifiers.ts
var RESERVED_KEYWORDS, reservedKeywordRegex, identifierNameRegex, validIdentifierRegex, isValidIdentifier, normalizeIdentifier;
var init_identifiers = __esm({
"src/pages/functions/identifiers.ts"() {
init_import_meta_url();
RESERVED_KEYWORDS = [
"do",
"if",
"in",
"for",
"let",
"new",
"try",
"var",
"case",
"else",
"enum",
"eval",
"null",
"this",
"true",
"void",
"with",
"await",
"break",
"catch",
"class",
"const",
"false",
"super",
"throw",
"while",
"yield",
"delete",
"export",
"import",
"public",
"return",
"static",
"switch",
"typeof",
"default",
"extends",
"finally",
"package",
"private",
"continue",
"debugger",
"function",
"arguments",
"interface",
"protected",
"implements",
"instanceof",
"NaN",
"Infinity",
"undefined"
];
reservedKeywordRegex = new RegExp(`^${RESERVED_KEYWORDS.join("|")}$`);
identifierNameRegex = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
validIdentifierRegex = new RegExp(
`(?!(${reservedKeywordRegex.source})$)${identifierNameRegex.source}`,
"u"
);
isValidIdentifier = /* @__PURE__ */ __name((identifier) => validIdentifierRegex.test(identifier), "isValidIdentifier");
normalizeIdentifier = /* @__PURE__ */ __name((identifier) => identifier.replace(
/(?:^[^$_\p{ID_Start}])|[^$_\u200C\u200D\p{ID_Continue}]/gu,
"_"
), "normalizeIdentifier");
}
});
// src/pages/functions/routes.ts
async function writeRoutesModule({
config,
srcDir,
outfile = "_routes.js"
}) {
const { importMap, routes } = parseConfig(config, srcDir);
const routesModule = generateRoutesModule(importMap, routes);
await import_promises17.default.writeFile(outfile, routesModule);
return outfile;
}
function parseConfig(config, baseDir) {
const routes = [];
const importMap = /* @__PURE__ */ new Map();
const identifierCount = /* @__PURE__ */ new Map();
function parseModuleIdentifiers(paths) {
if (typeof paths === "undefined") {
paths = [];
}
if (typeof paths === "string") {
paths = [paths];
}
return paths.map((modulePath) => {
const [filepath, name2 = "default"] = modulePath.split(":");
let { identifier } = importMap.get(modulePath) ?? {};
const resolvedPath2 = import_node_path39.default.resolve(baseDir, filepath);
if (import_node_path39.default.relative(baseDir, resolvedPath2).startsWith("..")) {
throw new UserError(`Invalid module path "${filepath}"`);
}
if (name2 !== "default" && !isValidIdentifier(name2)) {
throw new UserError(`Invalid module identifier "${name2}"`);
}
if (!identifier) {
identifier = normalizeIdentifier(`__${filepath}_${name2}`);
let count = identifierCount.get(identifier) ?? 0;
identifierCount.set(identifier, ++count);
if (count > 1) {
identifier += `_${count}`;
}
importMap.set(modulePath, { filepath: resolvedPath2, name: name2, identifier });
}
return identifier;
});
}
__name(parseModuleIdentifiers, "parseModuleIdentifiers");
for (const { routePath, mountPath, method, ...props } of config.routes ?? []) {
routes.push({
routePath,
mountPath,
method,
middlewares: parseModuleIdentifiers(props.middleware),
modules: parseModuleIdentifiers(props.module)
});
}
return { routes, importMap };
}
function generateRoutesModule(importMap, routes) {
return `${[...importMap.values()].map(
({ filepath, name: name2, identifier }) => `import { ${name2} as ${identifier} } from ${JSON.stringify(filepath)}`
).join("\n")}
export const routes = [
${routes.map(
(route) => ` {
routePath: "${route.routePath}",
mountPath: "${route.mountPath}",
method: "${route.method}",
middlewares: [${route.middlewares.join(", ")}],
modules: [${route.modules.join(", ")}],
},`
).join("\n")}
]`;
}
var import_promises17, import_node_path39;
var init_routes2 = __esm({
"src/pages/functions/routes.ts"() {
init_import_meta_url();
import_promises17 = __toESM(require("fs/promises"));
import_node_path39 = __toESM(require("path"));
init_errors();
init_identifiers();
__name(writeRoutesModule, "writeRoutesModule");
__name(parseConfig, "parseConfig");
__name(generateRoutesModule, "generateRoutesModule");
}
});
// src/pages/functions/routes-consolidation.ts
function consolidateRoutes(routes) {
const routesShortened = Array.from(
new Set(routes.map((route) => shortenRoute(route)))
);
const routesMap = /* @__PURE__ */ new Map();
for (const route of routesShortened) {
routesMap.set(route, true);
}
for (const route of routesShortened.filter((r7) => r7.endsWith("/*"))) {
if (routesMap.has(route)) {
const routeTrimmed = route.substring(0, route.length - 1);
for (const nextRoute of routesMap.keys()) {
if (nextRoute !== route && nextRoute.startsWith(routeTrimmed)) {
routesMap.delete(nextRoute);
}
}
}
}
return Array.from(routesMap.keys());
}
function shortenRoute(routeToShorten, maxLength = MAX_FUNCTIONS_ROUTES_RULE_LENGTH) {
if (routeToShorten.length <= maxLength) {
return routeToShorten;
}
let route = routeToShorten;
for (let i5 = 0; i5 < routeToShorten.length; i5++) {
for (let j6 = maxLength - 1 - i5; j6 > 0; j6--) {
if (route[j6] === "/") {
route = route.slice(0, j6) + "/*";
break;
}
}
if (route.length <= maxLength) {
break;
}
}
if (route.length > maxLength) {
route = "/*";
}
return route;
}
var init_routes_consolidation = __esm({
"src/pages/functions/routes-consolidation.ts"() {
init_import_meta_url();
init_constants();
__name(consolidateRoutes, "consolidateRoutes");
__name(shortenRoute, "shortenRoute");
}
});
// src/pages/functions/routes-transformation.ts
function convertRoutesToGlobPatterns(routes) {
const convertedRoutes = routes.map(({ routePath, middleware }) => {
const globbedRoutePath = routePath.replace(/:\w+\*?.*/, "*");
if (typeof middleware === "string" || Array.isArray(middleware) && middleware.length > 0) {
if (!globbedRoutePath.endsWith("*")) {
return toUrlPath((0, import_node_path40.join)(globbedRoutePath, "*"));
}
}
return toUrlPath(globbedRoutePath);
});
return Array.from(new Set(convertedRoutes));
}
function convertRoutesToRoutesJSONSpec(routes) {
const reversedRoutes = [...routes].reverse();
const include = convertRoutesToGlobPatterns(reversedRoutes);
return optimizeRoutesJSONSpec({
version: ROUTES_SPEC_VERSION,
description: ROUTES_SPEC_DESCRIPTION,
include,
exclude: []
});
}
function optimizeRoutesJSONSpec(spec) {
const optimizedSpec = { ...spec };
let consolidatedRoutes = consolidateRoutes(optimizedSpec.include);
if (consolidatedRoutes.length > MAX_FUNCTIONS_ROUTES_RULES) {
consolidatedRoutes = ["/*"];
}
consolidatedRoutes.sort((a5, b6) => compareRoutes2(b6, a5));
optimizedSpec.include = consolidatedRoutes;
return optimizedSpec;
}
function compareRoutes2(routeA, routeB) {
function parseRoutePath(routePath) {
return routePath.slice(1).split("/").filter(Boolean);
}
__name(parseRoutePath, "parseRoutePath");
const segmentsA = parseRoutePath(routeA);
const segmentsB = parseRoutePath(routeB);
if (segmentsA.length !== segmentsB.length) {
return segmentsB.length - segmentsA.length;
}
for (let i5 = 0; i5 < segmentsA.length; i5++) {
const isWildcardA = segmentsA[i5].includes("*");
const isWildcardB = segmentsB[i5].includes("*");
if (isWildcardA && !isWildcardB) {
return 1;
}
if (!isWildcardA && isWildcardB) {
return -1;
}
}
return routeA.localeCompare(routeB);
}
var import_node_path40;
var init_routes_transformation = __esm({
"src/pages/functions/routes-transformation.ts"() {
init_import_meta_url();
import_node_path40 = require("path");
init_paths();
init_constants();
init_routes_consolidation();
__name(convertRoutesToGlobPatterns, "convertRoutesToGlobPatterns");
__name(convertRoutesToRoutesJSONSpec, "convertRoutesToRoutesJSONSpec");
__name(optimizeRoutesJSONSpec, "optimizeRoutesJSONSpec");
__name(compareRoutes2, "compareRoutes");
}
});
// src/pages/buildFunctions.ts
async function buildFunctions({
outfile,
outdir,
outputConfigPath,
functionsDirectory,
minify = false,
sourcemap = false,
fallbackService = "ASSETS",
watch: watch2 = false,
onEnd,
plugin = false,
buildOutputDirectory,
routesOutputPath,
nodejsCompatMode,
local,
routesModule = (0, import_node_path41.join)(
getPagesTmpDir(),
`./functionsRoutes-${Math.random()}.mjs`
),
defineNavigatorUserAgent,
checkFetch,
external,
metafile
}) {
RUNNING_BUILDERS.forEach(
(runningBuilder) => runningBuilder.stop && runningBuilder.stop()
);
const baseURL = toUrlPath("/");
const config = await generateConfigFromFileTree({
baseDir: functionsDirectory,
baseURL
});
if (!config.routes || config.routes.length === 0) {
throw new FunctionsNoRoutesError(
`Failed to find any routes while compiling Functions in: ${functionsDirectory}`
);
}
if (routesOutputPath) {
const routesJSON = convertRoutesToRoutesJSONSpec(config.routes);
(0, import_node_fs22.writeFileSync)(routesOutputPath, JSON.stringify(routesJSON, null, 2));
}
if (outputConfigPath) {
(0, import_node_fs22.writeFileSync)(
outputConfigPath,
JSON.stringify({ ...config, baseURL }, null, 2)
);
}
await writeRoutesModule({
config,
srcDir: functionsDirectory,
outfile: routesModule
});
const absoluteFunctionsDirectory = (0, import_node_path41.resolve)(functionsDirectory);
let bundle;
if (plugin) {
if (outdir === void 0) {
throw new FatalError(
"Must specify an output directory when building a Plugin.",
1
);
}
bundle = await buildPluginFromFunctions({
routesModule,
outdir,
minify,
sourcemap,
watch: watch2,
nodejsCompatMode,
functionsDirectory: absoluteFunctionsDirectory,
local,
defineNavigatorUserAgent,
checkFetch,
external
});
} else {
bundle = await buildWorkerFromFunctions({
routesModule,
outfile,
outdir,
minify,
sourcemap,
fallbackService,
watch: watch2,
functionsDirectory: absoluteFunctionsDirectory,
local,
onEnd,
buildOutputDirectory,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
external,
metafile
});
}
RUNNING_BUILDERS.push(bundle);
return bundle;
}
var import_node_fs22, import_node_path41;
var init_buildFunctions = __esm({
"src/pages/buildFunctions.ts"() {
init_import_meta_url();
import_node_fs22 = require("fs");
import_node_path41 = require("path");
init_errors();
init_paths();
init_errors3();
init_buildPlugin();
init_buildWorker();
init_filepath_routing();
init_routes2();
init_routes_transformation();
init_utils6();
__name(buildFunctions, "buildFunctions");
}
});
// src/pages/build.ts
async function maybeReadPagesConfig(args) {
if (!args.projectDirectory || !args.buildMetadataPath) {
return;
}
const { configPath } = findWranglerConfig(args.projectDirectory, {
useRedirectIfAvailable: true
});
if (!configPath || !(0, import_node_fs23.existsSync)(configPath)) {
return void 0;
}
try {
const config = readPagesConfig({
...args,
config: configPath,
// eslint-disable-next-line turbo/no-undeclared-env-vars
env: process.env.PAGES_ENVIRONMENT
});
return {
...config,
hash: (0, import_node_crypto8.createHash)("sha256").update(await (0, import_promises18.readFile)(configPath)).digest("hex")
};
} catch (e7) {
if (e7 instanceof FatalError && e7.code === EXIT_CODE_INVALID_PAGES_CONFIG) {
return void 0;
}
throw e7;
}
}
var import_node_crypto8, import_node_fs23, import_promises18, import_node_path42, pagesFunctionsBuildCommand, validateArgs;
var init_build4 = __esm({
"src/pages/build.ts"() {
init_import_meta_url();
import_node_crypto8 = require("crypto");
import_node_fs23 = require("fs");
import_promises18 = require("fs/promises");
import_node_path42 = __toESM(require("path"));
init_create_worker_bundle_contents();
init_config2();
init_config_helpers();
init_create_command();
init_bundle();
init_find_additional_modules();
init_node_compat();
init_errors();
init_logger();
init_metrics();
init_navigator_user_agent();
init_buildFunctions();
init_errors3();
init_buildWorker();
pagesFunctionsBuildCommand = createCommand({
metadata: {
description: "Compile a folder of Pages Functions into a single Worker",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
directory: {
type: "string",
default: "functions",
description: "The directory of Pages Functions"
},
outfile: {
type: "string",
description: "The location of the output Worker script",
deprecated: true
},
outdir: {
type: "string",
description: "Output directory for the bundled Worker"
},
"output-config-path": {
type: "string",
description: "The location for the output config file"
},
"build-metadata-path": {
type: "string",
description: "The location for the build metadata file"
},
"project-directory": {
type: "string",
description: "The location of the Pages project"
},
"output-routes-path": {
type: "string",
description: "The location for the output _routes.json file"
},
minify: {
type: "boolean",
default: false,
description: "Minify the output Worker script"
},
sourcemap: {
type: "boolean",
default: false,
description: "Generate a sourcemap for the output Worker script"
},
"fallback-service": {
type: "string",
default: "ASSETS",
description: "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`."
},
watch: {
type: "boolean",
default: false,
description: "Watch for changes to the functions and automatically rebuild the Worker script"
},
plugin: {
type: "boolean",
default: false,
description: "Build a plugin rather than a Worker script"
},
"build-output-directory": {
type: "string",
description: "The directory to output static assets to"
},
"node-compat": {
type: "boolean",
default: false,
description: "Enable Node.js compatibility",
hidden: true,
deprecated: true
},
"compatibility-date": {
type: "string",
description: "Date to use for compatibility checks"
},
"compatibility-flags": {
description: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
requiresArg: true,
array: true
},
bindings: {
type: "string",
description: "Bindings used in Functions (used to register beta product shims)",
deprecated: true,
hidden: true
},
external: {
description: "A list of module imports to exclude from bundling",
type: "string",
array: true
},
metafile: {
describe: "Path to output build metadata from esbuild. If flag is used without a path, defaults to 'bundle-meta.json' inside the directory specified by --outdir.",
type: "string",
coerce: /* @__PURE__ */ __name((v7) => !v7 ? true : v7, "coerce")
}
},
positionalArgs: ["directory"],
async handler(args) {
const validatedArgs = await validateArgs(args);
let bundle = void 0;
if (validatedArgs.plugin) {
const {
directory,
outfile,
outdir,
outputConfigPath,
outputRoutesPath: routesOutputPath,
minify,
sourcemap,
fallbackService,
watch: watch2,
plugin,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
external,
metafile
} = validatedArgs;
try {
bundle = await buildFunctions({
outfile,
outdir,
outputConfigPath,
functionsDirectory: directory,
minify,
sourcemap,
fallbackService,
// This only watches already existing files using the esbuild watching mechanism
// it will not watch new files that are added to the functions directory!
watch: watch2,
plugin,
nodejsCompatMode,
routesOutputPath,
local: false,
defineNavigatorUserAgent,
checkFetch,
external,
metafile
});
} catch (e7) {
if (e7 instanceof FunctionsNoRoutesError) {
throw new FatalError(
getFunctionsNoRoutesWarning(directory),
EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR
);
} else {
throw e7;
}
}
if (outfile && outfile !== bundle.resolvedEntryPointPath) {
(0, import_node_fs23.writeFileSync)(
outfile,
`export { default } from './${(0, import_node_path42.relative)(
(0, import_node_path42.dirname)(outfile),
bundle.resolvedEntryPointPath
)}'`
);
}
} else {
const {
config,
buildMetadataPath,
buildMetadata,
directory,
outfile,
outdir,
outputConfigPath,
outputRoutesPath: routesOutputPath,
minify,
sourcemap,
fallbackService,
watch: watch2,
plugin,
buildOutputDirectory,
nodejsCompatMode,
workerScriptPath,
defineNavigatorUserAgent,
checkFetch,
external,
metafile
} = validatedArgs;
if (workerScriptPath) {
if ((0, import_node_fs23.lstatSync)(workerScriptPath).isDirectory()) {
bundle = await produceWorkerBundleForWorkerJSDirectory({
workerJSDirectory: workerScriptPath,
bundle: true,
buildOutputDirectory,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
sourceMaps: config?.upload_source_maps ?? sourcemap
});
} else {
bundle = await buildRawWorker({
workerScriptPath,
outdir,
directory: buildOutputDirectory,
local: false,
sourcemap: config?.upload_source_maps ?? sourcemap,
watch: watch2,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
externalModules: external
});
}
} else {
try {
bundle = await buildFunctions({
outdir,
outputConfigPath,
functionsDirectory: directory,
minify,
sourcemap: config?.upload_source_maps ?? sourcemap,
fallbackService,
watch: watch2,
plugin,
buildOutputDirectory,
nodejsCompatMode,
routesOutputPath,
local: false,
defineNavigatorUserAgent,
checkFetch,
external,
metafile
});
} catch (e7) {
if (e7 instanceof FunctionsNoRoutesError) {
throw new FatalError(
getFunctionsNoRoutesWarning(directory),
EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR
);
} else {
throw e7;
}
}
}
if (outdir) {
await writeAdditionalModules(bundle.modules, outdir);
}
if (outfile) {
const workerBundleContents = await createUploadWorkerBundleContents(
bundle,
config
);
(0, import_node_fs23.mkdirSync)((0, import_node_path42.dirname)(outfile), { recursive: true });
(0, import_node_fs23.writeFileSync)(
outfile,
Buffer.from(await workerBundleContents.arrayBuffer())
);
}
if (buildMetadataPath && buildMetadata) {
(0, import_node_fs23.writeFileSync)(buildMetadataPath, JSON.stringify(buildMetadata));
}
}
sendMetricsEvent("build pages functions");
}
});
__name(maybeReadPagesConfig, "maybeReadPagesConfig");
validateArgs = /* @__PURE__ */ __name(async (args) => {
const config = await maybeReadPagesConfig(args);
if (args.nodeCompat) {
throw new UserError(
`The --node-compat flag is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`
);
}
if (args.outdir && args.outfile) {
throw new FatalError(
"Cannot specify both an `--outdir` and an `--outfile`.",
1
);
}
if (args.plugin) {
if (args.outfile) {
logger.warn(
"Creating a Pages Plugin with `--outfile` is now deprecated. Please use `--outdir` instead."
);
args.outdir = (0, import_node_path42.dirname)((0, import_node_path42.resolve)(args.outfile));
} else if (!args.outfile && !args.outdir) {
args.outfile ??= "_worker.js";
args.outdir = ".";
logger.warn(
"Creating a Pages Plugin without `--outdir` is now deprecated. Please add an `--outdir` argument."
);
}
if (args.bindings) {
throw new FatalError(
"The `--bindings` flag cannot be used when creating a Pages Plugin with `--plugin`.",
1
);
}
if (args.buildOutputDirectory) {
throw new FatalError(
"The `--build-output-directory` flag cannot be used when creating a Pages Plugin with `--plugin`.",
1
);
}
} else {
if (!args.outdir) {
args.outfile ??= "_worker.bundle";
}
args.buildOutputDirectory ??= args.outfile ? (0, import_node_path42.dirname)(args.outfile) : ".";
}
args.buildOutputDirectory = config?.pages_build_output_dir ?? (args.buildOutputDirectory ? (0, import_node_path42.resolve)(args.buildOutputDirectory) : void 0);
if (args.outdir) {
args.outdir = (0, import_node_path42.resolve)(args.outdir);
}
if (args.outfile) {
args.outfile = (0, import_node_path42.resolve)(args.outfile);
}
const nodejsCompatMode = validateNodeCompatMode(
args.compatibilityDate ?? config?.compatibility_date,
args.compatibilityFlags ?? config?.compatibility_flags ?? [],
{
noBundle: config?.no_bundle
}
);
const defineNavigatorUserAgent = isNavigatorDefined(
args.compatibilityDate,
args.compatibilityFlags
);
const checkFetch = shouldCheckFetch(
args.compatibilityDate,
args.compatibilityFlags
);
let workerScriptPath;
if (args.buildOutputDirectory) {
const prospectiveWorkerScriptPath = (0, import_node_path42.resolve)(
args.buildOutputDirectory,
"_worker.js"
);
const foundWorkerScript = (0, import_node_fs23.existsSync)(prospectiveWorkerScriptPath);
if (foundWorkerScript) {
workerScriptPath = prospectiveWorkerScriptPath;
} else if (!foundWorkerScript && !(0, import_node_fs23.existsSync)(args.directory)) {
throw new FatalError(
`Could not find anything to build.
We first looked inside the build output directory (${(0, import_node_path42.basename)(
(0, import_node_path42.resolve)(args.buildOutputDirectory)
)}), then looked for the Functions directory (${(0, import_node_path42.basename)(
args.directory
)}) but couldn't find anything to build.
\u27A4 If you are trying to build _worker.js, please make sure you provide the [--build-output-directory] containing your static files.
\u27A4 If you are trying to build Pages Functions, please make sure [directory] points to the location of your Functions files.`,
EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR
);
}
} else if (!(0, import_node_fs23.existsSync)(args.directory)) {
throw new FatalError(
`Could not find anything to build.
We looked for the Functions directory (${(0, import_node_path42.basename)(
args.directory
)}) but couldn't find anything to build.
\u27A4 Please make sure [directory] points to the location of your Functions files.`,
EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR
);
}
return {
...args,
workerScriptPath,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
config,
buildMetadata: config && args.projectDirectory && config.pages_build_output_dir ? {
wrangler_config_hash: config.hash,
build_output_directory: import_node_path42.default.relative(
args.projectDirectory,
config.pages_build_output_dir
)
} : void 0
};
}, "validateArgs");
}
});
// src/pages/build-env.ts
var import_node_fs24, import_node_path43, pagesFunctionsBuildEnvCommand;
var init_build_env = __esm({
"src/pages/build-env.ts"() {
init_import_meta_url();
import_node_fs24 = require("fs");
import_node_path43 = __toESM(require("path"));
init_config2();
init_config_helpers();
init_create_command();
init_errors();
init_logger();
init_errors3();
pagesFunctionsBuildEnvCommand = createCommand({
metadata: {
description: "Render a list of environment variables from the config file",
status: "stable",
owner: "Workers: Authoring and Testing",
hidden: true
},
behaviour: {
provideConfig: false
},
args: {
projectDir: {
type: "string",
description: "The location of the Pages project"
},
outfile: {
type: "string",
description: "The location to write the build environment file"
}
},
positionalArgs: ["projectDir"],
async handler(args) {
if (!args.projectDir) {
throw new FatalError("No Pages project location specified");
}
if (!args.outfile) {
throw new FatalError("No outfile specified");
}
logger.log(
"Checking for configuration in a Wrangler configuration file (BETA)\n"
);
const { configPath } = findWranglerConfig(args.projectDir, {
useRedirectIfAvailable: true
});
if (!configPath || !(0, import_node_fs24.existsSync)(configPath)) {
logger.debug("No Wrangler configuration file found. Exiting.");
process.exitCode = EXIT_CODE_NO_CONFIG_FOUND;
return;
}
logger.log(
`Found ${configFileName(configPath)} file. Reading build configuration...`
);
let config;
try {
config = readPagesConfig({
...args,
config: configPath,
// eslint-disable-next-line turbo/no-undeclared-env-vars
env: process.env.PAGES_ENVIRONMENT
});
} catch (err) {
if (err instanceof FatalError && err.code === EXIT_CODE_INVALID_PAGES_CONFIG) {
logger.debug(
`Your ${configFileName(configPath)} file is invalid. Exiting.`
);
process.exitCode = EXIT_CODE_INVALID_PAGES_CONFIG;
return;
}
throw err;
}
const textVars = Object.fromEntries(
Object.entries(config.vars).filter(([_4, v7]) => typeof v7 === "string")
);
const buildConfiguration = {
vars: textVars,
pages_build_output_dir: import_node_path43.default.relative(
args.projectDir,
config.pages_build_output_dir
)
};
(0, import_node_fs24.writeFileSync)(args.outfile, JSON.stringify(buildConfiguration));
logger.debug(`Build configuration written to ${args.outfile}`);
logger.debug(JSON.stringify(buildConfiguration), null, 2);
const vars = Object.entries(buildConfiguration.vars);
const message = [
`Build environment variables: ${vars.length === 0 ? "(none found)" : ""}`,
...vars.map(([key, value]) => ` - ${key}: ${value}`)
].join("\n");
logger.log(
`pages_build_output_dir: ${buildConfiguration.pages_build_output_dir}`
);
logger.log(message);
}
});
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js
var require_Mime = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js"(exports2, module3) {
"use strict";
init_import_meta_url();
function Mime2() {
this._types = /* @__PURE__ */ Object.create(null);
this._extensions = /* @__PURE__ */ Object.create(null);
for (let i5 = 0; i5 < arguments.length; i5++) {
this.define(arguments[i5]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
__name(Mime2, "Mime");
Mime2.prototype.define = function(typeMap, force) {
for (let type in typeMap) {
let extensions = typeMap[type].map(function(t7) {
return t7.toLowerCase();
});
type = type.toLowerCase();
for (let i5 = 0; i5 < extensions.length; i5++) {
const ext = extensions[i5];
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);
}
}
};
Mime2.prototype.getType = function(path72) {
path72 = String(path72);
let last = path72.replace(/^.*[/\\]/, "").toLowerCase();
let ext = last.replace(/^.*\./, "").toLowerCase();
let hasPath = last.length < path72.length;
let hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
Mime2.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module3.exports = Mime2;
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js
var require_standard = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js"(exports2, module3) {
init_import_meta_url();
module3.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/.pnpm/mime@3.0.0/node_modules/mime/types/other.js
var require_other = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js"(exports2, module3) {
init_import_meta_url();
module3.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/.pnpm/mime@3.0.0/node_modules/mime/index.js
var require_mime = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var Mime2 = require_Mime();
module3.exports = new Mime2(require_standard(), require_other());
}
});
// ../../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
var require_path = __commonJS({
"../../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports2, module3) {
init_import_meta_url();
var isWindows4 = typeof process === "object" && process && process.platform === "win32";
module3.exports = isWindows4 ? { sep: "\\" } : { sep: "/" };
}
});
// ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
"../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
module3.exports = balanced;
function balanced(a5, b6, str) {
if (a5 instanceof RegExp) a5 = maybeMatch(a5, str);
if (b6 instanceof RegExp) b6 = maybeMatch(b6, str);
var r7 = range(a5, b6, str);
return r7 && {
start: r7[0],
end: r7[1],
pre: str.slice(0, r7[0]),
body: str.slice(r7[0] + a5.length, r7[1]),
post: str.slice(r7[1] + b6.length)
};
}
__name(balanced, "balanced");
function maybeMatch(reg, str) {
var m6 = str.match(reg);
return m6 ? m6[0] : null;
}
__name(maybeMatch, "maybeMatch");
balanced.range = range;
function range(a5, b6, str) {
var begs, beg, left2, right2, result;
var ai2 = str.indexOf(a5);
var bi2 = str.indexOf(b6, ai2 + 1);
var i5 = ai2;
if (ai2 >= 0 && bi2 > 0) {
if (a5 === b6) {
return [ai2, bi2];
}
begs = [];
left2 = str.length;
while (i5 >= 0 && !result) {
if (i5 == ai2) {
begs.push(i5);
ai2 = str.indexOf(a5, i5 + 1);
} else if (begs.length == 1) {
result = [begs.pop(), bi2];
} else {
beg = begs.pop();
if (beg < left2) {
left2 = beg;
right2 = bi2;
}
bi2 = str.indexOf(b6, i5 + 1);
}
i5 = ai2 < bi2 && ai2 >= 0 ? ai2 : bi2;
}
if (begs.length) {
result = [left2, right2];
}
}
return result;
}
__name(range, "range");
}
});
// ../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
"../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports2, module3) {
init_import_meta_url();
var balanced = require_balanced_match();
module3.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);
}
__name(numeric, "numeric");
function escapeBraces(str) {
return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
}
__name(escapeBraces, "escapeBraces");
function unescapeBraces(str) {
return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
}
__name(unescapeBraces, "unescapeBraces");
function parseCommaParts(str) {
if (!str)
return [""];
var parts = [];
var m6 = balanced("{", "}", str);
if (!m6)
return str.split(",");
var pre = m6.pre;
var body = m6.body;
var post = m6.post;
var p6 = pre.split(",");
p6[p6.length - 1] += "{" + body + "}";
var postParts = parseCommaParts(post);
if (post.length) {
p6[p6.length - 1] += postParts.shift();
p6.push.apply(p6, postParts);
}
parts.push.apply(parts, p6);
return parts;
}
__name(parseCommaParts, "parseCommaParts");
function expandTop(str) {
if (!str)
return [];
if (str.substr(0, 2) === "{}") {
str = "\\{\\}" + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
__name(expandTop, "expandTop");
function embrace(str) {
return "{" + str + "}";
}
__name(embrace, "embrace");
function isPadded(el) {
return /^-?0\d/.test(el);
}
__name(isPadded, "isPadded");
function lte(i5, y4) {
return i5 <= y4;
}
__name(lte, "lte");
function gte(i5, y4) {
return i5 >= y4;
}
__name(gte, "gte");
function expand(str, isTop) {
var expansions = [];
var m6 = balanced("{", "}", str);
if (!m6) return [str];
var pre = m6.pre;
var post = m6.post.length ? expand(m6.post, false) : [""];
if (/\$$/.test(m6.pre)) {
for (var k6 = 0; k6 < post.length; k6++) {
var expansion = pre + "{" + m6.body + "}" + post[k6];
expansions.push(expansion);
}
} else {
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m6.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m6.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m6.body.indexOf(",") >= 0;
if (!isSequence && !isOptions) {
if (m6.post.match(/,.*\}/)) {
str = m6.pre + "{" + m6.body + escClose + m6.post;
return expand(str);
}
return [str];
}
var n6;
if (isSequence) {
n6 = m6.body.split(/\.\./);
} else {
n6 = parseCommaParts(m6.body);
if (n6.length === 1) {
n6 = expand(n6[0], false).map(embrace);
if (n6.length === 1) {
return post.map(function(p6) {
return m6.pre + n6[0] + p6;
});
}
}
}
var N3;
if (isSequence) {
var x6 = numeric(n6[0]);
var y4 = numeric(n6[1]);
var width = Math.max(n6[0].length, n6[1].length);
var incr = n6.length == 3 ? Math.abs(numeric(n6[2])) : 1;
var test = lte;
var reverse = y4 < x6;
if (reverse) {
incr *= -1;
test = gte;
}
var pad2 = n6.some(isPadded);
N3 = [];
for (var i5 = x6; test(i5, y4); i5 += incr) {
var c6;
if (isAlphaSequence) {
c6 = String.fromCharCode(i5);
if (c6 === "\\")
c6 = "";
} else {
c6 = String(i5);
if (pad2) {
var need = width - c6.length;
if (need > 0) {
var z5 = new Array(need + 1).join("0");
if (i5 < 0)
c6 = "-" + z5 + c6.slice(1);
else
c6 = z5 + c6;
}
}
}
N3.push(c6);
}
} else {
N3 = [];
for (var j6 = 0; j6 < n6.length; j6++) {
N3.push.apply(N3, expand(n6[j6], false));
}
}
for (var j6 = 0; j6 < N3.length; j6++) {
for (var k6 = 0; k6 < post.length; k6++) {
var expansion = pre + N3[j6] + post[k6];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
}
return expansions;
}
__name(expand, "expand");
}
});
// ../../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
"../../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports2, module3) {
init_import_meta_url();
var minimatch = module3.exports = (p6, pattern, options = {}) => {
assertValidPattern(pattern);
if (!options.nocomment && pattern.charAt(0) === "#") {
return false;
}
return new Minimatch2(pattern, options).match(p6);
};
module3.exports = minimatch;
var path72 = require_path();
minimatch.sep = path72.sep;
var GLOBSTAR = Symbol("globstar **");
minimatch.GLOBSTAR = 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 charSet = /* @__PURE__ */ __name((s5) => s5.split("").reduce((set, c6) => {
set[c6] = true;
return set;
}, {}), "charSet");
var reSpecials = charSet("().*{}+?[]^$\\!");
var addPatternStartSet = charSet("[.(");
var slashSplit = /\/+/;
minimatch.filter = (pattern, options = {}) => (p6, i5, list) => minimatch(p6, pattern, options);
var ext = /* @__PURE__ */ __name((a5, b6 = {}) => {
const t7 = {};
Object.keys(a5).forEach((k6) => t7[k6] = a5[k6]);
Object.keys(b6).forEach((k6) => t7[k6] = b6[k6]);
return t7;
}, "ext");
minimatch.defaults = (def) => {
if (!def || typeof def !== "object" || !Object.keys(def).length) {
return minimatch;
}
const orig = minimatch;
const m6 = /* @__PURE__ */ __name((p6, pattern, options) => orig(p6, pattern, ext(def, options)), "m");
m6.Minimatch = class Minimatch extends orig.Minimatch {
static {
__name(this, "Minimatch");
}
constructor(pattern, options) {
super(pattern, ext(def, options));
}
};
m6.Minimatch.defaults = (options) => orig.defaults(ext(def, options)).Minimatch;
m6.filter = (pattern, options) => orig.filter(pattern, ext(def, options));
m6.defaults = (options) => orig.defaults(ext(def, options));
m6.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options));
m6.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options));
m6.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options));
return m6;
};
minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options);
var braceExpand = /* @__PURE__ */ __name((pattern, options = {}) => {
assertValidPattern(pattern);
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
return [pattern];
}
return expand(pattern);
}, "braceExpand");
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = /* @__PURE__ */ __name((pattern) => {
if (typeof pattern !== "string") {
throw new TypeError("invalid pattern");
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError("pattern is too long");
}
}, "assertValidPattern");
var SUBPARSE = Symbol("subparse");
minimatch.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
minimatch.match = (list, pattern, options = {}) => {
const mm = new Minimatch2(pattern, options);
list = list.filter((f6) => mm.match(f6));
if (mm.options.nonull && !list.length) {
list.push(pattern);
}
return list;
};
var globUnescape = /* @__PURE__ */ __name((s5) => s5.replace(/\\(.)/g, "$1"), "globUnescape");
var charUnescape = /* @__PURE__ */ __name((s5) => s5.replace(/\\([^-\]])/g, "$1"), "charUnescape");
var regExpEscape = /* @__PURE__ */ __name((s5) => s5.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "regExpEscape");
var braExpEscape = /* @__PURE__ */ __name((s5) => s5.replace(/[[\]\\]/g, "\\$&"), "braExpEscape");
var Minimatch2 = class {
static {
__name(this, "Minimatch");
}
constructor(pattern, options) {
assertValidPattern(pattern);
if (!options) options = {};
this.options = options;
this.set = [];
this.pattern = pattern;
this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
this.pattern = this.pattern.replace(/\\/g, "/");
}
this.regexp = null;
this.negate = false;
this.comment = false;
this.empty = false;
this.partial = !!options.partial;
this.make();
}
debug() {
}
make() {
const pattern = this.pattern;
const options = this.options;
if (!options.nocomment && pattern.charAt(0) === "#") {
this.comment = true;
return;
}
if (!pattern) {
this.empty = true;
return;
}
this.parseNegate();
let set = this.globSet = this.braceExpand();
if (options.debug) this.debug = (...args) => console.error(...args);
this.debug(this.pattern, set);
set = this.globParts = set.map((s5) => s5.split(slashSplit));
this.debug(this.pattern, set);
set = set.map((s5, si, set2) => s5.map(this.parse, this));
this.debug(this.pattern, set);
set = set.filter((s5) => s5.indexOf(false) === -1);
this.debug(this.pattern, set);
this.set = set;
}
parseNegate() {
if (this.options.nonegate) return;
const pattern = this.pattern;
let negate3 = false;
let negateOffset = 0;
for (let i5 = 0; i5 < pattern.length && pattern.charAt(i5) === "!"; i5++) {
negate3 = !negate3;
negateOffset++;
}
if (negateOffset) this.pattern = pattern.slice(negateOffset);
this.negate = negate3;
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
matchOne(file, pattern, partial) {
var options = this.options;
this.debug(
"matchOne",
{ "this": this, file, pattern }
);
this.debug("matchOne", file.length, pattern.length);
for (var fi = 0, pi = 0, fl = file.length, pl2 = pattern.length; fi < fl && pi < pl2; fi++, pi++) {
this.debug("matchOne loop");
var p6 = pattern[pi];
var f6 = file[fi];
this.debug(pattern, p6, f6);
if (p6 === false) return false;
if (p6 === GLOBSTAR) {
this.debug("GLOBSTAR", [pattern, p6, f6]);
var fr = fi;
var pr = pi + 1;
if (pr === pl2) {
this.debug("** at the end");
for (; fi < fl; fi++) {
if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
}
return true;
}
while (fr < fl) {
var swallowee = file[fr];
this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug("globstar found match!", fr, fl, swallowee);
return true;
} else {
if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
this.debug("dot detected!", file, fr, pattern, pr);
break;
}
this.debug("globstar swallow a segment, and continue");
fr++;
}
}
if (partial) {
this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
if (fr === fl) return true;
}
return false;
}
var hit;
if (typeof p6 === "string") {
hit = f6 === p6;
this.debug("string match", p6, f6, hit);
} else {
hit = f6.match(p6);
this.debug("pattern match", p6, f6, hit);
}
if (!hit) return false;
}
if (fi === fl && pi === pl2) {
return true;
} else if (fi === fl) {
return partial;
} else if (pi === pl2) {
return fi === fl - 1 && file[fi] === "";
}
throw new Error("wtf?");
}
braceExpand() {
return braceExpand(this.pattern, this.options);
}
parse(pattern, isSub) {
assertValidPattern(pattern);
const options = this.options;
if (pattern === "**") {
if (!options.noglobstar)
return GLOBSTAR;
else
pattern = "*";
}
if (pattern === "") return "";
let re = "";
let hasMagic = false;
let escaping = false;
const patternListStack = [];
const negativeLists = [];
let stateChar;
let inClass = false;
let reClassStart = -1;
let classStart = -1;
let cs2;
let pl2;
let sp;
let dotTravAllowed = pattern.charAt(0) === ".";
let dotFileAllowed = options.dot || dotTravAllowed;
const patternStart = /* @__PURE__ */ __name(() => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)", "patternStart");
const subPatternStart = /* @__PURE__ */ __name((p6) => p6.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)", "subPatternStart");
const clearStateChar = /* @__PURE__ */ __name(() => {
if (stateChar) {
switch (stateChar) {
case "*":
re += star;
hasMagic = true;
break;
case "?":
re += qmark;
hasMagic = true;
break;
default:
re += "\\" + stateChar;
break;
}
this.debug("clearStateChar %j %j", stateChar, re);
stateChar = false;
}
}, "clearStateChar");
for (let i5 = 0, c6; i5 < pattern.length && (c6 = pattern.charAt(i5)); i5++) {
this.debug("%s %s %s %j", pattern, i5, re, c6);
if (escaping) {
if (c6 === "/") {
return false;
}
if (reSpecials[c6]) {
re += "\\";
}
re += c6;
escaping = false;
continue;
}
switch (c6) {
/* istanbul ignore next */
case "/": {
return false;
}
case "\\":
if (inClass && pattern.charAt(i5 + 1) === "-") {
re += c6;
continue;
}
clearStateChar();
escaping = true;
continue;
// the various stateChar values
// for the "extglob" stuff.
case "?":
case "*":
case "+":
case "@":
case "!":
this.debug("%s %s %s %j <-- stateChar", pattern, i5, re, c6);
if (inClass) {
this.debug(" in class");
if (c6 === "!" && i5 === classStart + 1) c6 = "^";
re += c6;
continue;
}
this.debug("call clearStateChar %j", stateChar);
clearStateChar();
stateChar = c6;
if (options.noext) clearStateChar();
continue;
case "(": {
if (inClass) {
re += "(";
continue;
}
if (!stateChar) {
re += "\\(";
continue;
}
const plEntry = {
type: stateChar,
start: i5 - 1,
reStart: re.length,
open: plTypes[stateChar].open,
close: plTypes[stateChar].close
};
this.debug(this.pattern, " ", plEntry);
patternListStack.push(plEntry);
re += plEntry.open;
if (plEntry.start === 0 && plEntry.type !== "!") {
dotTravAllowed = true;
re += subPatternStart(pattern.slice(i5 + 1));
}
this.debug("plType %j %j", stateChar, re);
stateChar = false;
continue;
}
case ")": {
const plEntry = patternListStack[patternListStack.length - 1];
if (inClass || !plEntry) {
re += "\\)";
continue;
}
patternListStack.pop();
clearStateChar();
hasMagic = true;
pl2 = plEntry;
re += pl2.close;
if (pl2.type === "!") {
negativeLists.push(Object.assign(pl2, { reEnd: re.length }));
}
continue;
}
case "|": {
const plEntry = patternListStack[patternListStack.length - 1];
if (inClass || !plEntry) {
re += "\\|";
continue;
}
clearStateChar();
re += "|";
if (plEntry.start === 0 && plEntry.type !== "!") {
dotTravAllowed = true;
re += subPatternStart(pattern.slice(i5 + 1));
}
continue;
}
// these are mostly the same in regexp and glob
case "[":
clearStateChar();
if (inClass) {
re += "\\" + c6;
continue;
}
inClass = true;
classStart = i5;
reClassStart = re.length;
re += c6;
continue;
case "]":
if (i5 === classStart + 1 || !inClass) {
re += "\\" + c6;
continue;
}
cs2 = pattern.substring(classStart + 1, i5);
try {
RegExp("[" + braExpEscape(charUnescape(cs2)) + "]");
re += c6;
} catch (er) {
re = re.substring(0, reClassStart) + "(?:$.)";
}
hasMagic = true;
inClass = false;
continue;
default:
clearStateChar();
if (reSpecials[c6] && !(c6 === "^" && inClass)) {
re += "\\";
}
re += c6;
break;
}
}
if (inClass) {
cs2 = pattern.slice(classStart + 1);
sp = this.parse(cs2, SUBPARSE);
re = re.substring(0, reClassStart) + "\\[" + sp[0];
hasMagic = hasMagic || sp[1];
}
for (pl2 = patternListStack.pop(); pl2; pl2 = patternListStack.pop()) {
let tail;
tail = re.slice(pl2.reStart + pl2.open.length);
this.debug("setting tail", re, pl2);
tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_4, $1, $2) => {
if (!$2) {
$2 = "\\";
}
return $1 + $1 + $2 + "|";
});
this.debug("tail=%j\n %s", tail, tail, pl2, re);
const t7 = pl2.type === "*" ? star : pl2.type === "?" ? qmark : "\\" + pl2.type;
hasMagic = true;
re = re.slice(0, pl2.reStart) + t7 + "\\(" + tail;
}
clearStateChar();
if (escaping) {
re += "\\\\";
}
const addPatternStart = addPatternStartSet[re.charAt(0)];
for (let n6 = negativeLists.length - 1; n6 > -1; n6--) {
const nl = negativeLists[n6];
const nlBefore = re.slice(0, nl.reStart);
const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
let nlAfter = re.slice(nl.reEnd);
const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
const closeParensBefore = nlBefore.split(")").length;
const openParensBefore = nlBefore.split("(").length - closeParensBefore;
let cleanAfter = nlAfter;
for (let i5 = 0; i5 < openParensBefore; i5++) {
cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
}
nlAfter = cleanAfter;
const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
}
if (re !== "" && hasMagic) {
re = "(?=.)" + re;
}
if (addPatternStart) {
re = patternStart() + re;
}
if (isSub === SUBPARSE) {
return [re, hasMagic];
}
if (options.nocase && !hasMagic) {
hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
}
if (!hasMagic) {
return globUnescape(pattern);
}
const flags2 = options.nocase ? "i" : "";
try {
return Object.assign(new RegExp("^" + re + "$", flags2), {
_glob: pattern,
_src: re
});
} catch (er) {
return new RegExp("$.");
}
}
makeRe() {
if (this.regexp || this.regexp === false) return this.regexp;
const set = this.set;
if (!set.length) {
this.regexp = false;
return this.regexp;
}
const options = this.options;
const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
const flags2 = options.nocase ? "i" : "";
let re = set.map((pattern) => {
pattern = pattern.map(
(p6) => typeof p6 === "string" ? regExpEscape(p6) : p6 === GLOBSTAR ? GLOBSTAR : p6._src
).reduce((set2, p6) => {
if (!(set2[set2.length - 1] === GLOBSTAR && p6 === GLOBSTAR)) {
set2.push(p6);
}
return set2;
}, []);
pattern.forEach((p6, i5) => {
if (p6 !== GLOBSTAR || pattern[i5 - 1] === GLOBSTAR) {
return;
}
if (i5 === 0) {
if (pattern.length > 1) {
pattern[i5 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i5 + 1];
} else {
pattern[i5] = twoStar;
}
} else if (i5 === pattern.length - 1) {
pattern[i5 - 1] += "(?:\\/|" + twoStar + ")?";
} else {
pattern[i5 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i5 + 1];
pattern[i5 + 1] = GLOBSTAR;
}
});
return pattern.filter((p6) => p6 !== GLOBSTAR).join("/");
}).join("|");
re = "^(?:" + re + ")$";
if (this.negate) re = "^(?!" + re + ").*$";
try {
this.regexp = new RegExp(re, flags2);
} catch (ex) {
this.regexp = false;
}
return this.regexp;
}
match(f6, partial = this.partial) {
this.debug("match", f6, this.pattern);
if (this.comment) return false;
if (this.empty) return f6 === "";
if (f6 === "/" && partial) return true;
const options = this.options;
if (path72.sep !== "/") {
f6 = f6.split(path72.sep).join("/");
}
f6 = f6.split(slashSplit);
this.debug(this.pattern, "split", f6);
const set = this.set;
this.debug(this.pattern, "set", set);
let filename;
for (let i5 = f6.length - 1; i5 >= 0; i5--) {
filename = f6[i5];
if (filename) break;
}
for (let i5 = 0; i5 < set.length; i5++) {
const pattern = set[i5];
let file = f6;
if (options.matchBase && pattern.length === 1) {
file = [filename];
}
const hit = this.matchOne(file, pattern, partial);
if (hit) {
if (options.flipNegate) return true;
return !this.negate;
}
}
if (options.flipNegate) return false;
return this.negate;
}
static defaults(def) {
return minimatch.defaults(def).Minimatch;
}
};
minimatch.Minimatch = Minimatch2;
}
});
// src/pages/hash.ts
var import_node_fs25, import_node_path44, import_blake3_wasm, hashFile;
var init_hash = __esm({
"src/pages/hash.ts"() {
init_import_meta_url();
import_node_fs25 = require("fs");
import_node_path44 = require("path");
import_blake3_wasm = require("blake3-wasm");
hashFile = /* @__PURE__ */ __name((filepath) => {
const contents = (0, import_node_fs25.readFileSync)(filepath);
const base64Contents = contents.toString("base64");
const extension = (0, import_node_path44.extname)(filepath).substring(1);
return (0, import_blake3_wasm.hash)(base64Contents + extension).toString("hex").slice(0, 32);
}, "hashFile");
}
});
// src/pages/validate.ts
var import_promises19, import_node_path45, import_mime2, import_minimatch, pagesProjectValidateCommand, validate;
var init_validate2 = __esm({
"src/pages/validate.ts"() {
init_import_meta_url();
import_promises19 = require("fs/promises");
import_node_path45 = require("path");
import_mime2 = __toESM(require_mime());
import_minimatch = __toESM(require_minimatch());
init_pretty_bytes();
init_create_command();
init_errors();
init_constants();
init_hash();
pagesProjectValidateCommand = createCommand({
metadata: {
description: "Validate a Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hidden: true
},
behaviour: {
provideConfig: false
},
args: {
directory: {
type: "string",
demandOption: true,
description: "The directory of static files to validate"
}
},
positionalArgs: ["directory"],
async handler({ directory }) {
if (!directory) {
throw new FatalError("Must specify a directory.", 1);
}
await validate({
directory
});
}
});
validate = /* @__PURE__ */ __name(async (args) => {
const IGNORE_LIST = [
"_worker.js",
"_redirects",
"_headers",
"_routes.json",
"functions",
"**/.DS_Store",
"**/node_modules",
"**/.git"
].map((pattern) => new import_minimatch.Minimatch(pattern));
const directory = (0, import_node_path45.resolve)(args.directory);
const walk = /* @__PURE__ */ __name(async (dir, fileMap2 = /* @__PURE__ */ new Map(), startingDir = dir) => {
const files = await (0, import_promises19.readdir)(dir);
await Promise.all(
files.map(async (file) => {
const filepath = (0, import_node_path45.join)(dir, file);
const relativeFilepath = (0, import_node_path45.relative)(startingDir, filepath);
const filestat = await (0, import_promises19.stat)(filepath);
for (const minimatch of IGNORE_LIST) {
if (minimatch.match(relativeFilepath)) {
return;
}
}
if (filestat.isSymbolicLink()) {
return;
}
if (filestat.isDirectory()) {
fileMap2 = await walk(filepath, fileMap2, startingDir);
} else {
const name2 = relativeFilepath.split(import_node_path45.sep).join("/");
if (filestat.size > MAX_ASSET_SIZE) {
throw new FatalError(
`Error: Pages only supports files up to ${prettyBytes(
MAX_ASSET_SIZE,
{ binary: true }
)} in size
${name2} is ${prettyBytes(filestat.size, {
binary: true
})} in size`,
1
);
}
fileMap2.set(name2, {
path: filepath,
contentType: (0, import_mime2.getType)(name2) || "application/octet-stream",
sizeInBytes: filestat.size,
hash: hashFile(filepath)
});
}
})
);
return fileMap2;
}, "walk");
const fileMap = await walk(directory);
if (fileMap.size > MAX_ASSET_COUNT) {
throw new FatalError(
`Error: Pages only supports up to ${MAX_ASSET_COUNT.toLocaleString()} files in a deployment. Ensure you have specified your build output directory correctly.`,
1
);
}
return fileMap;
}, "validate");
}
});
// src/pages/upload.ts
function formatTime2(duration) {
return `(${(duration / 1e3).toFixed(2)} sec)`;
}
function renderProgress(done, total) {
const s5 = spinner();
if (isInteractive2()) {
s5.start(`Uploading... (${done}/${total})
`);
return {
update: /* @__PURE__ */ __name((d6, t7) => s5.update(`Uploading... (${d6}/${t7})
`), "update"),
stop: s5.stop
};
} else {
logger.log(`Uploading... (${done}/${total})`);
return {
update: /* @__PURE__ */ __name((d6, t7) => logger.log(`Uploading... (${d6}/${t7})`), "update"),
stop: /* @__PURE__ */ __name(() => {
}, "stop")
};
}
}
var import_promises20, import_node_path46, pagesProjectUploadCommand, upload, isJwtExpired;
var init_upload = __esm({
"src/pages/upload.ts"() {
init_import_meta_url();
import_promises20 = require("fs/promises");
import_node_path46 = require("path");
init_interactive();
init_dist2();
init_cfetch();
init_create_command();
init_misc_variables();
init_errors();
init_is_interactive();
init_logger();
init_parse();
init_constants();
init_errors3();
init_validate2();
pagesProjectUploadCommand = createCommand({
metadata: {
description: "Upload files to a project",
status: "stable",
owner: "Workers: Authoring and Testing",
hidden: true
},
behaviour: {
provideConfig: false
},
args: {
directory: {
type: "string",
demandOption: true,
description: "The directory of static files to upload"
},
"output-manifest-path": {
type: "string",
description: "The name of the project you want to deploy to"
},
"skip-caching": {
type: "boolean",
description: "Skip asset caching which speeds up builds"
}
},
positionalArgs: ["directory"],
async handler({ directory, outputManifestPath, skipCaching }) {
if (!directory) {
throw new FatalError("Must specify a directory.", 1);
}
if (!process.env.CF_PAGES_UPLOAD_JWT) {
throw new FatalError("No JWT given.", 1);
}
const fileMap = await validate({ directory });
const manifest = await upload({
fileMap,
jwt: process.env.CF_PAGES_UPLOAD_JWT,
skipCaching: skipCaching ?? false
});
if (outputManifestPath) {
await (0, import_promises20.mkdir)((0, import_node_path46.dirname)(outputManifestPath), { recursive: true });
await (0, import_promises20.writeFile)(outputManifestPath, JSON.stringify(manifest));
}
logger.log(`\u2728 Upload complete!`);
}
});
upload = /* @__PURE__ */ __name(async (args) => {
async function fetchJwt() {
if ("jwt" in args) {
return args.jwt;
} else {
return (await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${args.accountId}/pages/projects/${args.projectName}/upload-token`
)).jwt;
}
}
__name(fetchJwt, "fetchJwt");
const files = [...args.fileMap.values()];
let jwt = await fetchJwt();
const start = Date.now();
let attempts = 0;
const getMissingHashes = /* @__PURE__ */ __name(async (skipCaching) => {
if (skipCaching) {
logger.debug("Force skipping cache");
return files.map(({ hash }) => hash);
}
try {
return await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/pages/assets/check-missing`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${jwt}`
},
body: JSON.stringify({
hashes: files.map(({ hash }) => hash)
})
}
);
} catch (e7) {
if (attempts < MAX_CHECK_MISSING_ATTEMPTS) {
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, attempts++) * 1e3)
);
if (e7.code === 8000013 /* UNAUTHORIZED */ || isJwtExpired(jwt)) {
jwt = await fetchJwt();
}
return getMissingHashes(skipCaching);
} else {
throw e7;
}
}
}, "getMissingHashes");
const missingHashes = await getMissingHashes(args.skipCaching);
const sortedFiles = files.filter((file) => missingHashes.includes(file.hash)).sort((a5, b6) => b6.sizeInBytes - a5.sizeInBytes);
const buckets = new Array(BULK_UPLOAD_CONCURRENCY).fill(null).map(() => ({
files: [],
remainingSize: MAX_BUCKET_SIZE
}));
let bucketOffset = 0;
for (const file of sortedFiles) {
let inserted = false;
for (let i5 = 0; i5 < buckets.length; i5++) {
const bucket = buckets[(i5 + bucketOffset) % buckets.length];
if (bucket.remainingSize >= file.sizeInBytes && bucket.files.length < MAX_BUCKET_FILE_COUNT) {
bucket.files.push(file);
bucket.remainingSize -= file.sizeInBytes;
inserted = true;
break;
}
}
if (!inserted) {
buckets.push({
files: [file],
remainingSize: MAX_BUCKET_SIZE - file.sizeInBytes
});
}
bucketOffset++;
}
let counter = args.fileMap.size - sortedFiles.length;
const { update, stop } = renderProgress(counter, args.fileMap.size);
const queue = new PQueue({ concurrency: BULK_UPLOAD_CONCURRENCY });
const queuePromises = [];
for (const bucket of buckets) {
if (bucket.files.length === 0) {
continue;
}
attempts = 0;
let gatewayErrors = 0;
const doUpload = /* @__PURE__ */ __name(async () => {
const payload = await Promise.all(
bucket.files.map(async (file) => ({
key: file.hash,
value: (await (0, import_promises20.readFile)(file.path)).toString("base64"),
metadata: {
contentType: file.contentType
},
base64: true
}))
);
try {
logger.debug("POST /pages/assets/upload");
const res = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/pages/assets/upload`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${jwt}`
},
body: JSON.stringify(payload)
}
);
logger.debug("result:", res);
} catch (e7) {
if (attempts < MAX_UPLOAD_ATTEMPTS) {
logger.debug("failed:", e7, "retrying...");
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, attempts) * 1e3)
);
if (e7 instanceof APIError && e7.isGatewayError()) {
queue.concurrency = 1;
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, gatewayErrors) * 5e3)
);
gatewayErrors++;
if (gatewayErrors >= MAX_UPLOAD_GATEWAY_ERRORS) {
attempts++;
}
} else if (e7.code === 8000013 /* UNAUTHORIZED */ || isJwtExpired(jwt)) {
jwt = await fetchJwt();
} else {
attempts++;
}
return doUpload();
} else {
logger.debug("failed:", e7);
throw e7;
}
}
}, "doUpload");
queuePromises.push(
queue.add(
() => doUpload().then(
() => {
counter += bucket.files.length;
update(counter, args.fileMap.size);
},
(error2) => {
return Promise.reject(
new FatalError(
`Failed to upload files. Please try again. Error: ${JSON.stringify(
error2
)})`,
error2.code || 1
)
);
}
)
)
);
}
await Promise.all(queuePromises);
stop();
const uploadMs = Date.now() - start;
const skipped = args.fileMap.size - missingHashes.length;
const skippedMessage = skipped > 0 ? `(${skipped} already uploaded) ` : "";
logger.log(
`\u2728 Success! Uploaded ${sortedFiles.length} files ${skippedMessage}${formatTime2(uploadMs)}
`
);
const doUpsertHashes = /* @__PURE__ */ __name(async () => {
try {
return await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/pages/assets/upsert-hashes`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${jwt}`
},
body: JSON.stringify({
hashes: files.map(({ hash }) => hash)
})
}
);
} catch (e7) {
await new Promise((resolvePromise) => setTimeout(resolvePromise, 1e3));
if (e7.code === 8000013 /* UNAUTHORIZED */ || isJwtExpired(jwt)) {
jwt = await fetchJwt();
}
return await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/pages/assets/upsert-hashes`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${jwt}`
},
body: JSON.stringify({
hashes: files.map(({ hash }) => hash)
})
}
);
}
}, "doUpsertHashes");
try {
await doUpsertHashes();
} catch {
logger.warn(
"Failed to update file hashes. Every upload appeared to succeed for this deployment, but you might need to re-upload for future deployments. This shouldn't have any impact other than slowing the upload speed of your next deployment."
);
}
return Object.fromEntries(
[...args.fileMap.entries()].map(([fileName, file]) => [
`/${fileName}`,
file.hash
])
);
}, "upload");
isJwtExpired = /* @__PURE__ */ __name((token) => {
if (typeof vitest !== "undefined" && (token === "<<funfetti-auth-jwt>>" || token === "<<funfetti-auth-jwt2>>" || token === "<<aus-completion-token>>")) {
return false;
}
try {
const decodedJwt = JSON.parse(
Buffer.from(token.split(".")[1], "base64").toString()
);
const dateNow = (/* @__PURE__ */ new Date()).getTime() / 1e3;
return decodedJwt.exp <= dateNow;
} catch (e7) {
if (e7 instanceof Error) {
throw new Error(`Invalid token: ${e7.message}`);
}
}
}, "isJwtExpired");
__name(formatTime2, "formatTime");
__name(renderProgress, "renderProgress");
}
});
// src/api/pages/deploy.ts
async function deploy2({
directory,
accountId,
projectName,
branch,
skipCaching,
commitMessage,
commitHash,
commitDirty,
functionsDirectory: customFunctionsDirectory,
bundle,
sourceMaps,
args
}) {
let _headers, _redirects, _routesGenerated, _routesCustom, _workerJSIsDirectory = false, _workerJS;
bundle = bundle ?? true;
const _workerPath = (0, import_node_path47.resolve)(directory, "_worker.js");
try {
_headers = (0, import_node_fs26.readFileSync)((0, import_node_path47.join)(directory, "_headers"), "utf-8");
} catch {
}
try {
_redirects = (0, import_node_fs26.readFileSync)((0, import_node_path47.join)(directory, "_redirects"), "utf-8");
} catch {
}
try {
_routesCustom = (0, import_node_fs26.readFileSync)((0, import_node_path47.join)(directory, "_routes.json"), "utf-8");
} catch {
}
try {
_workerJSIsDirectory = (0, import_node_fs26.lstatSync)(_workerPath).isDirectory();
if (!_workerJSIsDirectory) {
_workerJS = (0, import_node_fs26.readFileSync)(_workerPath, "utf-8");
}
} catch {
}
const project = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}`
);
let isProduction = true;
if (branch) {
isProduction = project.production_branch === branch;
}
const env6 = isProduction ? "production" : "preview";
const deploymentConfig = project.deployment_configs[env6];
let config;
try {
config = readPagesConfig(
{ ...args, env: env6 },
{ useRedirectIfAvailable: true }
);
} catch (err) {
if (!(err instanceof FatalError && err.code === EXIT_CODE_INVALID_PAGES_CONFIG)) {
throw err;
}
}
const nodejsCompatMode = validateNodeCompatMode(
config?.compatibility_date ?? deploymentConfig.compatibility_date,
config?.compatibility_flags ?? deploymentConfig.compatibility_flags ?? [],
{
noBundle: config?.no_bundle
}
);
const defineNavigatorUserAgent = isNavigatorDefined(
config?.compatibility_date ?? deploymentConfig.compatibility_date,
config?.compatibility_flags ?? deploymentConfig.compatibility_flags
);
const checkFetch = shouldCheckFetch(
config?.compatibility_date ?? deploymentConfig.compatibility_date,
config?.compatibility_flags ?? deploymentConfig.compatibility_flags
);
let builtFunctions = void 0;
let workerBundle = void 0;
const functionsDirectory = customFunctionsDirectory || (0, import_node_path47.join)((0, import_node_process11.cwd)(), "functions");
const routesOutputPath = !(0, import_node_fs26.existsSync)((0, import_node_path47.join)(directory, "_routes.json")) ? (0, import_node_path47.join)(getPagesTmpDir(), `_routes-${Math.random()}.json`) : void 0;
let filepathRoutingConfig;
if (!_workerJS && (0, import_node_fs26.existsSync)(functionsDirectory)) {
const outputConfigPath = (0, import_node_path47.join)(
getPagesTmpDir(),
`functions-filepath-routing-config-${Math.random()}.json`
);
try {
workerBundle = await buildFunctions({
outputConfigPath,
functionsDirectory,
sourcemap: sourceMaps,
onEnd: /* @__PURE__ */ __name(() => {
}, "onEnd"),
buildOutputDirectory: directory,
routesOutputPath,
local: false,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch
});
builtFunctions = (0, import_node_fs26.readFileSync)(
workerBundle.resolvedEntryPointPath,
"utf-8"
);
filepathRoutingConfig = (0, import_node_fs26.readFileSync)(outputConfigPath, "utf-8");
} catch (e7) {
if (e7 instanceof FunctionsNoRoutesError) {
logger.warn(
getFunctionsNoRoutesWarning(functionsDirectory, "skipping")
);
} else {
throw e7;
}
}
}
const fileMap = await validate({ directory });
const manifest = await upload({
fileMap,
accountId,
projectName,
skipCaching: skipCaching ?? false
});
const formData = new import_undici12.FormData();
formData.append("manifest", JSON.stringify(manifest));
if (branch) {
formData.append("branch", branch);
}
if (commitMessage) {
formData.append("commit_message", commitMessage);
}
if (commitHash) {
formData.append("commit_hash", commitHash);
}
if (commitDirty !== void 0) {
formData.append("commit_dirty", commitDirty);
}
if (_headers) {
formData.append("_headers", new File([_headers], "_headers"));
logger.log(`\u2728 Uploading _headers`);
}
if (_redirects) {
formData.append("_redirects", new File([_redirects], "_redirects"));
logger.log(`\u2728 Uploading _redirects`);
}
if (filepathRoutingConfig) {
formData.append(
"functions-filepath-routing-config.json",
new File(
[filepathRoutingConfig],
"functions-filepath-routing-config.json"
)
);
}
if (config !== void 0 && config.configPath !== void 0 && config.pages_build_output_dir) {
const configHash = (0, import_node_crypto9.createHash)("sha256").update(await (0, import_promises21.readFile)(config.configPath)).digest("hex");
const outputDir = import_node_path47.default.relative(
process.cwd(),
config.pages_build_output_dir
);
formData.append("wrangler_config_hash", configHash);
formData.append("pages_build_output_dir", outputDir);
}
if (_workerJSIsDirectory) {
workerBundle = await produceWorkerBundleForWorkerJSDirectory({
workerJSDirectory: _workerPath,
bundle,
buildOutputDirectory: directory,
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
sourceMaps
});
} else if (_workerJS) {
if (bundle) {
const outfile = (0, import_node_path47.join)(
getPagesTmpDir(),
`./bundledWorker-${Math.random()}.mjs`
);
workerBundle = await buildRawWorker({
workerScriptPath: _workerPath,
outfile,
directory,
local: false,
sourcemap: true,
watch: false,
onEnd: /* @__PURE__ */ __name(() => {
}, "onEnd"),
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch
});
} else {
await checkRawWorker(_workerPath, nodejsCompatMode, () => {
});
workerBundle = {
modules: [],
dependencies: {},
stop: void 0,
resolvedEntryPointPath: _workerPath,
bundleType: "esm"
};
}
}
if (_workerJS || _workerJSIsDirectory) {
const workerBundleContents = await createUploadWorkerBundleContents(
workerBundle,
config
);
formData.append(
"_worker.bundle",
new File([workerBundleContents], "_worker.bundle")
);
logger.log(`\u2728 Uploading Worker bundle`);
if (_routesCustom) {
try {
const routesCustomJSON = JSON.parse(_routesCustom);
validateRoutes(routesCustomJSON, (0, import_node_path47.join)(directory, "_routes.json"));
formData.append(
"_routes.json",
new File([_routesCustom], "_routes.json")
);
logger.log(`\u2728 Uploading _routes.json`);
} catch (err) {
if (err instanceof FatalError) {
throw err;
}
}
}
}
if (builtFunctions && !_workerJS && !_workerJSIsDirectory) {
const workerBundleContents = await createUploadWorkerBundleContents(
workerBundle,
config
);
formData.append(
"_worker.bundle",
new File([workerBundleContents], "_worker.bundle")
);
logger.log(`\u2728 Uploading Functions bundle`);
if (_routesCustom) {
try {
const routesCustomJSON = JSON.parse(_routesCustom);
validateRoutes(routesCustomJSON, (0, import_node_path47.join)(directory, "_routes.json"));
formData.append(
"_routes.json",
new File([_routesCustom], "_routes.json")
);
logger.log(`\u2728 Uploading _routes.json`);
} catch (err) {
if (err instanceof FatalError) {
throw err;
}
}
} else if (routesOutputPath) {
try {
_routesGenerated = (0, import_node_fs26.readFileSync)(routesOutputPath, "utf-8");
if (_routesGenerated) {
formData.append(
"_routes.json",
new File([_routesGenerated], "_routes.json")
);
}
} catch {
}
}
}
let attempts = 0;
let lastErr;
while (attempts < MAX_DEPLOYMENT_ATTEMPTS) {
try {
const deploymentResponse = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments`,
{
method: "POST",
body: formData
}
);
return { deploymentResponse, formData };
} catch (e7) {
lastErr = e7;
if (e7.code === 8e6 /* UNKNOWN_ERROR */ && attempts < MAX_DEPLOYMENT_ATTEMPTS) {
logger.debug("failed:", e7, "retrying...");
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, attempts++) * 1e3)
);
} else {
logger.debug("failed:", e7);
throw e7;
}
}
}
throw lastErr;
}
var import_node_crypto9, import_node_fs26, import_promises21, import_node_path47, import_node_process11, import_undici12;
var init_deploy5 = __esm({
"src/api/pages/deploy.ts"() {
init_import_meta_url();
import_node_crypto9 = require("crypto");
import_node_fs26 = require("fs");
import_promises21 = require("fs/promises");
import_node_path47 = __toESM(require("path"));
import_node_process11 = require("process");
import_undici12 = __toESM(require_undici());
init_cfetch();
init_config2();
init_bundle();
init_node_compat();
init_misc_variables();
init_errors();
init_logger();
init_navigator_user_agent();
init_buildFunctions();
init_constants();
init_errors3();
init_buildWorker();
init_routes_validation();
init_upload();
init_utils6();
init_validate2();
init_create_worker_bundle_contents();
__name(deploy2, "deploy");
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/lang/en_US.js
function en_US_default(diff, idx) {
if (idx === 0)
return ["just now", "right now"];
var unit = EN_US[Math.floor(idx / 2)];
if (diff > 1)
unit += "s";
return [diff + " " + unit + " ago", "in " + diff + " " + unit];
}
var EN_US;
var init_en_US = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/lang/en_US.js"() {
init_import_meta_url();
EN_US = ["second", "minute", "hour", "day", "week", "month", "year"];
__name(en_US_default, "default");
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/lang/zh_CN.js
function zh_CN_default(diff, idx) {
if (idx === 0)
return ["\u521A\u521A", "\u7247\u523B\u540E"];
var unit = ZH_CN[~~(idx / 2)];
return [diff + " " + unit + "\u524D", diff + " " + unit + "\u540E"];
}
var ZH_CN;
var init_zh_CN = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/lang/zh_CN.js"() {
init_import_meta_url();
ZH_CN = ["\u79D2", "\u5206\u949F", "\u5C0F\u65F6", "\u5929", "\u5468", "\u4E2A\u6708", "\u5E74"];
__name(zh_CN_default, "default");
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/register.js
var Locales, register, getLocale;
var init_register = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/register.js"() {
init_import_meta_url();
Locales = {};
register = /* @__PURE__ */ __name(function(locale, func) {
Locales[locale] = func;
}, "register");
getLocale = /* @__PURE__ */ __name(function(locale) {
return Locales[locale] || Locales["en_US"];
}, "getLocale");
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/utils/date.js
function toDate(input) {
if (input instanceof Date)
return input;
if (!isNaN(input) || /^\d+$/.test(input))
return new Date(parseInt(input));
input = (input || "").trim().replace(/\.\d+/, "").replace(/-/, "/").replace(/-/, "/").replace(/(\d)T(\d)/, "$1 $2").replace(/Z/, " UTC").replace(/([+-]\d\d):?(\d\d)/, " $1$2");
return new Date(input);
}
function formatDiff(diff, localeFunc) {
var agoIn = diff < 0 ? 1 : 0;
diff = Math.abs(diff);
var totalSec = diff;
var idx = 0;
for (; diff >= SEC_ARRAY[idx] && idx < SEC_ARRAY.length; idx++) {
diff /= SEC_ARRAY[idx];
}
diff = Math.floor(diff);
idx *= 2;
if (diff > (idx === 0 ? 9 : 1))
idx += 1;
return localeFunc(diff, idx, totalSec)[agoIn].replace("%s", diff.toString());
}
function diffSec(date, relativeDate) {
var relDate = relativeDate ? toDate(relativeDate) : /* @__PURE__ */ new Date();
return (+relDate - +toDate(date)) / 1e3;
}
var SEC_ARRAY;
var init_date = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/utils/date.js"() {
init_import_meta_url();
SEC_ARRAY = [
60,
60,
24,
7,
365 / 7 / 12,
12
];
__name(toDate, "toDate");
__name(formatDiff, "formatDiff");
__name(diffSec, "diffSec");
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/format.js
var format7;
var init_format2 = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/format.js"() {
init_import_meta_url();
init_date();
init_register();
format7 = /* @__PURE__ */ __name(function(date, locale, opts) {
var sec = diffSec(date, opts && opts.relativeDate);
return formatDiff(sec, getLocale(locale));
}, "format");
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/utils/dom.js
var init_dom = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/utils/dom.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/realtime.js
var init_realtime2 = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/realtime.js"() {
init_import_meta_url();
init_dom();
init_date();
init_register();
}
});
// ../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/index.js
var init_esm5 = __esm({
"../../node_modules/.pnpm/timeago.js@4.0.2/node_modules/timeago.js/esm/index.js"() {
init_import_meta_url();
init_en_US();
init_zh_CN();
init_register();
init_format2();
init_realtime2();
register("en_US", en_US_default);
register("zh_CN", zh_CN_default);
}
});
// src/pages/projects.ts
var import_node_child_process4, pagesProjectListCommand, listProjects, pagesProjectCreateCommand, pagesProjectDeleteCommand;
var init_projects = __esm({
"src/pages/projects.ts"() {
init_import_meta_url();
import_node_child_process4 = require("child_process");
init_esm5();
init_cfetch();
init_config_cache();
init_create_command();
init_dialogs();
init_misc_variables();
init_errors();
init_logger();
init_metrics();
init_user2();
init_auth_variables();
init_constants();
pagesProjectListCommand = createCommand({
metadata: {
description: "List your Cloudflare Pages projects",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
async handler() {
const config = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = getCloudflareAccountIdFromEnv() ?? await requireAuth(config);
const projects = await listProjects({ accountId });
const data = projects.map((project) => {
return {
"Project Name": project.name,
"Project Domains": `${project.domains.join(", ")}`,
"Git Provider": project.source ? "Yes" : "No",
"Last Modified": project.latest_deployment ? format7(project.latest_deployment.modified_on) : format7(project.created_on)
};
});
saveToConfigCache(PAGES_CONFIG_CACHE_FILENAME, {
account_id: accountId
});
logger.table(data);
sendMetricsEvent("list pages projects");
}
});
listProjects = /* @__PURE__ */ __name(async ({
accountId
}) => {
const pageSize = 10;
let page = 1;
const results = [];
while (results.length % pageSize === 0) {
const json = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects`,
{},
new URLSearchParams({
per_page: pageSize.toString(),
page: page.toString()
})
);
page++;
results.push(...json);
if (json.length < pageSize) {
break;
}
}
return results;
}, "listProjects");
pagesProjectCreateCommand = createCommand({
metadata: {
description: "Create a new Cloudflare Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
"project-name": {
type: "string",
demandOption: true,
description: "The name of your Pages project"
},
"production-branch": {
type: "string",
description: "The name of the production branch of your project"
},
"compatibility-flags": {
description: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
requiresArg: true,
array: true
},
"compatibility-date": {
description: "Date to use for compatibility checks",
type: "string",
requiresArg: true
}
},
positionalArgs: ["project-name"],
async handler({
productionBranch,
compatibilityFlags,
compatibilityDate,
projectName
}) {
const config = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = getCloudflareAccountIdFromEnv() ?? await requireAuth(config);
const isInteractive3 = process.stdin.isTTY;
if (!projectName && isInteractive3) {
projectName = await prompt("Enter the name of your new project:");
}
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
if (!productionBranch && isInteractive3) {
let isGitDir = true;
try {
(0, import_node_child_process4.execSync)(`git rev-parse --is-inside-work-tree`, {
stdio: "ignore"
});
} catch {
isGitDir = false;
}
if (isGitDir) {
try {
productionBranch = (0, import_node_child_process4.execSync)(`git rev-parse --abbrev-ref HEAD`).toString().trim();
} catch {
}
}
productionBranch = await prompt("Enter the production branch name:", {
defaultValue: productionBranch ?? "production"
});
}
if (!productionBranch) {
throw new FatalError("Must specify a production branch.", 1);
}
const deploymentConfig = {
...compatibilityFlags && {
compatibility_flags: [...compatibilityFlags]
},
...compatibilityDate && {
compatibility_date: compatibilityDate
}
};
const body = {
name: projectName,
production_branch: productionBranch,
deployment_configs: {
production: { ...deploymentConfig },
preview: { ...deploymentConfig }
}
};
const { subdomain } = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects`,
{
method: "POST",
body: JSON.stringify(body)
}
);
saveToConfigCache(PAGES_CONFIG_CACHE_FILENAME, {
account_id: accountId,
project_name: projectName
});
logger.log(
`\u2728 Successfully created the '${projectName}' project. It will be available at https://${subdomain}/ once you create your first deployment.`
);
logger.log(
`To deploy a folder of assets, run 'wrangler pages deploy [directory]'.`
);
sendMetricsEvent("create pages project");
}
});
pagesProjectDeleteCommand = createCommand({
metadata: {
description: "Delete a Cloudflare Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
"project-name": {
type: "string",
description: "The name of your Pages project",
demandOption: true
},
yes: {
alias: "y",
type: "boolean",
description: 'Answer "yes" to confirm project deletion'
}
},
positionalArgs: ["project-name"],
async handler(args) {
const config = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = getCloudflareAccountIdFromEnv() ?? await requireAuth(config);
const confirmed = args.yes || await confirm(
`Are you sure you want to delete "${args.projectName}"? This action cannot be undone.`
);
if (confirmed) {
logger.log("Deleting", args.projectName);
await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${args.projectName}`,
{ method: "DELETE" }
);
logger.log("Successfully deleted", args.projectName);
}
}
});
}
});
// src/pages/prompt-select-project.ts
async function promptSelectProject({
accountId
}) {
const projects = await listProjects({ accountId });
return select("Select a project:", {
choices: projects.map((project) => ({
title: project.name,
value: project.name
}))
});
}
var init_prompt_select_project = __esm({
"src/pages/prompt-select-project.ts"() {
init_import_meta_url();
init_dialogs();
init_projects();
__name(promptSelectProject, "promptSelectProject");
}
});
// src/pages/deploy.ts
function promptSelectExistingOrNewProject(message, items) {
return select(message, {
choices: items.map((i5) => ({ title: i5.label, value: i5.value }))
});
}
var import_node_child_process5, import_promises22, import_node_path48, pagesDeploymentCreateCommand, pagesPublishCommand, pagesDeployCommand;
var init_deploy6 = __esm({
"src/pages/deploy.ts"() {
init_import_meta_url();
import_node_child_process5 = require("child_process");
import_promises22 = require("fs/promises");
import_node_path48 = __toESM(require("path"));
init_deploy5();
init_cfetch();
init_config2();
init_config_cache();
init_config_helpers();
init_create_command();
init_dialogs();
init_misc_variables();
init_errors();
init_logger();
init_metrics();
init_output();
init_parse();
init_user2();
init_friendly_validator_errors();
init_constants();
init_errors3();
init_projects();
init_prompt_select_project();
init_utils6();
pagesDeploymentCreateCommand = createAlias({
aliasOf: "wrangler pages deploy"
});
pagesPublishCommand = createAlias({
aliasOf: "wrangler pages deploy",
metadata: {
deprecated: true,
hidden: true
}
});
pagesDeployCommand = createCommand({
metadata: {
description: "Deploy a directory of static assets as a Pages deployment",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
directory: {
type: "string",
description: "The directory of static files to upload"
},
"project-name": {
type: "string",
description: "The name of the project you want to deploy to"
},
branch: {
type: "string",
description: "The name of the branch you want to deploy to"
},
"commit-hash": {
type: "string",
description: "The SHA to attach to this deployment"
},
"commit-message": {
type: "string",
description: "The commit message to attach to this deployment"
},
"commit-dirty": {
type: "boolean",
description: "Whether or not the workspace should be considered dirty for this deployment"
},
"skip-caching": {
type: "boolean",
description: "Skip asset caching which speeds up builds"
},
bundle: {
type: "boolean",
default: void 0,
hidden: true
},
"no-bundle": {
type: "boolean",
default: void 0,
description: "Whether to run bundling on `_worker.js` before deploying"
},
config: {
description: "Pages does not support custom Wrangler configuration file locations",
type: "string",
hidden: true
},
"upload-source-maps": {
type: "boolean",
default: false,
description: "Whether to upload any server-side sourcemaps with this deployment"
}
},
positionalArgs: ["directory"],
async handler(args) {
let { branch, commitHash, commitMessage, commitDirty } = args;
if (args._[1] === "publish") {
logger.warn(
"`wrangler pages publish` is deprecated and will be removed in the next major version.\nPlease use `wrangler pages deploy` instead, which accepts exactly the same arguments."
);
}
if (args.config) {
throw new FatalError(
"Pages does not support custom paths for the Wrangler configuration file",
1
);
}
if (args.env) {
throw new FatalError(
"Pages does not support targeting an environment with the --env flag. Use the --branch flag to target your production or preview branch",
1
);
}
let config;
const { configPath } = findWranglerConfig(process.cwd(), {
useRedirectIfAvailable: true
});
try {
config = readPagesConfig({ ...args, config: configPath, env: void 0 });
} catch (err) {
if (!(err instanceof FatalError && err.code === EXIT_CODE_INVALID_PAGES_CONFIG)) {
throw err;
}
}
if (configPath && config === void 0) {
logger.warn(
`Pages now has ${configFileName(configPath)} support.
We detected a configuration file at ${configPath} but it is missing the "pages_build_output_dir" field, required by Pages.
If you would like to use this configuration file to deploy your project, please use "pages_build_output_dir" to specify the directory of static files to upload.
Ignoring configuration file for now, and proceeding with project deploy.`
);
}
const directory = args.directory ?? config?.pages_build_output_dir;
if (!directory) {
throw new FatalError(
`Must specify a directory of assets to deploy. Please specify the [<directory>] argument in the \`pages deploy\` command, or configure \`pages_build_output_dir\` in your ${configFileName(configPath)} file.`,
1
);
}
const configCache = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = await requireAuth(configCache);
let projectName = args.projectName ?? config?.name ?? configCache.project_name;
let isExistingProject = true;
if (projectName) {
try {
await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}`
);
} catch (err) {
if (err.code !== 8000007) {
throw err;
} else {
isExistingProject = false;
}
}
}
const isInteractive3 = process.stdin.isTTY;
if ((!projectName || !isExistingProject) && isInteractive3) {
let existingOrNew = "new";
if (!projectName) {
const duProjects = (await listProjects({ accountId })).filter(
(project) => !project.source
);
if (duProjects.length > 0) {
const message = "No project specified. Would you like to create one or use an existing project?";
const items = [
{
key: "new",
label: "Create a new project",
value: "new"
},
{
key: "existing",
label: "Use an existing project",
value: "existing"
}
];
existingOrNew = await promptSelectExistingOrNewProject(
message,
items
);
}
}
if (projectName !== void 0 && !isExistingProject) {
const message = `The project you specified does not exist: "${projectName}". Would you like to create it?`;
const items = [
{
key: "new",
label: "Create a new project",
value: "new"
}
];
existingOrNew = await promptSelectExistingOrNewProject(message, items);
}
switch (existingOrNew) {
case "existing": {
projectName = await promptSelectProject({ accountId });
break;
}
case "new": {
if (!projectName) {
projectName = await prompt("Enter the name of your new project:");
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
}
let isGitDir2 = true;
try {
(0, import_node_child_process5.execSync)(`git rev-parse --is-inside-work-tree`, {
stdio: "ignore"
});
} catch {
isGitDir2 = false;
}
let productionBranch;
if (isGitDir2) {
try {
productionBranch = (0, import_node_child_process5.execSync)(`git rev-parse --abbrev-ref HEAD`).toString().trim();
} catch {
}
}
productionBranch = await prompt("Enter the production branch name:", {
defaultValue: productionBranch ?? "production"
});
if (!productionBranch) {
throw new FatalError("Must specify a production branch.", 1);
}
await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects`,
{
method: "POST",
body: JSON.stringify({
name: projectName,
production_branch: productionBranch
})
}
);
saveToConfigCache(PAGES_CONFIG_CACHE_FILENAME, {
account_id: accountId,
project_name: projectName
});
logger.log(`\u2728 Successfully created the '${projectName}' project.`);
sendMetricsEvent("create pages project");
break;
}
}
}
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
let isGitDir = true;
try {
(0, import_node_child_process5.execSync)(`git rev-parse --is-inside-work-tree`, {
stdio: "ignore"
});
} catch {
isGitDir = false;
}
let isGitDirty = false;
if (isGitDir) {
try {
isGitDirty = Boolean(
(0, import_node_child_process5.execSync)(`git status --porcelain`).toString().length
);
if (!branch) {
branch = (0, import_node_child_process5.execSync)(`git rev-parse --abbrev-ref HEAD`).toString().trim();
}
if (!commitHash) {
commitHash = (0, import_node_child_process5.execSync)(`git rev-parse HEAD`).toString().trim();
}
if (!commitMessage) {
commitMessage = (0, import_node_child_process5.execSync)(`git show -s --format=%B ${commitHash}`).toString().trim();
}
} catch {
}
if (isGitDirty && !commitDirty) {
logger.warn(
`Warning: Your working directory is a git repo and has uncommitted changes
To silence this warning, pass in --commit-dirty=true`
);
}
if (commitDirty === void 0) {
commitDirty = isGitDirty;
}
}
const enableBundling = args.bundle ?? !(args.noBundle ?? config?.no_bundle);
const { deploymentResponse, formData } = await deploy2({
directory,
accountId,
projectName,
branch,
commitMessage,
commitHash,
commitDirty,
skipCaching: args.skipCaching,
bundle: enableBundling,
// Sourcemaps from deploy arguments will take precedence so people can try it for one-off deployments without updating their wrangler.toml
sourceMaps: config?.upload_source_maps || args.uploadSourceMaps,
args
});
saveToConfigCache(PAGES_CONFIG_CACHE_FILENAME, {
account_id: accountId,
project_name: projectName
});
let latestDeploymentStage;
let alias;
let attempts = 0;
logger.log("\u{1F30E} Deploying...");
while (attempts < MAX_DEPLOYMENT_STATUS_ATTEMPTS && latestDeploymentStage?.name !== "deploy" && latestDeploymentStage?.status !== "success" && latestDeploymentStage?.status !== "failure") {
try {
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, attempts++) * 1e3)
);
logger.debug(
`attempt #${attempts}: Attempting to fetch status for deployment with id "${deploymentResponse.id}" ...`
);
const deployment = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments/${deploymentResponse.id}`
);
latestDeploymentStage = deployment.latest_stage;
alias = (deployment.aliases?.filter((a5) => a5.endsWith(".pages.dev")) ?? [])[0];
} catch (err) {
logger.debug(
`Attempt to get deployment status for deployment with id "${deploymentResponse.id}" failed: ${err}`
);
}
}
if (latestDeploymentStage?.name === "deploy" && latestDeploymentStage?.status === "success") {
logger.log(
`\u2728 Deployment complete! Take a peek over at ${deploymentResponse.url}` + (alias ? `
\u2728 Deployment alias URL: ${alias}` : "")
);
} else if (latestDeploymentStage?.name === "deploy" && latestDeploymentStage?.status === "failure") {
const logs = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments/${deploymentResponse.id}/history/logs?size=10000000`
);
const failureMessage = logs.data[logs.total - 1].line.replace("Error:", "").trim();
if (failureMessage.includes("Script startup exceeded CPU time limit")) {
const startupError = new ParseError({ text: failureMessage });
Object.assign(startupError, { code: 10021 });
const workerBundle = formData.get("_worker.bundle");
const filePath = import_node_path48.default.join(getPagesTmpDir(), "_worker.bundle");
await (0, import_promises22.writeFile)(filePath, workerBundle.stream());
throw new UserError(
await diagnoseStartupError(
startupError,
filePath,
getPagesProjectRoot()
)
);
}
throw new FatalError(
`Deployment failed!
${failureMessage}`,
1
);
} else {
logger.log(
`\u2728 Deployment complete! However, we couldn't ascertain the final status of your deployment.
\u26A1\uFE0F Visit your deployment at ${deploymentResponse.url}
\u26A1\uFE0F Check the deployment details on the Cloudflare dashboard: https://dash.cloudflare.com/${accountId}/pages/view/${projectName}/${deploymentResponse.id}`
);
}
writeOutput({
type: "pages-deploy",
version: 1,
pages_project: deploymentResponse.project_name,
deployment_id: deploymentResponse.id,
url: deploymentResponse.url
});
writeOutput({
type: "pages-deploy-detailed",
version: 1,
pages_project: deploymentResponse.project_name,
deployment_id: deploymentResponse.id,
url: deploymentResponse.url,
alias,
environment: deploymentResponse.environment,
production_branch: deploymentResponse.production_branch,
deployment_trigger: {
metadata: {
commit_hash: deploymentResponse.deployment_trigger?.metadata?.commit_hash ?? ""
}
}
});
sendMetricsEvent("create pages deployment");
}
});
__name(promptSelectExistingOrNewProject, "promptSelectExistingOrNewProject");
}
});
// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
var require_ms = __commonJS({
"../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports2, module3) {
init_import_meta_url();
var s5 = 1e3;
var m6 = s5 * 60;
var h6 = m6 * 60;
var d6 = h6 * 24;
var w6 = d6 * 7;
var y4 = d6 * 365.25;
module3.exports = function(val2, options) {
options = options || {};
var type = typeof val2;
if (type === "string" && val2.length > 0) {
return parse7(val2);
} else if (type === "number" && isFinite(val2)) {
return options.long ? fmtLong(val2) : fmtShort(val2);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val2)
);
};
function parse7(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match2) {
return;
}
var n6 = parseFloat(match2[1]);
var type = (match2[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n6 * y4;
case "weeks":
case "week":
case "w":
return n6 * w6;
case "days":
case "day":
case "d":
return n6 * d6;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n6 * h6;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n6 * m6;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n6 * s5;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n6;
default:
return void 0;
}
}
__name(parse7, "parse");
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d6) {
return Math.round(ms / d6) + "d";
}
if (msAbs >= h6) {
return Math.round(ms / h6) + "h";
}
if (msAbs >= m6) {
return Math.round(ms / m6) + "m";
}
if (msAbs >= s5) {
return Math.round(ms / s5) + "s";
}
return ms + "ms";
}
__name(fmtShort, "fmtShort");
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d6) {
return plural2(ms, msAbs, d6, "day");
}
if (msAbs >= h6) {
return plural2(ms, msAbs, h6, "hour");
}
if (msAbs >= m6) {
return plural2(ms, msAbs, m6, "minute");
}
if (msAbs >= s5) {
return plural2(ms, msAbs, s5, "second");
}
return ms + " ms";
}
__name(fmtLong, "fmtLong");
function plural2(ms, msAbs, n6, name2) {
var isPlural = msAbs >= n6 * 1.5;
return Math.round(ms / n6) + " " + name2 + (isPlural ? "s" : "");
}
__name(plural2, "plural");
}
});
// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/common.js
var require_common = __commonJS({
"../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/common.js"(exports2, module3) {
init_import_meta_url();
function setup(env6) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce2;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms();
createDebug.destroy = destroy;
Object.keys(env6).forEach((key) => {
createDebug[key] = env6[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i5 = 0; i5 < namespace.length; i5++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i5);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
__name(selectColor, "selectColor");
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
if (!debug.enabled) {
return;
}
const self2 = debug;
const curr = Number(/* @__PURE__ */ new Date());
const ms = curr - (prevTime || curr);
self2.diff = ms;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format9) => {
if (match2 === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format9];
if (typeof formatter === "function") {
const val2 = args[index];
match2 = formatter.call(self2, val2);
args.splice(index, 1);
index--;
}
return match2;
});
createDebug.formatArgs.call(self2, args);
const logFn = self2.log || createDebug.log;
logFn.apply(self2, args);
}
__name(debug, "debug");
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: /* @__PURE__ */ __name(() => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
}, "get"),
set: /* @__PURE__ */ __name((v7) => {
enableOverride = v7;
}, "set")
});
if (typeof createDebug.init === "function") {
createDebug.init(debug);
}
return debug;
}
__name(createDebug, "createDebug");
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
__name(extend, "extend");
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);
}
}
}
__name(enable, "enable");
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;
}
__name(matchesTemplate, "matchesTemplate");
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
__name(disable, "disable");
function enabled(name2) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name2, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name2, ns)) {
return true;
}
}
return false;
}
__name(enabled, "enabled");
function coerce2(val2) {
if (val2 instanceof Error) {
return val2.stack || val2.message;
}
return val2;
}
__name(coerce2, "coerce");
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`.");
}
__name(destroy, "destroy");
createDebug.enable(createDebug.load());
return createDebug;
}
__name(setup, "setup");
module3.exports = setup;
}
});
// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/browser.js
var require_browser = __commonJS({
"../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/browser.js"(exports2, module3) {
init_import_meta_url();
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 m6;
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 && (m6 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m6[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+)/);
}
__name(useColors, "useColors");
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module3.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c6 = "color: " + this.color;
args.splice(1, 0, c6, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match2) => {
if (match2 === "%%") {
return;
}
index++;
if (match2 === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c6);
}
__name(formatArgs, "formatArgs");
exports2.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports2.storage.setItem("debug", namespaces);
} else {
exports2.storage.removeItem("debug");
}
} catch (error2) {
}
}
__name(save, "save");
function load() {
let r7;
try {
r7 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
} catch (error2) {
}
if (!r7 && typeof process !== "undefined" && "env" in process) {
r7 = process.env.DEBUG;
}
return r7;
}
__name(load, "load");
function localstorage() {
try {
return localStorage;
} catch (error2) {
}
}
__name(localstorage, "localstorage");
module3.exports = require_common()(exports2);
var { formatters } = module3.exports;
formatters.j = function(v7) {
try {
return JSON.stringify(v7);
} catch (error2) {
return "[UnexpectedJSONParseError]: " + error2.message;
}
};
}
});
// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/node.js
var require_node4 = __commonJS({
"../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/node.js"(exports2, module3) {
init_import_meta_url();
var tty3 = require("tty");
var util3 = require("util");
exports2.init = init3;
exports2.log = log2;
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load;
exports2.useColors = useColors;
exports2.destroy = util3.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 supportsColor3 = (init_supports_color2(), __toCommonJS(supports_color_exports));
if (supportsColor3 && (supportsColor3.stderr || supportsColor3).level >= 2) {
exports2.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error2) {
}
exports2.inspectOpts = Object.keys(process.env).filter((key) => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_4, k6) => {
return k6.toUpperCase();
});
let val2 = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val2)) {
val2 = true;
} else if (/^(no|off|false|disabled)$/i.test(val2)) {
val2 = false;
} else if (val2 === "null") {
val2 = null;
} else {
val2 = Number(val2);
}
obj[prop] = val2;
return obj;
}, {});
function useColors() {
return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty3.isatty(process.stderr.fd);
}
__name(useColors, "useColors");
function formatArgs(args) {
const { namespace: name2, useColors: useColors2 } = this;
if (useColors2) {
const c6 = this.color;
const colorCode = "\x1B[3" + (c6 < 8 ? c6 : "8;5;" + c6);
const prefix = ` ${colorCode};1m${name2} \x1B[0m`;
args[0] = prefix + args[0].split("\n").join("\n" + prefix);
args.push(colorCode + "m+" + module3.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name2 + " " + args[0];
}
}
__name(formatArgs, "formatArgs");
function getDate() {
if (exports2.inspectOpts.hideDate) {
return "";
}
return (/* @__PURE__ */ new Date()).toISOString() + " ";
}
__name(getDate, "getDate");
function log2(...args) {
return process.stderr.write(util3.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
}
__name(log2, "log");
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
delete process.env.DEBUG;
}
}
__name(save, "save");
function load() {
return process.env.DEBUG;
}
__name(load, "load");
function init3(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports2.inspectOpts);
for (let i5 = 0; i5 < keys.length; i5++) {
debug.inspectOpts[keys[i5]] = exports2.inspectOpts[keys[i5]];
}
}
__name(init3, "init");
module3.exports = require_common()(exports2);
var { formatters } = module3.exports;
formatters.o = function(v7) {
this.inspectOpts.colors = this.useColors;
return util3.inspect(v7, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
};
formatters.O = function(v7) {
this.inspectOpts.colors = this.useColors;
return util3.inspect(v7, this.inspectOpts);
};
}
});
// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/index.js
var require_src3 = __commonJS({
"../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/index.js"(exports2, module3) {
init_import_meta_url();
if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
module3.exports = require_browser();
} else {
module3.exports = require_node4();
}
}
});
// ../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/helpers.js
var require_helpers = __commonJS({
"../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/helpers.js"(exports2) {
"use strict";
init_import_meta_url();
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
var desc = Object.getOwnPropertyDescriptor(m6, k6);
if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m6[k6];
}, "get") };
}
Object.defineProperty(o5, k22, desc);
} : function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
o5[k22] = m6[k6];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v7) {
Object.defineProperty(o5, "default", { enumerable: true, value: v7 });
} : function(o5, v7) {
o5["default"] = v7;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k6 in mod) if (k6 !== "default" && Object.prototype.hasOwnProperty.call(mod, k6)) __createBinding(result, mod, k6);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.req = exports2.json = exports2.toBuffer = void 0;
var http5 = __importStar(require("http"));
var https2 = __importStar(require("https"));
async function toBuffer(stream2) {
let length = 0;
const chunks = [];
for await (const chunk of stream2) {
length += chunk.length;
chunks.push(chunk);
}
return Buffer.concat(chunks, length);
}
__name(toBuffer, "toBuffer");
exports2.toBuffer = toBuffer;
async function json(stream2) {
const buf = await toBuffer(stream2);
const str = buf.toString("utf8");
try {
return JSON.parse(str);
} catch (_err) {
const err = _err;
err.message += ` (input: ${str})`;
throw err;
}
}
__name(json, "json");
exports2.json = json;
function req(url4, opts = {}) {
const href = typeof url4 === "string" ? url4 : url4.href;
const req2 = (href.startsWith("https:") ? https2 : http5).request(url4, opts);
const promise = new Promise((resolve25, reject) => {
req2.once("response", resolve25).once("error", reject).end();
});
req2.then = promise.then.bind(promise);
return req2;
}
__name(req, "req");
exports2.req = req;
}
});
// ../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/index.js
var require_dist3 = __commonJS({
"../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/index.js"(exports2) {
"use strict";
init_import_meta_url();
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
var desc = Object.getOwnPropertyDescriptor(m6, k6);
if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m6[k6];
}, "get") };
}
Object.defineProperty(o5, k22, desc);
} : function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
o5[k22] = m6[k6];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v7) {
Object.defineProperty(o5, "default", { enumerable: true, value: v7 });
} : function(o5, v7) {
o5["default"] = v7;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k6 in mod) if (k6 !== "default" && Object.prototype.hasOwnProperty.call(mod, k6)) __createBinding(result, mod, k6);
}
__setModuleDefault(result, mod);
return result;
};
var __exportStar = exports2 && exports2.__exportStar || function(m6, exports3) {
for (var p6 in m6) if (p6 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p6)) __createBinding(exports3, m6, p6);
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Agent = void 0;
var net2 = __importStar(require("net"));
var http5 = __importStar(require("http"));
var https_1 = require("https");
__exportStar(require_helpers(), exports2);
var INTERNAL = Symbol("AgentBaseInternalState");
var Agent = class extends http5.Agent {
static {
__name(this, "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((l6) => l6.indexOf("(https.js:") !== -1 || l6.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(name2) {
if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
return null;
}
if (!this.sockets[name2]) {
this.sockets[name2] = [];
}
const fakeSocket = new net2.Socket({ writable: false });
this.sockets[name2].push(fakeSocket);
this.totalSocketCount++;
return fakeSocket;
}
decrementSockets(name2, socket) {
if (!this.sockets[name2] || socket === null) {
return;
}
const sockets = this.sockets[name2];
const index = sockets.indexOf(socket);
if (index !== -1) {
sockets.splice(index, 1);
this.totalSocketCount--;
if (sockets.length === 0) {
delete this.sockets[name2];
}
}
}
// 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 = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options);
if (secureEndpoint) {
return https_1.Agent.prototype.getName.call(this, options);
}
return super.getName(options);
}
createSocket(req, options, cb2) {
const connectOpts = {
...options,
secureEndpoint: this.isSecureEndpoint(options)
};
const name2 = this.getName(connectOpts);
const fakeSocket = this.incrementSockets(name2);
Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
this.decrementSockets(name2, fakeSocket);
if (socket instanceof http5.Agent) {
try {
return socket.addRequest(req, connectOpts);
} catch (err) {
return cb2(err);
}
}
this[INTERNAL].currentSocket = socket;
super.createSocket(req, options, cb2);
}, (err) => {
this.decrementSockets(name2, fakeSocket);
cb2(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(v7) {
if (this[INTERNAL]) {
this[INTERNAL].defaultPort = v7;
}
}
get protocol() {
return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
}
set protocol(v7) {
if (this[INTERNAL]) {
this[INTERNAL].protocol = v7;
}
}
};
exports2.Agent = Agent;
}
});
// ../../node_modules/.pnpm/https-proxy-agent@7.0.2_supports-color@9.2.2/node_modules/https-proxy-agent/dist/parse-proxy-response.js
var require_parse_proxy_response = __commonJS({
"../../node_modules/.pnpm/https-proxy-agent@7.0.2_supports-color@9.2.2/node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
"use strict";
init_import_meta_url();
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_src3());
var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
function parseProxyResponse(socket) {
return new Promise((resolve25, reject) => {
let buffersLength = 0;
const buffers = [];
function read2() {
const b6 = socket.read();
if (b6)
ondata(b6);
else
socket.once("readable", read2);
}
__name(read2, "read");
function cleanup() {
socket.removeListener("end", onend);
socket.removeListener("error", onerror);
socket.removeListener("readable", read2);
}
__name(cleanup, "cleanup");
function onend() {
cleanup();
debug("onend");
reject(new Error("Proxy connection ended before receiving CONNECT response"));
}
__name(onend, "onend");
function onerror(err) {
cleanup();
debug("onerror %o", err);
reject(err);
}
__name(onerror, "onerror");
function ondata(b6) {
buffers.push(b6);
buffersLength += b6.length;
const buffered = Buffer.concat(buffers, buffersLength);
const endOfHeaders = buffered.indexOf("\r\n\r\n");
if (endOfHeaders === -1) {
debug("have not received end of HTTP headers yet...");
read2();
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;
}
}
debug("got proxy server response: %o %o", firstLine, headers);
cleanup();
resolve25({
connect: {
statusCode,
statusText,
headers
},
buffered
});
}
__name(ondata, "ondata");
socket.on("error", onerror);
socket.on("end", onend);
read2();
});
}
__name(parseProxyResponse, "parseProxyResponse");
exports2.parseProxyResponse = parseProxyResponse;
}
});
// ../../node_modules/.pnpm/https-proxy-agent@7.0.2_supports-color@9.2.2/node_modules/https-proxy-agent/dist/index.js
var require_dist4 = __commonJS({
"../../node_modules/.pnpm/https-proxy-agent@7.0.2_supports-color@9.2.2/node_modules/https-proxy-agent/dist/index.js"(exports2) {
"use strict";
init_import_meta_url();
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
var desc = Object.getOwnPropertyDescriptor(m6, k6);
if (!desc || ("get" in desc ? !m6.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m6[k6];
}, "get") };
}
Object.defineProperty(o5, k22, desc);
} : function(o5, m6, k6, k22) {
if (k22 === void 0) k22 = k6;
o5[k22] = m6[k6];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o5, v7) {
Object.defineProperty(o5, "default", { enumerable: true, value: v7 });
} : function(o5, v7) {
o5["default"] = v7;
});
var __importStar = exports2 && exports2.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k6 in mod) if (k6 !== "default" && Object.prototype.hasOwnProperty.call(mod, k6)) __createBinding(result, mod, k6);
}
__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 net2 = __importStar(require("net"));
var tls = __importStar(require("tls"));
var assert_1 = __importDefault(require("assert"));
var debug_1 = __importDefault(require_src3());
var agent_base_1 = require_dist3();
var parse_proxy_response_1 = require_parse_proxy_response();
var debug = (0, debug_1.default)("https-proxy-agent");
var HttpsProxyAgent3 = class extends agent_base_1.Agent {
static {
__name(this, "HttpsProxyAgent");
}
constructor(proxy2, opts) {
super(opts);
this.options = { path: void 0 };
this.proxy = typeof proxy2 === "string" ? new URL(proxy2) : proxy2;
this.proxyHeaders = opts?.headers ?? {};
debug("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 ? omit(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: proxy2 } = this;
if (!opts.host) {
throw new TypeError('No "host" provided');
}
let socket;
if (proxy2.protocol === "https:") {
debug("Creating `tls.Socket`: %o", this.connectOpts);
const servername = this.connectOpts.servername || this.connectOpts.host;
socket = tls.connect({
...this.connectOpts,
servername: servername && net2.isIP(servername) ? void 0 : servername
});
} else {
debug("Creating `net.Socket`: %o", this.connectOpts);
socket = net2.connect(this.connectOpts);
}
const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
const host = net2.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
`;
if (proxy2.username || proxy2.password) {
const auth = `${decodeURIComponent(proxy2.username)}:${decodeURIComponent(proxy2.password)}`;
headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
}
headers.Host = `${host}:${opts.port}`;
if (!headers["Proxy-Connection"]) {
headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
}
for (const name2 of Object.keys(headers)) {
payload += `${name2}: ${headers[name2]}\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) {
debug("Upgrading socket connection to TLS");
const servername = opts.servername || opts.host;
return tls.connect({
...omit(opts, "host", "path", "port"),
socket,
servername: net2.isIP(servername) ? void 0 : servername
});
}
return socket;
}
socket.destroy();
const fakeSocket = new net2.Socket({ writable: false });
fakeSocket.readable = true;
req.once("socket", (s5) => {
debug("Replaying proxy buffer for failed request");
(0, assert_1.default)(s5.listenerCount("data") > 0);
s5.push(buffered);
s5.push(null);
});
return fakeSocket;
}
};
HttpsProxyAgent3.protocols = ["http", "https"];
exports2.HttpsProxyAgent = HttpsProxyAgent3;
function resume(socket) {
socket.resume();
}
__name(resume, "resume");
function omit(obj, ...keys) {
const ret = {};
let key;
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key];
}
}
return ret;
}
__name(omit, "omit");
}
});
// src/utils/constants.ts
var resetColor, fgGreenColor, betaCmdColor, DEFAULT_LOCAL_PORT, DEFAULT_INSPECTOR_PORT, proxy;
var init_constants5 = __esm({
"src/utils/constants.ts"() {
init_import_meta_url();
resetColor = "\x1B[0m";
fgGreenColor = "\x1B[32m";
betaCmdColor = "#BD5B08";
DEFAULT_LOCAL_PORT = 8787;
DEFAULT_INSPECTOR_PORT = 9229;
proxy = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY || void 0;
}
});
// src/tail/filters.ts
function translateCLICommandToFilterMessage(cliFilters) {
const apiFilters = [];
if (cliFilters.samplingRate) {
apiFilters.push(parseSamplingRate(cliFilters.samplingRate));
}
if (cliFilters.status) {
apiFilters.push(parseOutcome(cliFilters.status));
}
if (cliFilters.method) {
apiFilters.push(parseMethod(cliFilters.method));
}
if (cliFilters.header) {
apiFilters.push(parseHeader(cliFilters.header));
}
if (cliFilters.clientIp) {
apiFilters.push(parseIP(cliFilters.clientIp));
}
if (cliFilters.search) {
apiFilters.push(parseQuery(cliFilters.search));
}
if (cliFilters.versionId) {
apiFilters.push(parseScriptVersion(cliFilters.versionId));
}
return {
filters: apiFilters
};
}
function parseSamplingRate(sampling_rate) {
if (sampling_rate <= 0 || sampling_rate >= 1) {
throw new UserError(
"A sampling rate must be between 0 and 1 in order to have any effect.\nFor example, a sampling rate of 0.25 means 25% of events will be logged."
);
}
return { sampling_rate };
}
function parseOutcome(statuses) {
const outcomes = /* @__PURE__ */ new Set();
for (const status2 of statuses) {
switch (status2) {
case "ok":
outcomes.add("ok");
break;
case "canceled":
outcomes.add("canceled");
break;
case "error":
outcomes.add("exception");
outcomes.add("exceededCpu");
outcomes.add("exceededMemory");
outcomes.add("unknown");
break;
default:
break;
}
}
return {
outcome: Array.from(outcomes)
};
}
function parseMethod(method) {
return { method };
}
function parseHeader(header) {
const [headerKey, headerQuery] = header.split(":", 2);
return {
header: {
key: headerKey.trim(),
query: headerQuery?.trim()
}
};
}
function parseIP(client_ip) {
return { client_ip };
}
function parseQuery(query) {
return { query };
}
function parseScriptVersion(scriptVersion) {
return { scriptVersion };
}
var init_filters = __esm({
"src/tail/filters.ts"() {
init_import_meta_url();
init_errors();
__name(translateCLICommandToFilterMessage, "translateCLICommandToFilterMessage");
__name(parseSamplingRate, "parseSamplingRate");
__name(parseOutcome, "parseOutcome");
__name(parseMethod, "parseMethod");
__name(parseHeader, "parseHeader");
__name(parseIP, "parseIP");
__name(parseQuery, "parseQuery");
__name(parseScriptVersion, "parseScriptVersion");
}
});
// src/tail/printing.ts
function prettyPrintLogs(data) {
const eventMessage2 = JSON.parse(data.toString());
if (isScheduledEvent(eventMessage2.event)) {
const cronPattern = eventMessage2.event.cron;
const datetime = new Date(
eventMessage2.event.scheduledTime
).toLocaleString();
const outcome = prettifyOutcome(eventMessage2.outcome);
logger.log(`"${cronPattern}" @ ${datetime} - ${outcome}`);
} else if (isRequestEvent(eventMessage2.event)) {
const requestMethod = eventMessage2.event?.request.method.toUpperCase();
const url4 = eventMessage2.event?.request.url;
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(eventMessage2.eventTimestamp).toLocaleString();
logger.log(
url4 ? `${requestMethod} ${url4} - ${outcome} @ ${datetime}` : `[missing request] - ${outcome} @ ${datetime}`
);
} else if (isEmailEvent(eventMessage2.event)) {
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(eventMessage2.eventTimestamp).toLocaleString();
const mailFrom = eventMessage2.event.mailFrom;
const rcptTo = eventMessage2.event.rcptTo;
const rawSize = eventMessage2.event.rawSize;
logger.log(
`Email from:${mailFrom} to:${rcptTo} size:${rawSize} @ ${datetime} - ${outcome}`
);
} else if (isAlarmEvent(eventMessage2.event)) {
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(
eventMessage2.event.scheduledTime
).toLocaleString();
logger.log(`Alarm @ ${datetime} - ${outcome}`);
} else if (isTailEvent(eventMessage2.event)) {
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(eventMessage2.eventTimestamp).toLocaleString();
const tailedScripts = new Set(
eventMessage2.event.consumedEvents.map((consumedEvent) => consumedEvent.scriptName).filter((scriptName) => !!scriptName)
);
logger.log(
`Tailing ${Array.from(tailedScripts).join(
","
)} - ${outcome} @ ${datetime}`
);
} else if (isTailInfo(eventMessage2.event)) {
if (eventMessage2.event.type === "overload") {
logger.log(`${source_default.red.bold(eventMessage2.event.message)}`);
} else if (eventMessage2.event.type === "overload-stop") {
logger.log(`${source_default.yellow.bold(eventMessage2.event.message)}`);
}
} else if (isQueueEvent(eventMessage2.event)) {
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(eventMessage2.eventTimestamp).toLocaleString();
const queueName = eventMessage2.event.queue;
const batchSize = eventMessage2.event.batchSize;
const batchSizeMsg = `${batchSize} message${batchSize !== 1 ? "s" : ""}`;
logger.log(
`Queue ${queueName} (${batchSizeMsg}) - ${outcome} @ ${datetime}`
);
} else if (isRpcEvent(eventMessage2.event)) {
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(eventMessage2.eventTimestamp).toLocaleString();
logger.log(
`${eventMessage2.entrypoint}.${eventMessage2.event.rpcMethod} - ${outcome} @ ${datetime}`
);
} else {
const outcome = prettifyOutcome(eventMessage2.outcome);
const datetime = new Date(eventMessage2.eventTimestamp).toLocaleString();
logger.log(`Unknown Event - ${outcome} @ ${datetime}`);
}
if (eventMessage2.logs.length > 0) {
eventMessage2.logs.forEach(({ level, message }) => {
logger.log(` (${level})`, ...message);
});
}
if (eventMessage2.exceptions.length > 0) {
eventMessage2.exceptions.forEach(({ name: name2, message }) => {
logger.error(` ${name2}:`, message);
});
}
}
function jsonPrintLogs(data) {
logger.json(JSON.parse(data.toString()));
}
function isRequestEvent(event) {
return Boolean(event && "request" in event);
}
function isScheduledEvent(event) {
return Boolean(event && "cron" in event);
}
function isEmailEvent(event) {
return Boolean(event && "mailFrom" in event);
}
function isQueueEvent(event) {
return Boolean(event && "queue" in event);
}
function isRpcEvent(event) {
return Boolean(event && "rpcMethod" in event);
}
function isAlarmEvent(event) {
return Boolean(event && "scheduledTime" in event && !("cron" in event));
}
function isTailEvent(event) {
return Boolean(event && "consumedEvents" in event);
}
function isTailInfo(event) {
return Boolean(event && "message" in event && "type" in event);
}
function prettifyOutcome(outcome) {
switch (outcome) {
case "ok":
return "Ok";
case "canceled":
return "Canceled";
case "exceededCpu":
return "Exceeded CPU Limit";
case "exceededMemory":
return "Exceeded Memory Limit";
case "exception":
return "Exception Thrown";
case "unknown":
default:
return "Unknown";
}
}
var init_printing = __esm({
"src/tail/printing.ts"() {
init_import_meta_url();
init_source();
init_logger();
__name(prettyPrintLogs, "prettyPrintLogs");
__name(jsonPrintLogs, "jsonPrintLogs");
__name(isRequestEvent, "isRequestEvent");
__name(isScheduledEvent, "isScheduledEvent");
__name(isEmailEvent, "isEmailEvent");
__name(isQueueEvent, "isQueueEvent");
__name(isRpcEvent, "isRpcEvent");
__name(isAlarmEvent, "isAlarmEvent");
__name(isTailEvent, "isTailEvent");
__name(isTailInfo, "isTailInfo");
__name(prettifyOutcome, "prettifyOutcome");
}
});
// src/tail/createTail.ts
function makeCreateTailUrl(accountId, workerName, env6) {
return env6 ? `/accounts/${accountId}/workers/services/${workerName}/environments/${env6}/tails` : `/accounts/${accountId}/workers/scripts/${workerName}/tails`;
}
function makeDeleteTailUrl(accountId, workerName, tailId, env6) {
return env6 ? `/accounts/${accountId}/workers/services/${workerName}/environments/${env6}/tails/${tailId}` : `/accounts/${accountId}/workers/scripts/${workerName}/tails/${tailId}`;
}
async function createPagesTail({
accountId,
projectName,
deploymentId,
filters,
debug = false
}) {
const tailRecord = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments/${deploymentId}/tails`,
{
method: "POST",
body: JSON.stringify(filters)
}
);
const deleteTail = /* @__PURE__ */ __name(async () => fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments/${deploymentId}/tails/${tailRecord.id}`,
{ method: "DELETE" }
), "deleteTail");
const p6 = proxy ? { agent: new import_https_proxy_agent.HttpsProxyAgent(proxy) } : {};
const tail = new wrapper_default(tailRecord.url, TRACE_VERSION, {
headers: {
"Sec-WebSocket-Protocol": TRACE_VERSION,
// needs to be `trace-v1` to be accepted
"User-Agent": `wrangler-js/${version}`
},
...p6
});
tail.on("open", () => {
tail.send(
JSON.stringify({ debug }),
{ binary: false, compress: false, mask: false, fin: true },
(err) => {
if (err) {
throw err;
}
}
);
});
return { tail, deleteTail, expiration: tailRecord.expires_at };
}
async function createTail(complianceConfig, accountId, workerName, filters, debug, env6) {
const createTailUrl = makeCreateTailUrl(accountId, workerName, env6);
const {
id: tailId,
url: websocketUrl,
expires_at: expiration
} = await fetchResult(
complianceConfig,
createTailUrl,
{
method: "POST",
body: JSON.stringify(filters)
}
);
const deleteUrl = makeDeleteTailUrl(accountId, workerName, tailId, env6);
async function deleteTail() {
await fetchResult(complianceConfig, deleteUrl, { method: "DELETE" });
}
__name(deleteTail, "deleteTail");
const p6 = proxy ? { agent: new import_https_proxy_agent.HttpsProxyAgent(proxy) } : {};
const tail = new wrapper_default(websocketUrl, TRACE_VERSION, {
headers: {
"Sec-WebSocket-Protocol": TRACE_VERSION,
// needs to be `trace-v1` to be accepted
"User-Agent": `wrangler-js/${version}`
},
...p6
});
tail.on("open", function() {
tail.send(
JSON.stringify({ debug }),
{ binary: false, compress: false, mask: false, fin: true },
(err) => {
if (err) {
throw err;
}
}
);
});
return { tail, expiration, deleteTail };
}
var import_https_proxy_agent, TRACE_VERSION;
var init_createTail = __esm({
"src/tail/createTail.ts"() {
init_import_meta_url();
import_https_proxy_agent = __toESM(require_dist4());
init_wrapper();
init_package();
init_cfetch();
init_misc_variables();
init_constants5();
init_filters();
init_printing();
TRACE_VERSION = "trace-v1";
__name(makeCreateTailUrl, "makeCreateTailUrl");
__name(makeDeleteTailUrl, "makeDeleteTailUrl");
__name(createPagesTail, "createPagesTail");
__name(createTail, "createTail");
}
});
// src/pages/deployment-tails.ts
var import_promises23, import_signal_exit5, statusChoices, isStatusChoiceList, pagesDeploymentTailCommand;
var init_deployment_tails = __esm({
"src/pages/deployment-tails.ts"() {
init_import_meta_url();
import_promises23 = require("timers/promises");
import_signal_exit5 = __toESM(require_signal_exit());
init_cfetch();
init_config2();
init_config_cache();
init_create_command();
init_misc_variables();
init_errors();
init_is_interactive();
init_logger();
init_metrics();
init_createTail();
init_filters();
init_user2();
init_constants();
init_prompt_select_project();
init_utils6();
statusChoices = ["ok", "error", "canceled"];
isStatusChoiceList = /* @__PURE__ */ __name((data) => data?.every((d6) => statusChoices.includes(d6)) ?? false, "isStatusChoiceList");
pagesDeploymentTailCommand = createCommand({
metadata: {
description: "Start a tailing session for a project's deployment and livestream logs from your Functions",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false,
printBanner: /* @__PURE__ */ __name((args) => args.format === "pretty" || args.format === void 0 && !isNonInteractiveOrCI(), "printBanner")
},
args: {
deployment: {
type: "string",
description: "(Optional) ID or URL of the deployment to tail. Specify by environment if deployment ID is unknown."
},
"project-name": {
type: "string",
description: "The name of the project you would like to tail"
},
environment: {
type: "string",
choices: ["production", "preview"],
default: "production",
description: "When not providing a specific deployment ID, specifying environment will grab the latest production or preview deployment"
},
format: {
type: "string",
choices: ["json", "pretty"],
description: "The format of log entries"
},
debug: {
type: "boolean",
hidden: true,
default: false,
description: "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it."
},
status: {
choices: statusChoices,
description: "Filter by invocation status",
array: true
},
header: {
type: "string",
requiresArg: true,
description: "Filter by HTTP header"
},
method: {
type: "string",
requiresArg: true,
description: "Filter by HTTP method",
array: true
},
search: {
type: "string",
requiresArg: true,
description: "Filter by a text match in console.log messages"
},
"sampling-rate": {
type: "number",
description: "Adds a percentage of requests to log sampling rate"
},
ip: {
type: "string",
requiresArg: true,
description: 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
array: true
}
},
positionalArgs: ["deployment"],
async handler({
deployment,
projectName,
environment,
header,
ip: clientIp,
method,
samplingRate,
search,
status: status2,
format: format9,
debug,
...args
}) {
if (format9 === void 0) {
format9 = isNonInteractiveOrCI() ? "json" : "pretty";
}
if (status2 && !isStatusChoiceList(status2)) {
throw new FatalError(
"Invalid value for `--status`. Valid options: " + statusChoices.join(", ")
);
}
const config = readConfig(args);
const pagesConfig = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = await requireAuth(pagesConfig);
let deploymentId = deployment;
if (!isInteractive2()) {
if (!deploymentId) {
throw new FatalError(
"Must specify a deployment in non-interactive mode.",
1
);
}
if (!projectName) {
throw new FatalError(
"Must specify a project name in non-interactive mode.",
1
);
}
}
if (!projectName && isInteractive2()) {
projectName = await promptSelectProject({ accountId });
}
if (!deployment && !projectName) {
throw new FatalError("Must specify a project name or deployment.", 1);
}
const deployments = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments`,
{},
new URLSearchParams({ env: environment })
);
const envDeployments = deployments.filter(
(d6) => d6.environment === environment && d6.latest_stage.name === "deploy" && d6.latest_stage.status === "success"
);
if (isUrl(deployment)) {
const { hostname: deploymentHostname } = new URL(deployment);
const targetDeployment = envDeployments.find(
(d6) => new URL(d6.url).hostname === deploymentHostname
);
if (!targetDeployment) {
throw new FatalError(
"Could not find deployment match url: " + deployment,
1
);
}
deploymentId = targetDeployment.id;
} else if (!deployment) {
if (envDeployments.length === 0) {
throw new FatalError(
"No deployments for environment: " + environment,
1
);
}
if (format9 === "pretty") {
logger.log(
"No deployment specified. Using latest deployment for",
environment,
"environment."
);
}
const latestDeployment = envDeployments.map((d6) => ({ id: d6.id, created_on: new Date(d6.created_on) })).sort((a5, b6) => +b6.created_on - +a5.created_on)[0];
deploymentId = latestDeployment.id;
}
if (!deploymentId || !projectName) {
throw new Error("An unknown error occurred.");
}
const filters = translateCLICommandToFilterMessage({
header,
clientIp,
method,
samplingRate,
search,
status: status2
});
sendMetricsEvent("begin pages log stream", {
sendMetrics: config.send_metrics
});
const { tail, deleteTail } = await createPagesTail({
accountId,
projectName,
deploymentId,
filters,
debug
});
const onCloseTail = /* @__PURE__ */ (() => {
let didTerminate = false;
return async () => {
if (didTerminate) {
return;
}
tail.terminate();
await deleteTail();
sendMetricsEvent("end pages log stream", {
sendMetrics: config.send_metrics
});
didTerminate = true;
};
})();
(0, import_signal_exit5.default)(onCloseTail);
tail.on("message", (data) => {
if (format9 === "pretty") {
prettyPrintLogs(data);
} else {
jsonPrintLogs(data);
}
});
tail.on("close", onCloseTail);
while (tail.readyState !== tail.OPEN) {
switch (tail.readyState) {
case tail.CONNECTING:
await (0, import_promises23.setTimeout)(100);
break;
case tail.CLOSING:
await (0, import_promises23.setTimeout)(100);
break;
case tail.CLOSED:
sendMetricsEvent("end log stream", {
sendMetrics: config.send_metrics
});
throw new Error(
`Connection to deployment ${deploymentId} closed unexpectedly.`
);
}
}
if (format9 === "pretty") {
logger.log(
`Connected to deployment ${deploymentId}, waiting for logs...`
);
}
}
});
}
});
// src/pages/deployments.ts
var pagesDeploymentListCommand;
var init_deployments2 = __esm({
"src/pages/deployments.ts"() {
init_import_meta_url();
init_esm5();
init_cfetch();
init_config_cache();
init_create_command();
init_misc_variables();
init_errors();
init_logger();
init_metrics();
init_user2();
init_constants();
init_prompt_select_project();
pagesDeploymentListCommand = createCommand({
metadata: {
description: "List deployments in your Cloudflare Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
"project-name": {
type: "string",
description: "The name of the project you would like to list deployments for"
},
environment: {
type: "string",
choices: ["production", "preview"],
description: "Environment type to list deployments for"
},
json: {
type: "boolean",
description: "Return output as clean JSON",
default: false
}
},
async handler({ projectName, environment, json }) {
const config = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = await requireAuth(config);
projectName ??= config.project_name;
const isInteractive3 = process.stdin.isTTY;
if (!projectName && isInteractive3) {
projectName = await promptSelectProject({ accountId });
}
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
const deployments = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}/deployments`,
{},
environment ? new URLSearchParams({ env: environment }) : new URLSearchParams({})
);
const titleCase = /* @__PURE__ */ __name((word) => word.charAt(0).toUpperCase() + word.slice(1), "titleCase");
const shortSha = /* @__PURE__ */ __name((sha) => sha.slice(0, 7), "shortSha");
const getStatus = /* @__PURE__ */ __name((deployment) => {
if (deployment.latest_stage.status === "success" && deployment.latest_stage.ended_on) {
return format7(deployment.latest_stage.ended_on);
}
return titleCase(deployment.latest_stage.status);
}, "getStatus");
const data = deployments.map((deployment) => {
return {
Id: deployment.id,
Environment: titleCase(deployment.environment),
Branch: deployment.deployment_trigger.metadata.branch,
Source: shortSha(deployment.deployment_trigger.metadata.commit_hash),
Deployment: deployment.url,
Status: getStatus(deployment),
// TODO: Use a url shortener
Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`
};
});
saveToConfigCache(PAGES_CONFIG_CACHE_FILENAME, {
account_id: accountId
});
if (json) {
logger.log(JSON.stringify(data, null, 2));
} else {
logger.table(data);
}
sendMetricsEvent("list pages deployments");
}
});
}
});
// src/deployment-bundle/esbuild-plugins/alias-external.ts
function esbuildAliasExternalPlugin(aliases2) {
return {
name: "external-alias-imports",
setup(build5) {
build5.onResolve({ filter: /.*/ }, (args) => {
if (args.kind === "entry-point") {
return {
path: args.path
};
}
if (!Object.keys(aliases2).includes(args.path)) {
throw new Error("unrecognized module: " + args.path);
}
return {
path: aliases2[args.path],
external: true
};
});
}
};
}
var init_alias_external = __esm({
"src/deployment-bundle/esbuild-plugins/alias-external.ts"() {
init_import_meta_url();
__name(esbuildAliasExternalPlugin, "esbuildAliasExternalPlugin");
}
});
// src/pages/dev.ts
function isWindows3() {
return process.platform === "win32";
}
async function sleep(ms) {
await new Promise((promiseResolve) => setTimeout(promiseResolve, ms));
}
function getPids(pid) {
const pids = [pid];
let command2, regExp;
if (isWindows3()) {
command2 = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
regExp = new RegExp(/(\d+)/);
} else {
command2 = `pgrep -P ${pid}`;
regExp = new RegExp(/(\d+)/);
}
try {
const newPids = (0, import_node_child_process6.execSync)(command2).toString().split("\n").map((line) => line.match(regExp)).filter((line) => line !== null).map((match2) => parseInt(match2[1]));
pids.push(...newPids.map(getPids).flat());
} catch {
}
return pids;
}
function getPort(pid) {
let command2, regExp;
if (isWindows3()) {
command2 = process.env.SYSTEMROOT + "\\system32\\netstat.exe -nao";
regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
} else {
command2 = "lsof -nPi";
regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
}
try {
const matches = (0, import_node_child_process6.execSync)(command2).toString().split("\n").map((line) => line.match(regExp)).filter((line) => line !== null);
const match2 = matches[0];
if (match2) {
return parseInt(match2[1]);
}
} catch (thrown) {
logger.error(
`Error scanning for ports of process with PID ${pid}: ${thrown}`
);
}
}
async function spawnProxyProcess({
port,
command: command2
}) {
if (command2.length > 0 || port !== void 0) {
logger.warn(
`Specifying a \`-- <command>\` or \`--proxy\` is deprecated and will be removed in a future version of Wrangler.
Build your application to a directory and run the \`wrangler pages dev <directory>\` instead.
This results in a more faithful emulation of production behavior.`
);
}
if (port !== void 0) {
logger.warn(
"On Node.js 17+, wrangler will default to fetching only the IPv6 address. Please ensure that the process listening on the port specified via `--proxy` is configured for IPv6."
);
}
if (command2.length === 0) {
if (port !== void 0) {
return port;
}
CLEANUP();
throw new FatalError(
`Must specify a directory of static assets to serve, or a command to run, or a proxy port, or configure \`pages_build_output_dir\` in your Wrangler configuration file.`,
1
);
}
logger.log(`Running ${quote(command2)}...`);
const proxy2 = (0, import_node_child_process6.spawn)(
command2[0].toString(),
command2.slice(1).map((value) => value.toString()),
{
shell: isWindows3(),
env: {
BROWSER: "none",
...process.env
}
}
);
CLEANUP_CALLBACKS.push(() => {
proxy2.kill();
});
proxy2.stdout.on("data", (data) => {
logger.log(`[proxy]: ${data}`);
});
proxy2.stderr.on("data", (data) => {
logger.error(`[proxy]: ${data}`);
});
proxy2.on("close", (code) => {
logger.error(`Proxy exited with status ${code}.`);
CLEANUP();
process.exitCode = code ?? 0;
});
while (!proxy2.pid) {
}
if (port === void 0) {
logger.log(
`Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
);
logger.log("To skip, specify the proxy port with --proxy.");
await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1e3);
port = getPids(proxy2.pid).map(getPort).filter((nr) => nr !== void 0)[0];
if (port === void 0) {
CLEANUP();
throw new FatalError(
"Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
1
);
} else {
logger.log(`Automatically determined the proxy port to be ${port}.`);
}
}
return port;
}
function resolvePagesDevServerSettings(config, args) {
let compatibilityDate = args.compatibilityDate || config.compatibility_date;
if (!compatibilityDate) {
const currentDate = formatCompatibilityDate(/* @__PURE__ */ new Date());
logger.warn(
`No compatibility_date was specified. Using today's date: ${currentDate}.
\u276F\u276F Add one to your ${configFileName(config.configPath)} file: compatibility_date = "${currentDate}", or
\u276F\u276F Pass it in your terminal: wrangler pages dev [<DIRECTORY>] --compatibility-date=${currentDate}
See https://developers.cloudflare.com/workers/platform/compatibility-dates/ for more information.`
);
compatibilityDate = currentDate;
}
return {
compatibilityDate,
compatibilityFlags: args.compatibilityFlags ?? config.compatibility_flags,
ip: args.ip ?? config.dev.ip ?? DEFAULT_IP,
// because otherwise `unstable_dev` will default the port number to `0`
port: args.port ?? config.dev?.port ?? DEFAULT_PAGES_LOCAL_PORT,
inspectorPort: args.inspectorPort ?? config.dev?.inspector_port,
localProtocol: args.localProtocol ?? config.dev?.local_protocol
};
}
function getBindingsFromArgs(args) {
let vars = {};
if (args.binding?.length) {
vars = Object.fromEntries(
args.binding.map((binding) => binding.toString().split("=")).map(([key, ...values]) => [key, values.join("=")])
);
}
let kvNamespaces;
if (args.kv?.length) {
kvNamespaces = args.kv.map((kv) => {
const { binding, ref } = BINDING_REGEXP.exec(kv.toString())?.groups || {};
if (!binding) {
logger.warn("Could not parse KV binding:", kv.toString());
return;
}
return {
binding,
id: ref || kv.toString()
};
}).filter(Boolean);
}
let durableObjectsBindings;
if (args.do?.length) {
durableObjectsBindings = args.do.map((durableObject) => {
const { binding, className, scriptName } = DURABLE_OBJECTS_BINDING_REGEXP.exec(durableObject.toString())?.groups || {};
if (!binding || !className) {
logger.warn(
"Could not parse Durable Object binding:",
durableObject.toString()
);
return;
}
return {
name: binding,
class_name: className,
script_name: scriptName
};
}).filter(Boolean);
}
let d1Databases;
if (args.d1?.length) {
d1Databases = args.d1.map((d1) => {
const { binding, ref } = BINDING_REGEXP.exec(d1.toString())?.groups || {};
if (!binding) {
logger.warn("Could not parse D1 binding:", d1.toString());
return;
}
return {
binding,
database_id: ref || d1.toString(),
database_name: `local-${d1}`
};
}).filter(Boolean);
}
let r2Buckets;
if (args.r2?.length) {
r2Buckets = args.r2.map((r22) => {
const { binding, ref } = BINDING_REGEXP.exec(r22.toString())?.groups || {};
if (!binding) {
logger.warn("Could not parse R2 binding:", r22.toString());
return;
}
return { binding, bucket_name: ref || binding.toString() };
}).filter(Boolean);
}
let services;
if (args.service?.length) {
services = args.service.map((serviceBinding) => {
const { binding, service, environment, entrypoint } = SERVICE_BINDING_REGEXP.exec(serviceBinding.toString())?.groups || {};
if (!binding || !service) {
logger.warn(
"Could not parse Service binding:",
serviceBinding.toString()
);
return;
}
let serviceName = service;
if (environment) {
serviceName = `${service}-${environment}`;
}
return {
binding,
service: serviceName,
environment,
entrypoint
};
}).filter(Boolean);
if (services.find(({ environment }) => !!environment)) {
logger.warn("Support for service binding environments is experimental.");
}
}
let ai2;
if (args.ai) {
ai2 = { binding: args.ai.toString() };
}
let version_metadata;
if (args.versionMetadata) {
version_metadata = { binding: args.versionMetadata.toString() };
}
return {
vars,
kv_namespaces: kvNamespaces,
d1_databases: d1Databases,
r2_buckets: r2Buckets,
services,
ai: ai2,
version_metadata,
// don't construct the full `EnvironmentNonInheritable["durable_objects"]` shape here.
// `startDev()` will do that for us in its `getBindings()` function
do_bindings: durableObjectsBindings
};
}
var import_node_child_process6, import_node_events2, import_node_fs27, import_node_path49, esbuild3, DURABLE_OBJECTS_BINDING_REGEXP, BINDING_REGEXP, SERVICE_BINDING_REGEXP, DEFAULT_IP, DEFAULT_PAGES_LOCAL_PORT, DEFAULT_SCRIPT_PATH, pagesDevCommand;
var init_dev = __esm({
"src/pages/dev.ts"() {
init_import_meta_url();
import_node_child_process6 = require("child_process");
import_node_events2 = __toESM(require("events"));
import_node_fs27 = require("fs");
import_node_path49 = __toESM(require("path"));
init_esm4();
esbuild3 = __toESM(require("esbuild"));
init_config2();
init_create_command();
init_build_failures();
init_bundle();
init_alias_external();
init_node_compat();
init_dev2();
init_errors();
init_experimental_flags();
init_logger();
init_metrics();
init_navigator_user_agent();
init_paths();
init_compatibility_date();
init_debounce();
init_shell_quote();
init_buildFunctions();
init_constants();
init_errors3();
init_buildWorker();
init_routes_validation();
init_utils6();
DURABLE_OBJECTS_BINDING_REGEXP = new RegExp(
/^(?<binding>[^=]+)=(?<className>[^@\s]+)(@(?<scriptName>.*)$)?$/
);
BINDING_REGEXP = new RegExp(/^(?<binding>[^=]+)(?:=(?<ref>[^\s]+))?$/);
SERVICE_BINDING_REGEXP = new RegExp(
/^(?<binding>[^=]+)=(?<service>[^@#\s]+)(@(?<environment>.*)$)?(#(?<entrypoint>.*))?$/
);
DEFAULT_IP = process.platform === "win32" ? "127.0.0.1" : "localhost";
DEFAULT_PAGES_LOCAL_PORT = 8788;
DEFAULT_SCRIPT_PATH = "_worker.js";
pagesDevCommand = createCommand({
metadata: {
description: "Develop your full-stack Pages application locally",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
directory: {
type: "string",
description: "The directory of static assets to serve"
},
command: {
type: "string",
description: "The proxy command to run [deprecated]"
},
local: {
type: "boolean",
default: true,
description: "Run on my machine",
deprecated: true,
hidden: true
},
"compatibility-date": {
description: "Date to use for compatibility checks",
type: "string"
},
"compatibility-flags": {
description: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
array: true
},
ip: {
type: "string",
// On Windows, when specifying `localhost` as the socket hostname,
// `workerd` will only listen on the IPv4 loopback `127.0.0.1`, not the
// IPv6 `::1`: https://github.com/cloudflare/workerd/issues/1408
// On Node 17+, `fetch()` will only try to fetch the IPv6 address.
// For now, on Windows, we default to listening on IPv4 only and using
// `127.0.0.1` when sending control requests to `workerd` (e.g. with the
// `ProxyController`).
description: "The IP address to listen on"
},
port: {
type: "number",
description: "The port to listen on (serve from)"
},
"inspector-port": {
type: "number",
description: "Port for devtools to connect to"
},
proxy: {
type: "number",
description: "The port to proxy (where the static assets are served)",
deprecated: true
},
"script-path": {
type: "string",
description: "The location of the single Worker script if not using functions [default: _worker.js]",
// hacking in a fake default message here so we can detect when user is setting this and show a deprecation message
deprecated: true
},
bundle: {
type: "boolean",
default: void 0,
hidden: true
},
"no-bundle": {
type: "boolean",
default: void 0,
conflicts: "bundle",
description: "Whether to run bundling on `_worker.js`"
},
binding: {
type: "array",
description: "Bind variable/secret (KEY=VALUE)",
alias: "b"
},
kv: {
type: "array",
description: "KV namespace to bind (--kv KV_BINDING)",
alias: "k"
},
d1: {
type: "array",
description: "D1 database to bind (--d1 D1_BINDING)"
},
do: {
type: "array",
description: "Durable Object to bind (--do DO_BINDING=CLASS_NAME@SCRIPT_NAME)",
alias: "o"
},
r2: {
type: "array",
description: "R2 bucket to bind (--r2 R2_BINDING)"
},
ai: {
type: "string",
description: "AI to bind (--ai AI_BINDING)"
},
"version-metadata": {
type: "string",
description: "Worker Version metadata (--version-metadata VERSION_METADATA_BINDING)"
},
service: {
type: "array",
description: "Service to bind (--service SERVICE=SCRIPT_NAME)",
alia: "s"
},
"live-reload": {
type: "boolean",
default: false,
description: "Auto reload HTML pages when change is detected"
},
"local-protocol": {
description: "Protocol to listen to requests on, defaults to http.",
choices: ["http", "https"]
},
"https-key-path": {
description: "Path to a custom certificate key",
type: "string",
requiresArg: true
},
"https-cert-path": {
description: "Path to a custom certificate",
type: "string",
requiresArg: true
},
"persist-to": {
description: "Specify directory to use for local persistence (defaults to .wrangler/state)",
type: "string",
requiresArg: true
},
"node-compat": {
description: "Enable Node.js compatibility",
default: false,
type: "boolean",
hidden: true,
deprecated: true
},
"experimental-local": {
description: "Run on my machine using the Cloudflare Workers runtime",
type: "boolean",
deprecated: true,
hidden: true
},
"log-level": {
choices: ["debug", "info", "log", "warn", "error", "none"],
description: "Specify logging level"
},
"show-interactive-dev-session": {
description: "Show interactive dev session (defaults to true if the terminal supports interactivity)",
type: "boolean"
},
"experimental-vectorize-bind-to-prod": {
type: "boolean",
description: "Bind to production Vectorize indexes in local development mode",
default: false
},
"experimental-images-local-mode": {
type: "boolean",
description: "Use a local lower-fidelity implementation of the Images binding",
default: false
}
},
positionalArgs: ["directory", "command"],
async handler(args) {
if (args.logLevel) {
logger.loggerLevel = args.logLevel;
}
if (args.nodeCompat) {
throw new UserError(
`The --node-compat flag is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`
);
}
if (args.experimentalLocal) {
logger.warn(
"--experimental-local is no longer required and will be removed in a future version.\n`wrangler pages dev` now uses the local Cloudflare Workers runtime by default."
);
}
if (args.config && !Array.isArray(args.config)) {
throw new FatalError(
"Pages does not support custom paths for the Wrangler configuration file",
1
);
}
if (args.env) {
throw new FatalError(
"Pages does not support targeting an environment with the --env flag during local development.",
1
);
}
if (args.scriptPath !== void 0) {
logger.warn(
`\`--script-path\` is deprecated and will be removed in a future version of Wrangler.
The Worker script should be named \`_worker.js\` and located in the build output directory of your project (specified with \`wrangler pages dev <directory>\`).`
);
}
const config = readConfig(
{ ...args, env: void 0, config: void 0 },
{ useRedirectIfAvailable: true }
);
if (args.config && Array.isArray(args.config) && config.configPath && import_node_path49.default.resolve(process.cwd(), args.config[0]) !== config.configPath) {
throw new FatalError(
"The first `--config` argument must point to your Pages configuration file: " + import_node_path49.default.relative(process.cwd(), config.configPath)
);
}
const resolvedDirectory = args.directory ?? config.pages_build_output_dir;
const [_pages, _dev, ...remaining] = args._;
const command2 = remaining;
let proxyPort;
let directory = resolvedDirectory;
if (directory !== void 0 && command2.length > 0) {
throw new FatalError(
"Specify either a directory OR a proxy command, not both.",
1
);
} else if (directory === void 0) {
proxyPort = await spawnProxyProcess({
port: args.proxy,
command: command2
});
if (proxyPort === void 0) {
return void 0;
}
} else {
directory = (0, import_node_path49.resolve)(directory);
}
const {
compatibilityDate,
compatibilityFlags,
ip,
port,
inspectorPort,
localProtocol
} = resolvePagesDevServerSettings(config, args);
const {
vars,
kv_namespaces,
do_bindings,
d1_databases,
r2_buckets,
services,
ai: ai2
} = getBindingsFromArgs(args);
let scriptReadyResolve;
const scriptReadyPromise = new Promise(
(promiseResolve) => scriptReadyResolve = promiseResolve
);
const singleWorkerScriptPath = args.scriptPath ?? DEFAULT_SCRIPT_PATH;
const workerScriptPath = directory !== void 0 ? (0, import_node_path49.join)(directory, singleWorkerScriptPath) : (0, import_node_path49.resolve)(singleWorkerScriptPath);
const usingWorkerDirectory = (0, import_node_fs27.existsSync)(workerScriptPath) && (0, import_node_fs27.lstatSync)(workerScriptPath).isDirectory();
const usingWorkerScript = (0, import_node_fs27.existsSync)(workerScriptPath);
const enableBundling = args.bundle ?? !(args.noBundle ?? config.no_bundle);
const functionsDirectory = "./functions";
let usingFunctions = !usingWorkerScript && (0, import_node_fs27.existsSync)(functionsDirectory);
let scriptPath4 = "";
const nodejsCompatMode = validateNodeCompatMode(
args.compatibilityDate ?? config.compatibility_date,
args.compatibilityFlags ?? config.compatibility_flags ?? [],
{
noBundle: !enableBundling
}
);
const defineNavigatorUserAgent = isNavigatorDefined(
compatibilityDate,
compatibilityFlags
);
const checkFetch = shouldCheckFetch(compatibilityDate, compatibilityFlags);
let modules = [];
if (usingWorkerDirectory) {
const runBuild2 = /* @__PURE__ */ __name(async () => {
const bundleResult = await produceWorkerBundleForWorkerJSDirectory({
workerJSDirectory: workerScriptPath,
bundle: enableBundling,
buildOutputDirectory: directory ?? ".",
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
sourceMaps: config?.upload_source_maps ?? false
});
modules = bundleResult.modules;
scriptPath4 = bundleResult.resolvedEntryPointPath;
}, "runBuild");
await runBuild2().then(() => scriptReadyResolve());
watch([workerScriptPath], {
persistent: true,
ignoreInitial: true
}).on("all", async () => {
try {
await runBuild2();
} catch (e7) {
if (isBuildFailure(e7)) {
logger.warn("Error building worker script:", e7.message);
return;
}
throw e7;
}
});
} else if (usingWorkerScript) {
const watcher = watch([workerScriptPath], {
persistent: true,
ignoreInitial: true
});
let watchedBundleDependencies = [];
scriptPath4 = workerScriptPath;
let runBuild2 = /* @__PURE__ */ __name(async () => {
await checkRawWorker(
workerScriptPath,
nodejsCompatMode,
() => scriptReadyResolve()
);
}, "runBuild");
if (enableBundling) {
scriptPath4 = (0, import_node_path49.join)(
getPagesTmpDir(),
`./bundledWorker-${Math.random()}.mjs`
);
runBuild2 = /* @__PURE__ */ __name(async () => {
const workerScriptDirectory = (0, import_node_path49.dirname)(workerScriptPath);
let currentBundleDependencies = [];
const bundle = await buildRawWorker({
workerScriptPath: usingWorkerDirectory ? (0, import_node_path49.join)(workerScriptPath, "index.js") : workerScriptPath,
outfile: scriptPath4,
directory: directory ?? ".",
nodejsCompatMode,
local: true,
sourcemap: true,
watch: false,
onEnd: /* @__PURE__ */ __name(() => scriptReadyResolve(), "onEnd"),
defineNavigatorUserAgent,
checkFetch
});
const bundleDependencies = Object.keys(bundle.dependencies).map((dep) => (0, import_node_path49.resolve)(workerScriptDirectory, dep)).filter(
(resolvedDep) => !resolvedDep.includes((0, import_node_path49.normalize)(singleWorkerScriptPath)) && !resolvedDep.includes((0, import_node_path49.normalize)("/.wrangler/")) && resolvedDep.includes((0, import_node_path49.resolve)(process.cwd()))
);
const bundleModules = bundle.modules.filter((module3) => !!module3.filePath).map(
(module3) => (0, import_node_path49.resolve)(workerScriptDirectory, module3.filePath)
);
currentBundleDependencies = [...bundleDependencies, ...bundleModules];
if (watchedBundleDependencies.length) {
watcher.unwatch(watchedBundleDependencies);
}
watcher.add(currentBundleDependencies);
watchedBundleDependencies = [...currentBundleDependencies];
}, "runBuild");
}
const debouncedRunBuild = debounce(async () => {
try {
await runBuild2();
} catch {
logger.warn(
`Failed to build ${singleWorkerScriptPath}. Continuing to serve the last successfully built version of the Worker.`
);
}
}, 50);
try {
await runBuild2();
watcher.on("all", async (eventName, p6) => {
logger.debug(`\u{1F300} "${eventName}" event detected at ${p6}.`);
if (eventName === "unlink") {
return;
}
debouncedRunBuild();
});
} catch {
throw new FatalError(`Failed to build ${singleWorkerScriptPath}.`);
}
} else if (usingFunctions) {
scriptPath4 = (0, import_node_path49.join)(
getPagesTmpDir(),
`./functionsWorker-${Math.random()}.mjs`
);
const routesModule = (0, import_node_path49.join)(
getPagesTmpDir(),
`./functionsRoutes-${Math.random()}.mjs`
);
logger.debug(`Compiling worker to "${scriptPath4}"...`);
const onEnd = /* @__PURE__ */ __name(() => scriptReadyResolve(), "onEnd");
const watcher = watch([functionsDirectory], {
persistent: true,
ignoreInitial: true
});
let watchedBundleDependencies = [];
const buildFn = /* @__PURE__ */ __name(async () => {
let currentBundleDependencies = [];
const bundle = await buildFunctions({
outfile: scriptPath4,
functionsDirectory,
sourcemap: true,
watch: false,
onEnd,
buildOutputDirectory: directory,
nodejsCompatMode,
local: true,
routesModule,
defineNavigatorUserAgent,
checkFetch
});
const bundleDependencies = Object.keys(bundle.dependencies).map((dep) => (0, import_node_path49.resolve)(functionsDirectory, dep)).filter(
(resolvedDep) => !resolvedDep.includes((0, import_node_path49.normalize)("/functions/")) && !resolvedDep.includes((0, import_node_path49.normalize)("/.wrangler/")) && resolvedDep.includes((0, import_node_path49.resolve)(process.cwd()))
);
const bundleModules = bundle.modules.filter((module3) => !!module3.filePath).map(
(module3) => (0, import_node_path49.resolve)(functionsDirectory, module3.filePath)
);
currentBundleDependencies = [...bundleDependencies, ...bundleModules];
if (watchedBundleDependencies.length) {
watcher.unwatch(watchedBundleDependencies);
}
watcher.add(currentBundleDependencies);
watchedBundleDependencies = [...currentBundleDependencies];
sendMetricsEvent("build pages functions");
}, "buildFn");
const debouncedBuildFn = debounce(async () => {
try {
await buildFn();
} catch (e7) {
if (e7 instanceof FunctionsNoRoutesError) {
logger.warn(
`${getFunctionsNoRoutesWarning(functionsDirectory)}. Continuing to serve the last successfully built version of Functions.`
);
} else {
logger.warn(
`Failed to build Functions at ${functionsDirectory}. Continuing to serve the last successfully built version of Functions.`
);
}
}
}, 50);
try {
await buildFn();
watcher.on("all", async (eventName, p6) => {
logger.debug(`\u{1F300} "${eventName}" event detected at ${p6}.`);
debouncedBuildFn();
});
} catch (e7) {
if (e7 instanceof FunctionsNoRoutesError) {
logger.error(
getFunctionsNoRoutesWarning(functionsDirectory, "skipping")
);
onEnd();
usingFunctions = false;
} else {
throw new FatalError(
`Failed to build Functions at ${functionsDirectory}.`
);
}
}
}
if (!usingFunctions && !usingWorkerScript) {
scriptReadyResolve();
logger.log("No Functions. Shimming...");
scriptPath4 = (0, import_node_path49.resolve)(getBasePath(), "templates/pages-shim.ts");
}
await scriptReadyPromise;
if (scriptPath4 === "") {
throw new Error(
"Failed to start wrangler pages dev due to an unknown error"
);
}
let scriptEntrypoint = scriptPath4;
if (directory && (usingFunctions || usingWorkerScript || usingWorkerDirectory)) {
const routesJSONPath = (0, import_node_path49.join)(directory, "_routes.json");
if ((0, import_node_fs27.existsSync)(routesJSONPath)) {
let routesJSONContents;
const runBuild2 = /* @__PURE__ */ __name(async (entrypointFile, outfile, routes) => {
await esbuild3.build({
entryPoints: [
(0, import_node_path49.resolve)(getBasePath(), "templates/pages-dev-pipeline.ts")
],
bundle: true,
sourcemap: true,
format: "esm",
plugins: [
esbuildAliasExternalPlugin({
__ENTRY_POINT__: entrypointFile,
"./pages-dev-util": (0, import_node_path49.resolve)(
getBasePath(),
"templates/pages-dev-util.ts"
)
})
],
outfile,
define: {
__ROUTES__: routes
}
});
}, "runBuild");
try {
routesJSONContents = (0, import_node_fs27.readFileSync)(routesJSONPath, "utf-8");
validateRoutes(JSON.parse(routesJSONContents), directory);
scriptEntrypoint = (0, import_node_path49.join)(
getPagesTmpDir(),
`${Math.random().toString(36).slice(2)}.js`
);
await runBuild2(scriptPath4, scriptEntrypoint, routesJSONContents);
} catch (err) {
if (err instanceof FatalError) {
throw err;
} else {
throw new FatalError(
`Could not validate _routes.json at ${directory}: ${err}`,
1
);
}
}
watch([routesJSONPath], {
persistent: true,
ignoreInitial: true
}).on("all", async (event) => {
try {
if (event === "unlink") {
return;
}
routesJSONContents = (0, import_node_fs27.readFileSync)(routesJSONPath, "utf-8");
validateRoutes(JSON.parse(routesJSONContents), directory);
await runBuild2(scriptPath4, scriptEntrypoint, routesJSONContents);
} catch (err) {
const error2 = err instanceof FatalError ? err : `Could not validate _routes.json at ${directory}: ${err}`;
const defaultRoutesJSONSpec = {
version: ROUTES_SPEC_VERSION,
include: ["/*"],
exclude: []
};
logger.error(error2);
logger.warn(
`Ignoring provided _routes.json file, and falling back to the following default routes configuration:
${JSON.stringify(defaultRoutesJSONSpec, null, 2)}`
);
routesJSONContents = JSON.stringify(defaultRoutesJSONSpec);
await runBuild2(scriptPath4, scriptEntrypoint, routesJSONContents);
}
});
}
}
const devServer = await run(
{
MULTIWORKER: Array.isArray(args.config),
RESOURCES_PROVISION: false,
REMOTE_BINDINGS: false,
DEPLOY_REMOTE_DIFF_CHECK: false
},
() => startDev({
script: scriptEntrypoint,
_: [],
$0: "",
remote: false,
local: true,
d1Databases: d1_databases,
testScheduled: false,
enablePagesAssetsServiceBinding: {
proxyPort,
directory
},
forceLocal: true,
liveReload: args.liveReload,
showInteractiveDevSession: args.showInteractiveDevSession,
processEntrypoint: true,
additionalModules: modules,
v: void 0,
cwd: void 0,
assets: void 0,
name: void 0,
noBundle: false,
latest: false,
routes: void 0,
host: void 0,
localUpstream: void 0,
upstreamProtocol: void 0,
var: void 0,
define: void 0,
alias: void 0,
jsxFactory: void 0,
jsxFragment: void 0,
tsconfig: void 0,
minify: void 0,
legacyEnv: void 0,
env: void 0,
envFile: void 0,
ip,
port,
inspectorPort,
localProtocol,
httpsKeyPath: args.httpsKeyPath,
httpsCertPath: args.httpsCertPath,
compatibilityDate,
compatibilityFlags,
nodeCompat: void 0,
vars,
kv: kv_namespaces,
durableObjects: do_bindings,
r2: r2_buckets,
services,
ai: ai2,
rules: usingWorkerDirectory ? [
{
type: "ESModule",
globs: ["**/*.js", "**/*.mjs"]
}
] : void 0,
bundle: enableBundling,
persistTo: args.persistTo,
logLevel: args.logLevel ?? "log",
experimentalProvision: void 0,
experimentalRemoteBindings: false,
experimentalVectorizeBindToProd: false,
experimentalImagesLocalMode: false,
enableIpc: true,
config: Array.isArray(args.config) ? args.config : void 0,
site: void 0,
siteInclude: void 0,
siteExclude: void 0,
enableContainers: false
})
);
sendMetricsEvent("run pages dev");
process.on("exit", CLEANUP);
process.on("SIGINT", CLEANUP);
process.on("SIGTERM", CLEANUP);
await import_node_events2.default.once(devServer.devEnv, "teardown");
const teardownRegistry = await devServer.teardownRegistryPromise;
await teardownRegistry?.(devServer.devEnv.config.latestConfig?.name);
devServer.unregisterHotKeys?.();
CLEANUP();
process.exit(0);
}
});
__name(isWindows3, "isWindows");
__name(sleep, "sleep");
__name(getPids, "getPids");
__name(getPort, "getPort");
__name(spawnProxyProcess, "spawnProxyProcess");
__name(resolvePagesDevServerSettings, "resolvePagesDevServerSettings");
__name(getBindingsFromArgs, "getBindingsFromArgs");
}
});
// src/pages/download-config.ts
async function toEnvironment(deploymentConfig, accountId) {
const configObj = {};
configObj.compatibility_date = deploymentConfig.compatibility_date ?? formatCompatibilityDate(/* @__PURE__ */ new Date());
if (deploymentConfig.always_use_latest_compatibility_date) {
configObj.compatibility_date = import_miniflare16.supportedCompatibilityDate;
}
if (deploymentConfig.compatibility_flags?.length) {
configObj.compatibility_flags = deploymentConfig.compatibility_flags;
}
if (deploymentConfig.placement) {
configObj.placement = deploymentConfig.placement;
} else {
configObj.placement = { mode: "off" };
}
if (deploymentConfig.limits) {
configObj.limits = deploymentConfig.limits;
}
for (const [name2, envVar] of Object.entries(
deploymentConfig.env_vars ?? {}
)) {
if (envVar?.value && envVar?.type == "plain_text") {
configObj.vars ??= {};
configObj.vars[name2] = envVar?.value;
}
}
for (const [name2, namespace] of Object.entries(
deploymentConfig.kv_namespaces ?? {}
)) {
configObj.kv_namespaces ??= [];
configObj.kv_namespaces.push({ id: namespace.namespace_id, binding: name2 });
}
for (const [name2, ns] of Object.entries(
deploymentConfig.durable_object_namespaces ?? {}
)) {
configObj.durable_objects ??= { bindings: [] };
if (ns.class_name && ns.class_name !== "") {
configObj.durable_objects.bindings.push({
name: name2,
class_name: ns.class_name,
script_name: ns.service,
environment: ns.environment
});
} else {
const namespace = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/workers/durable_objects/namespaces/${ns.namespace_id}`
);
configObj.durable_objects.bindings.push({
name: name2,
class_name: namespace.class,
script_name: namespace.script,
environment: namespace.environment
});
}
}
for (const [name2, namespace] of Object.entries(
deploymentConfig.d1_databases ?? {}
)) {
configObj.d1_databases ??= [];
configObj.d1_databases.push({
database_id: namespace.id,
binding: name2,
database_name: name2
});
}
for (const [name2, bucket] of Object.entries(
deploymentConfig.r2_buckets ?? {}
)) {
configObj.r2_buckets ??= [];
configObj.r2_buckets.push({
bucket_name: bucket.name,
binding: name2
});
}
for (const [name2, { service, environment }] of Object.entries(
deploymentConfig.services ?? {}
)) {
configObj.services ??= [];
configObj.services.push({
binding: name2,
service,
environment
});
}
for (const [name2, queue] of Object.entries(
deploymentConfig.queue_producers ?? {}
)) {
configObj.queues ??= { producers: [] };
configObj.queues?.producers?.push({
binding: name2,
queue: queue.name
});
}
for (const [name2, { dataset }] of Object.entries(
deploymentConfig.analytics_engine_datasets ?? {}
)) {
configObj.analytics_engine_datasets ??= [];
configObj.analytics_engine_datasets.push({
binding: name2,
dataset
});
}
for (const [name2] of Object.entries(deploymentConfig.ai_bindings ?? {})) {
configObj.ai = { binding: name2 };
}
return configObj;
}
async function writeWranglerToml(toml) {
let tomlString = import_toml6.default.stringify(toml);
tomlString = tomlString.split("\n").map((line) => line.trimStart()).join("\n");
await (0, import_promises24.writeFile)(
"wrangler.toml",
`# Generated by Wrangler on ${/* @__PURE__ */ new Date()}
${tomlString}`
);
}
function simplifyEnvironments(preview, production) {
const topLevel = { ...preview };
if (preview.compatibility_date === production.compatibility_date) {
delete production.compatibility_date;
delete preview.compatibility_date;
}
if (JSON.stringify(preview.compatibility_flags) === JSON.stringify(production.compatibility_flags)) {
delete production.compatibility_flags;
delete preview.compatibility_date;
}
if (JSON.stringify(preview.placement) === JSON.stringify(production.placement)) {
delete production.placement;
delete preview.placement;
if (topLevel.placement?.mode === "off") {
delete topLevel.placement;
}
}
if (JSON.stringify(preview.limits) === JSON.stringify(production.limits)) {
delete production.limits;
delete preview.limits;
return { topLevel, production };
} else if (preview.limits && !production.limits) {
delete topLevel.limits;
return { topLevel, production, preview };
}
return { topLevel, production };
}
async function downloadProject(accountId, projectName) {
const project = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}`
);
logger.debug(JSON.stringify(project, null, 2));
const { topLevel, preview, production } = simplifyEnvironments(
await toEnvironment(project.deployment_configs.preview, accountId),
await toEnvironment(project.deployment_configs.production, accountId)
);
return {
name: project.name,
pages_build_output_dir: project.build_config.destination_dir,
...topLevel,
...{
env: preview ? {
preview,
production
} : {
production
}
}
};
}
var import_fs17, import_promises24, import_toml6, import_miniflare16, pagesDownloadConfigCommand;
var init_download_config = __esm({
"src/pages/download-config.ts"() {
init_import_meta_url();
import_fs17 = require("fs");
import_promises24 = require("fs/promises");
import_toml6 = __toESM(require_toml());
init_source();
import_miniflare16 = require("miniflare");
init_cfetch();
init_config_cache();
init_create_command();
init_dialogs();
init_misc_variables();
init_errors();
init_logger();
init_metrics();
init_user2();
init_compatibility_date();
init_constants();
__name(toEnvironment, "toEnvironment");
__name(writeWranglerToml, "writeWranglerToml");
__name(simplifyEnvironments, "simplifyEnvironments");
__name(downloadProject, "downloadProject");
pagesDownloadConfigCommand = createCommand({
metadata: {
description: "Download your Pages project config as a Wrangler configuration file",
status: "experimental",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
projectName: {
type: "string",
description: "The Pages project to download"
},
force: {
description: "Overwrite an existing Wrangler configuration file without prompting",
type: "boolean"
}
},
positionalArgs: ["projectName"],
async handler({ projectName, force }) {
void sendMetricsEvent("download pages config");
const projectConfig = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = await requireAuth(projectConfig);
projectName ??= projectConfig.project_name;
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
const config = await downloadProject(accountId, projectName);
if (!force && (0, import_fs17.existsSync)("wrangler.toml")) {
const overwrite = await confirm(
"Your existing Wrangler configuration file will be overwritten. Continue?",
{ fallbackValue: false }
);
if (!overwrite) {
throw new FatalError(
"Not overwriting existing Wrangler configuration file"
);
}
}
await writeWranglerToml(config);
logger.info(
source_default.green(
"Success! Your project settings have been downloaded to wrangler.toml"
)
);
}
});
}
});
// src/pages/functions.ts
var import_node_fs28, import_node_path50, pagesFunctionsOptimizeRoutesCommand;
var init_functions = __esm({
"src/pages/functions.ts"() {
init_import_meta_url();
import_node_fs28 = require("fs");
import_node_path50 = __toESM(require("path"));
init_create_command();
init_errors();
init_routes_transformation();
init_routes_validation();
pagesFunctionsOptimizeRoutesCommand = createCommand({
metadata: {
description: "Consolidate and optimize route paths declared in _routes.json",
status: "stable",
owner: "Workers: Authoring and Testing",
hidden: true
},
behaviour: {
provideConfig: false
},
args: {
routesPath: {
type: "string",
demandOption: true,
description: "The location of the _routes.json file"
},
outputRoutesPath: {
type: "string",
demandOption: true,
description: "The location of the optimized output routes file"
}
},
async handler({ routesPath, outputRoutesPath }) {
let routesFileContents;
const routesOutputDirectory = import_node_path50.default.dirname(outputRoutesPath);
if (!(0, import_node_fs28.existsSync)(routesPath)) {
throw new FatalError(
`Oops! File ${routesPath} does not exist. Please make sure --routes-path is a valid file path (for example "/public/_routes.json").`,
1
);
}
if (!(0, import_node_fs28.existsSync)(routesOutputDirectory) || !(0, import_node_fs28.lstatSync)(routesOutputDirectory).isDirectory()) {
throw new FatalError(
`Oops! Folder ${routesOutputDirectory} does not exist. Please make sure --output-routes-path is a valid file path (for example "/public/_routes.json").`,
1
);
}
try {
routesFileContents = (0, import_node_fs28.readFileSync)(routesPath, "utf-8");
} catch (err) {
throw new FatalError(`Error while reading ${routesPath} file: ${err}`);
}
const routes = JSON.parse(routesFileContents);
validateRoutes(routes, routesPath);
const optimizedRoutes = optimizeRoutesJSONSpec(routes);
const optimizedRoutesContents = JSON.stringify(optimizedRoutes);
try {
(0, import_node_fs28.writeFileSync)(outputRoutesPath, optimizedRoutesContents);
} catch (err) {
throw new FatalError(
`Error writing to ${outputRoutesPath} file: ${err}`,
1
);
}
}
});
}
});
// src/utils/getLegacyScriptName.ts
function getLegacyScriptName(args, config) {
return args.name && args.env && isLegacyEnv(config) ? `${args.name}-${args.env}` : args.name ?? config.name;
}
var init_getLegacyScriptName = __esm({
"src/utils/getLegacyScriptName.ts"() {
init_import_meta_url();
init_isLegacyEnv();
__name(getLegacyScriptName, "getLegacyScriptName");
}
});
// src/utils/std.ts
function trimTrailingWhitespace(str) {
return str.trimEnd();
}
function readFromStdin() {
return new Promise((resolve25, reject) => {
const stdin = process.stdin;
const chunks = [];
stdin.on("readable", () => {
let chunk;
while (null !== (chunk = stdin.read())) {
chunks.push(chunk);
}
});
stdin.on("end", () => {
resolve25(chunks.join(""));
});
stdin.on("error", (err) => {
reject(err);
});
});
}
var init_std = __esm({
"src/utils/std.ts"() {
init_import_meta_url();
__name(trimTrailingWhitespace, "trimTrailingWhitespace");
__name(readFromStdin, "readFromStdin");
}
});
// src/secret/index.ts
function isMissingWorkerError(e7) {
return typeof e7 === "object" && e7 !== null && e7.code === 10007;
}
async function createDraftWorker({
config,
args,
accountId,
scriptName
}) {
const confirmation = await confirm(
`There doesn't seem to be a Worker called "${scriptName}". Do you want to create a new Worker with that name and add secrets to it?`,
// we want to default to true in non-interactive/CI contexts to preserve existing behaviour
{ defaultValue: true, fallbackValue: true }
);
if (!confirmation) {
logger.log("Aborting. No secrets added.");
return null;
} else {
logger.log(`\u{1F300} Creating new Worker "${scriptName}"...`);
}
await fetchResult(
config,
!isLegacyEnv(config) && args.env ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}` : `/accounts/${accountId}/workers/scripts/${scriptName}`,
{
method: "PUT",
body: createWorkerUploadForm({
name: scriptName,
main: {
name: scriptName,
filePath: void 0,
content: `export default { fetch() {} }`,
type: "esm"
},
bindings: {
kv_namespaces: [],
send_email: [],
vars: {},
durable_objects: { bindings: [] },
workflows: [],
queues: [],
r2_buckets: [],
d1_databases: [],
vectorize: [],
hyperdrive: [],
secrets_store_secrets: [],
services: [],
analytics_engine_datasets: [],
wasm_modules: {},
browser: void 0,
ai: void 0,
images: void 0,
version_metadata: void 0,
text_blobs: {},
data_blobs: {},
dispatch_namespaces: [],
mtls_certificates: [],
pipelines: [],
logfwdr: { bindings: [] },
assets: void 0,
unsafe: {
bindings: void 0,
metadata: void 0,
capnp: void 0
},
unsafe_hello_world: []
},
modules: [],
migrations: void 0,
compatibility_date: void 0,
compatibility_flags: void 0,
keepVars: false,
// this doesn't matter since it's a new script anyway
keepSecrets: false,
// this doesn't matter since it's a new script anyway
logpush: false,
sourceMaps: void 0,
placement: void 0,
tail_consumers: void 0,
limits: void 0,
assets: void 0,
observability: void 0
})
}
);
}
function validateFileSecrets(content, jsonFilePath) {
if (content === null || typeof content !== "object") {
throw new FatalError(
`The contents of "${jsonFilePath}" is not valid. It should be a JSON object of string values.`
);
}
const entries = Object.entries(content);
for (const [key, value] of entries) {
if (typeof value !== "string") {
throw new FatalError(
`The value for "${key}" in "${jsonFilePath}" is not a "string" instead it is of type "${typeof value}"`
);
}
}
}
async function parseBulkInputToObject(input) {
let content;
if (input) {
const jsonFilePath = import_node_path51.default.resolve(input);
try {
const fileContent = readFileSync6(jsonFilePath);
try {
content = parseJSON(fileContent);
} catch (e7) {
content = (0, import_dotenv2.parse)(fileContent);
if (Object.keys(content).length === 0) {
throw e7;
}
}
} catch (e7) {
throw new FatalError(
`The contents of "${input}" is not valid JSON: "${e7}"`
);
}
validateFileSecrets(content, input);
} else {
try {
const rl = import_node_readline2.default.createInterface({ input: process.stdin });
let pipedInput = "";
for await (const line of rl) {
pipedInput += line;
}
try {
content = parseJSON(pipedInput);
} catch (e7) {
content = (0, import_dotenv2.parse)(pipedInput);
if (Object.keys(content).length === 0) {
throw e7;
}
}
} catch {
return;
}
}
return content;
}
var import_node_path51, import_node_readline2, import_dotenv2, import_undici13, VERSION_NOT_DEPLOYED_ERR_CODE, secretNamespace, secretPutCommand, secretDeleteCommand, secretListCommand, secretBulkCommand;
var init_secret = __esm({
"src/secret/index.ts"() {
init_import_meta_url();
import_node_path51 = __toESM(require("path"));
import_node_readline2 = __toESM(require("readline"));
import_dotenv2 = __toESM(require_main());
import_undici13 = __toESM(require_undici());
init_cfetch();
init_config2();
init_create_command();
init_create_worker_upload_form();
init_dialogs();
init_errors();
init_logger();
init_metrics();
init_parse();
init_user2();
init_getLegacyScriptName();
init_isLegacyEnv();
init_std();
VERSION_NOT_DEPLOYED_ERR_CODE = 10215;
__name(isMissingWorkerError, "isMissingWorkerError");
__name(createDraftWorker, "createDraftWorker");
secretNamespace = createNamespace({
metadata: {
description: "\u{1F92B} Generate a secret that can be referenced in a Worker",
status: "stable",
owner: "Workers: Deploy and Config"
}
});
secretPutCommand = createCommand({
metadata: {
description: "Create or update a secret variable for a Worker",
status: "stable",
owner: "Workers: Deploy and Config"
},
positionalArgs: ["key"],
behaviour: {
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
key: {
describe: "The variable name to be accessible in the Worker",
type: "string",
demandOption: true
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
async handler(args, { config }) {
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages secret put` instead."
);
}
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
const accountId = await requireAuth(config);
const isInteractive3 = process.stdin.isTTY;
const secretValue = trimTrailingWhitespace(
isInteractive3 ? await prompt("Enter a secret value:", { isSecret: true }) : await readFromStdin()
);
logger.log(
`\u{1F300} Creating the secret for the Worker "${scriptName}" ${args.env && !isLegacyEnv(config) ? `(${args.env})` : ""}`
);
async function submitSecret() {
const url4 = !args.env || isLegacyEnv(config) ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets` : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
try {
return await fetchResult(config, url4, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: args.key,
text: secretValue,
type: "secret_text"
})
});
} catch (e7) {
if (e7 instanceof APIError && e7.code === VERSION_NOT_DEPLOYED_ERR_CODE) {
throw new UserError(
"Secret edit failed. You attempted to modify a secret, but the latest version of your Worker isn't currently deployed. Please ensure that the latest version of your Worker is fully deployed (wrangler versions deploy) before modifying secrets. Alternatively, you can use the Cloudflare dashboard to modify secrets and deploy the version.\n\nNote: This limitation will be addressed in an upcoming release."
);
} else {
throw e7;
}
}
}
__name(submitSecret, "submitSecret");
try {
await submitSecret();
sendMetricsEvent("create encrypted variable", {
sendMetrics: config.send_metrics
});
} catch (e7) {
if (isMissingWorkerError(e7)) {
const result = await createDraftWorker({
config,
args,
accountId,
scriptName
});
if (result === null) {
return;
}
await submitSecret();
} else {
throw e7;
}
}
logger.log(`\u2728 Success! Uploaded secret ${args.key}`);
}
});
secretDeleteCommand = createCommand({
metadata: {
description: "Delete a secret variable from a Worker",
status: "stable",
owner: "Workers: Deploy and Config"
},
positionalArgs: ["key"],
behaviour: {
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
key: {
describe: "The variable name to be accessible in the Worker",
type: "string",
demandOption: true
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
async handler(args, { config }) {
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages secret delete` instead."
);
}
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
const accountId = await requireAuth(config);
if (await confirm(
`Are you sure you want to permanently delete the secret ${args.key} on the Worker ${scriptName}${args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""}?`
)) {
logger.log(
`\u{1F300} Deleting the secret ${args.key} on the Worker ${scriptName}${args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""}`
);
const url4 = !args.env || isLegacyEnv(config) ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets` : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
await fetchResult(config, `${url4}/${args.key}`, { method: "DELETE" });
sendMetricsEvent("delete encrypted variable", {
sendMetrics: config.send_metrics
});
logger.log(`\u2728 Success! Deleted secret ${args.key}`);
}
}
});
secretListCommand = createCommand({
metadata: {
description: "List all secrets for a Worker",
status: "stable",
owner: "Workers: Deploy and Config"
},
args: {
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
format: {
default: "json",
choices: ["json", "pretty"],
describe: "The format to print the secrets in"
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => args.format === "pretty", "printBanner")
},
async handler(args, { config }) {
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages secret list` instead."
);
}
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
const accountId = await requireAuth(config);
const url4 = !args.env || isLegacyEnv(config) ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets` : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
const secrets = await fetchResult(
config,
url4
);
if (args.format === "pretty") {
for (const workerSecret of secrets) {
logger.log(`Secret Name: ${workerSecret.name}
`);
}
} else {
logger.log(JSON.stringify(secrets, null, " "));
}
sendMetricsEvent("list encrypted variables", {
sendMetrics: config.send_metrics
});
}
});
secretBulkCommand = createCommand({
metadata: {
description: "Bulk upload secrets for a Worker",
status: "stable",
owner: "Workers: Deploy and Config"
},
positionalArgs: ["file"],
behaviour: {
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
file: {
describe: `The file of key-value pairs to upload, as JSON in form {"key": value, ...} or .dev.vars file in the form KEY=VALUE`,
type: "string"
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
async handler(args, { config }) {
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages secret bulk` instead."
);
}
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
const error2 = new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
logger.error(error2.message);
throw error2;
}
const accountId = await requireAuth(config);
logger.log(
`\u{1F300} Creating the secrets for the Worker "${scriptName}" ${args.env && !isLegacyEnv(config) ? `(${args.env})` : ""}`
);
const content = await parseBulkInputToObject(args.file);
if (!content) {
return logger.error(`\u{1F6A8} No content found in file, or piped input.`);
}
function getSettings2() {
const url4 = !args.env || isLegacyEnv(config) ? `/accounts/${accountId}/workers/scripts/${scriptName}/settings` : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/settings`;
return fetchResult(config, url4);
}
__name(getSettings2, "getSettings");
function putBindingsSettings(bindings) {
const url4 = !args.env || isLegacyEnv(config) ? `/accounts/${accountId}/workers/scripts/${scriptName}/settings` : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/settings`;
const data = new import_undici13.FormData();
data.set("settings", JSON.stringify({ bindings }));
return fetchResult(config, url4, {
method: "PATCH",
body: data
});
}
__name(putBindingsSettings, "putBindingsSettings");
let existingBindings;
try {
const settings = await getSettings2();
existingBindings = settings.bindings;
} catch (e7) {
if (isMissingWorkerError(e7)) {
const result = await createDraftWorker({
config,
args,
accountId,
scriptName
});
if (result === null) {
return;
}
existingBindings = [];
} else {
throw e7;
}
}
const inheritBindings = existingBindings.filter((binding) => {
return binding.type !== "secret_text" || content[binding.name] === void 0;
}).map((binding) => ({ type: binding.type, name: binding.name }));
const upsertBindings = Object.entries(
content
).map(([key, value]) => {
return {
type: "secret_text",
name: key,
text: value
};
});
try {
await putBindingsSettings(inheritBindings.concat(upsertBindings));
for (const upsertedBinding of upsertBindings) {
logger.log(
`\u2728 Successfully created secret for key: ${upsertedBinding.name}`
);
}
logger.log("");
logger.log("Finished processing secrets file:");
logger.log(`\u2728 ${upsertBindings.length} secrets successfully uploaded`);
} catch (err) {
logger.log("");
logger.log(`\u{1F6A8} Secrets failed to upload`);
throw err;
}
}
});
__name(validateFileSecrets, "validateFileSecrets");
__name(parseBulkInputToObject, "parseBulkInputToObject");
}
});
// src/pages/secret/index.ts
function isPagesEnv(env6) {
return ["production", "preview"].includes(env6);
}
async function pagesProject(env6, cliProjectName) {
env6 ??= "production";
if (!isPagesEnv(env6)) {
throw new FatalError(
`Pages does not support the "${env6}" named environment. Please specify "production" (default) or "preview"`,
1
);
}
let config;
const { configPath } = findWranglerConfig(process.cwd());
try {
config = readPagesConfig({ config: configPath, env: void 0 });
} catch (err) {
if (!(err instanceof FatalError && err.code === EXIT_CODE_INVALID_PAGES_CONFIG)) {
throw err;
}
}
if (configPath && config === void 0) {
logger.warn(
`Pages now has ${configFileName(configPath)} support.
We detected a configuration file at ${configPath} but it is missing the "pages_build_output_dir" field, required by Pages.
If you would like to use this configuration file for your project, please use "pages_build_output_dir" to specify the directory of static files to upload.
Ignoring configuration file for now.`
);
}
const configCache = getConfigCache(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = await requireAuth(configCache);
const projectName = cliProjectName ?? config?.name ?? configCache.project_name;
let project;
if (projectName) {
try {
project = await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${projectName}`
);
} catch (err) {
if (err.code === 8000007) {
throw new FatalError(`Project "${projectName}" does not exist.`, 1);
}
throw err;
}
} else {
throw new FatalError("Must specify a project name.", 1);
}
return { env: env6, project, accountId, config };
}
var pagesSecretNamespace, pagesSecretPutCommand, pagesSecretBulkCommand, pagesSecretDeleteCommand, pagesSecretListCommand;
var init_secret2 = __esm({
"src/pages/secret/index.ts"() {
init_import_meta_url();
init_source();
init_cfetch();
init_config2();
init_config_cache();
init_config_helpers();
init_create_command();
init_dialogs();
init_misc_variables();
init_errors();
init_is_interactive();
init_logger();
init_metrics();
init_secret();
init_user2();
init_std();
init_constants();
init_errors3();
__name(isPagesEnv, "isPagesEnv");
__name(pagesProject, "pagesProject");
pagesSecretNamespace = createNamespace({
metadata: {
description: "Generate a secret that can be referenced in a Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
}
});
pagesSecretPutCommand = createCommand({
metadata: {
description: "Create or update a secret variable for a Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
key: {
type: "string",
description: "The variable name to be accessible in the Pages project",
demandOption: true
},
"project-name": {
type: "string",
alias: ["project"],
description: "The name of your Pages project"
}
},
positionalArgs: ["key"],
async handler(args) {
const { env: env6, project, accountId, config } = await pagesProject(
args.env,
args.projectName
);
const secretValue = trimTrailingWhitespace(
isInteractive2() ? await prompt("Enter a secret value:", { isSecret: true }) : await readFromStdin()
);
logger.log(
`\u{1F300} Creating the secret for the Pages project "${project.name}" (${env6})`
);
await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${project.name}`,
{
method: "PATCH",
body: JSON.stringify({
deployment_configs: {
[env6]: {
env_vars: {
[args.key]: {
value: secretValue,
type: "secret_text"
}
},
wrangler_config_hash: project.deployment_configs[env6].wrangler_config_hash
}
}
})
}
);
sendMetricsEvent("create pages encrypted variable", {
sendMetrics: config?.send_metrics
});
logger.log(`\u2728 Success! Uploaded secret ${args.key}`);
}
});
pagesSecretBulkCommand = createCommand({
metadata: {
description: "Bulk upload secrets for a Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
file: {
type: "string",
description: `The file of key-value pairs to upload, as JSON in form {"key": value, ...} or .dev.vars file in the form KEY=VALUE`
},
"project-name": {
type: "string",
alias: ["project"],
description: "The name of your Pages project"
}
},
positionalArgs: ["file"],
async handler(args) {
const { env: env6, project, accountId } = await pagesProject(
args.env,
args.projectName
);
logger.log(
`\u{1F300} Creating the secrets for the Pages project "${project.name}" (${env6})`
);
const content = await parseBulkInputToObject(args.file);
if (!content) {
throw new FatalError(`\u{1F6A8} No content found in file or piped input.`);
}
const upsertBindings = Object.fromEntries(
Object.entries(content).map(([key, value]) => {
return [
key,
{
type: "secret_text",
value
}
];
})
);
try {
await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${project.name}`,
{
method: "PATCH",
body: JSON.stringify({
deployment_configs: {
[env6]: {
env_vars: {
...upsertBindings
},
wrangler_config_hash: project.deployment_configs[env6].wrangler_config_hash
}
}
})
}
);
logger.log("Finished processing secrets file:");
logger.log(
`\u2728 ${Object.keys(upsertBindings).length} secrets successfully uploaded`
);
} catch (err) {
logger.log(`\u{1F6A8} Secrets failed to upload`);
throw err;
}
}
});
pagesSecretDeleteCommand = createCommand({
metadata: {
description: "Delete a secret variable from a Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
key: {
type: "string",
description: "The variable name to be accessible in the Pages project",
demandOption: true
},
"project-name": {
type: "string",
alias: ["project"],
description: "The name of your Pages project"
}
},
positionalArgs: ["key"],
async handler(args) {
const { env: env6, project, accountId, config } = await pagesProject(
args.env,
args.projectName
);
if (await confirm(
`Are you sure you want to permanently delete the secret ${args.key} on the Pages project ${project.name} (${env6})?`
)) {
logger.log(
`\u{1F300} Deleting the secret ${args.key} on the Pages project ${project.name} (${env6})`
);
await fetchResult(
COMPLIANCE_REGION_CONFIG_PUBLIC,
`/accounts/${accountId}/pages/projects/${project.name}`,
{
method: "PATCH",
body: JSON.stringify({
deployment_configs: {
[env6]: {
env_vars: {
[args.key]: null
},
wrangler_config_hash: project.deployment_configs[env6].wrangler_config_hash
}
}
})
}
);
sendMetricsEvent("delete pages encrypted variable", {
sendMetrics: config?.send_metrics
});
logger.log(`\u2728 Success! Deleted secret ${args.key}`);
}
}
});
pagesSecretListCommand = createCommand({
metadata: {
description: "List all secrets for a Pages project",
status: "stable",
owner: "Workers: Authoring and Testing",
hideGlobalFlags: ["config", "env"]
},
behaviour: {
provideConfig: false
},
args: {
"project-name": {
type: "string",
alias: ["project"],
description: "The name of your Pages project"
}
},
async handler(args) {
const { env: env6, project, config } = await pagesProject(
args.env,
args.projectName
);
const secrets = Object.entries(
project.deployment_configs[env6].env_vars ?? {}
).filter(([_4, val2]) => val2?.type === "secret_text");
const message = [
`The "${source_default.blue(env6)}" environment of your Pages project "${source_default.blue(
project.name
)}" has access to the following secrets:`,
...secrets.map(
([name2]) => ` - ${name2}: ${source_default.italic("Value Encrypted")}`
)
].join("\n");
logger.log(message);
sendMetricsEvent("list pages encrypted variables", {
sendMetrics: config?.send_metrics
});
}
});
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig;
var init_httpExtensionConfiguration = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
init_import_meta_url();
getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
let httpHandler = runtimeConfig.httpHandler;
return {
setHttpHandler(handler) {
httpHandler = handler;
},
httpHandler() {
return httpHandler;
},
updateHttpClientConfig(key, value) {
httpHandler.updateHttpClientConfig(key, value);
},
httpHandlerConfigs() {
return httpHandler.httpHandlerConfigs();
}
};
}, "getHttpHandlerExtensionConfiguration");
resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => {
return {
httpHandler: httpHandlerExtensionConfiguration.httpHandler()
};
}, "resolveHttpHandlerRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
init_import_meta_url();
init_httpExtensionConfiguration();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/abort.js
var init_abort = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/abort.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/auth.js
var HttpAuthLocation;
var init_auth = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/auth.js"() {
init_import_meta_url();
(function(HttpAuthLocation2) {
HttpAuthLocation2["HEADER"] = "header";
HttpAuthLocation2["QUERY"] = "query";
})(HttpAuthLocation || (HttpAuthLocation = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
var HttpApiKeyAuthLocation;
var init_HttpApiKeyAuth = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"() {
init_import_meta_url();
(function(HttpApiKeyAuthLocation2) {
HttpApiKeyAuthLocation2["HEADER"] = "header";
HttpApiKeyAuthLocation2["QUERY"] = "query";
})(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
var init_HttpAuthScheme = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
var init_HttpAuthSchemeProvider = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpSigner.js
var init_HttpSigner = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/HttpSigner.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
var init_IdentityProviderConfig = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/index.js
var init_auth2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/auth/index.js"() {
init_import_meta_url();
init_auth();
init_HttpApiKeyAuth();
init_HttpAuthScheme();
init_HttpAuthSchemeProvider();
init_HttpSigner();
init_IdentityProviderConfig();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
var init_blob_payload_input_types = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/checksum.js
var init_checksum = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/checksum.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/client.js
var init_client4 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/client.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/command.js
var init_command3 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/command.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/config.js
var init_config4 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/config.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/manager.js
var init_manager = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/manager.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/pool.js
var init_pool = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/pool.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/index.js
var init_connection = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/connection/index.js"() {
init_import_meta_url();
init_config4();
init_manager();
init_pool();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/crypto.js
var init_crypto = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/crypto.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/encode.js
var init_encode = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/encode.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoint.js
var EndpointURLScheme;
var init_endpoint = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoint.js"() {
init_import_meta_url();
(function(EndpointURLScheme2) {
EndpointURLScheme2["HTTP"] = "http";
EndpointURLScheme2["HTTPS"] = "https";
})(EndpointURLScheme || (EndpointURLScheme = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
var init_EndpointRuleObject = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
var init_ErrorRuleObject = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
var init_RuleSetObject = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/shared.js
var init_shared2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/shared.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
var init_TreeRuleObject = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/index.js
var init_endpoints = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/endpoints/index.js"() {
init_import_meta_url();
init_EndpointRuleObject();
init_ErrorRuleObject();
init_RuleSetObject();
init_shared2();
init_TreeRuleObject();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/eventStream.js
var init_eventStream = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/eventStream.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/checksum.js
var AlgorithmId;
var init_checksum2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/checksum.js"() {
init_import_meta_url();
(function(AlgorithmId2) {
AlgorithmId2["MD5"] = "md5";
AlgorithmId2["CRC32"] = "crc32";
AlgorithmId2["CRC32C"] = "crc32c";
AlgorithmId2["SHA1"] = "sha1";
AlgorithmId2["SHA256"] = "sha256";
})(AlgorithmId || (AlgorithmId = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
var init_defaultClientConfiguration = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"() {
init_import_meta_url();
init_checksum2();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
var init_defaultExtensionConfiguration = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/index.js
var init_extensions2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/extensions/index.js"() {
init_import_meta_url();
init_defaultClientConfiguration();
init_defaultExtensionConfiguration();
init_checksum2();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/feature-ids.js
var init_feature_ids = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/feature-ids.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/http.js
var FieldPosition;
var init_http = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/http.js"() {
init_import_meta_url();
(function(FieldPosition2) {
FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
})(FieldPosition || (FieldPosition = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
var init_httpHandlerInitialization = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
var init_apiKeyIdentity = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
var init_awsCredentialIdentity = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/identity.js
var init_identity = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/identity.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
var init_tokenIdentity = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/index.js
var init_identity2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/identity/index.js"() {
init_import_meta_url();
init_apiKeyIdentity();
init_awsCredentialIdentity();
init_identity();
init_tokenIdentity();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/logger.js
var init_logger2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/logger.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/middleware.js
var SMITHY_CONTEXT_KEY;
var init_middleware2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/middleware.js"() {
init_import_meta_url();
SMITHY_CONTEXT_KEY = "__smithy_context";
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/pagination.js
var init_pagination = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/pagination.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/profile.js
var IniSectionType;
var init_profile = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/profile.js"() {
init_import_meta_url();
(function(IniSectionType2) {
IniSectionType2["PROFILE"] = "profile";
IniSectionType2["SSO_SESSION"] = "sso-session";
IniSectionType2["SERVICES"] = "services";
})(IniSectionType || (IniSectionType = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/response.js
var init_response = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/response.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/retry.js
var init_retry2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/retry.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/serde.js
var init_serde = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/serde.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/shapes.js
var init_shapes = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/shapes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/signature.js
var init_signature = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/signature.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/stream.js
var init_stream2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/stream.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
var init_streaming_blob_common_types = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
var init_streaming_blob_payload_input_types = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
var init_streaming_blob_payload_output_types = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transfer.js
var RequestHandlerProtocol;
var init_transfer = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transfer.js"() {
init_import_meta_url();
(function(RequestHandlerProtocol2) {
RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
})(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
var init_client_payload_blob_type_narrow = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transform/no-undefined.js
var init_no_undefined = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transform/no-undefined.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transform/type-transform.js
var init_type_transform = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/transform/type-transform.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/uri.js
var init_uri = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/uri.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/util.js
var init_util2 = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/util.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/waiter.js
var init_waiter = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/waiter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/index.js
var init_dist_es = __esm({
"../../node_modules/.pnpm/@smithy+types@3.7.2/node_modules/@smithy/types/dist-es/index.js"() {
init_import_meta_url();
init_abort();
init_auth2();
init_blob_payload_input_types();
init_checksum();
init_client4();
init_command3();
init_connection();
init_crypto();
init_encode();
init_endpoint();
init_endpoints();
init_eventStream();
init_extensions2();
init_feature_ids();
init_http();
init_httpHandlerInitialization();
init_identity2();
init_logger2();
init_middleware2();
init_pagination();
init_profile();
init_response();
init_retry2();
init_serde();
init_shapes();
init_signature();
init_stream2();
init_streaming_blob_common_types();
init_streaming_blob_payload_input_types();
init_streaming_blob_payload_output_types();
init_transfer();
init_client_payload_blob_type_narrow();
init_no_undefined();
init_type_transform();
init_uri();
init_util2();
init_waiter();
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
init_import_meta_url();
init_dist_es();
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery(query) {
return Object.keys(query).reduce((carry, paramName) => {
const param = query[paramName];
return {
...carry,
[paramName]: Array.isArray(param) ? [...param] : param
};
}, {});
}
var HttpRequest;
var init_httpRequest = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
init_import_meta_url();
HttpRequest = class _HttpRequest {
static {
__name(this, "HttpRequest");
}
constructor(options) {
this.method = options.method || "GET";
this.hostname = options.hostname || "localhost";
this.port = options.port;
this.query = options.query || {};
this.headers = options.headers || {};
this.body = options.body;
this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
this.username = options.username;
this.password = options.password;
this.fragment = options.fragment;
}
static clone(request4) {
const cloned = new _HttpRequest({
...request4,
headers: { ...request4.headers }
});
if (cloned.query) {
cloned.query = cloneQuery(cloned.query);
}
return cloned;
}
static isInstance(request4) {
if (!request4) {
return false;
}
const req = request4;
return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
}
clone() {
return _HttpRequest.clone(this);
}
};
__name(cloneQuery, "cloneQuery");
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var HttpResponse;
var init_httpResponse = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
init_import_meta_url();
HttpResponse = class {
static {
__name(this, "HttpResponse");
}
constructor(options) {
this.statusCode = options.statusCode;
this.reason = options.reason;
this.headers = options.headers || {};
this.body = options.body;
}
static isInstance(response) {
if (!response)
return false;
const resp = response;
return typeof resp.statusCode === "number" && typeof resp.headers === "object";
}
};
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
function isValidHostname(hostname2) {
const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
return hostPattern.test(hostname2);
}
var init_isValidHostname = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
init_import_meta_url();
__name(isValidHostname, "isValidHostname");
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types4 = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es2 = __esm({
"../../node_modules/.pnpm/@smithy+protocol-http@4.1.8/node_modules/@smithy/protocol-http/dist-es/index.js"() {
init_import_meta_url();
init_extensions();
init_Field();
init_Fields();
init_httpHandler();
init_httpRequest();
init_httpResponse();
init_isValidHostname();
init_types4();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.714.0/node_modules/@aws-sdk/middleware-expect-continue/dist-es/index.js
function addExpectContinueMiddleware(options) {
return (next) => async (args) => {
const { request: request4 } = args;
if (HttpRequest.isInstance(request4) && request4.body && options.runtime === "node") {
if (options.requestHandler?.constructor?.name !== "FetchHttpHandler") {
request4.headers = {
...request4.headers,
Expect: "100-continue"
};
}
}
return next({
...args,
request: request4
});
};
}
var addExpectContinueMiddlewareOptions, getAddExpectContinuePlugin;
var init_dist_es3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.714.0/node_modules/@aws-sdk/middleware-expect-continue/dist-es/index.js"() {
init_import_meta_url();
init_dist_es2();
__name(addExpectContinueMiddleware, "addExpectContinueMiddleware");
addExpectContinueMiddlewareOptions = {
step: "build",
tags: ["SET_EXPECT_HEADER", "EXPECT_HEADER"],
name: "addExpectContinueMiddleware",
override: true
};
getAddExpectContinuePlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(addExpectContinueMiddleware(options), addExpectContinueMiddlewareOptions);
}, "applyToStack")
}), "getAddExpectContinuePlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/constants.js
var RequestChecksumCalculation, DEFAULT_REQUEST_CHECKSUM_CALCULATION, ResponseChecksumValidation, DEFAULT_RESPONSE_CHECKSUM_VALIDATION, ChecksumAlgorithm, ChecksumLocation, DEFAULT_CHECKSUM_ALGORITHM, S3_EXPRESS_DEFAULT_CHECKSUM_ALGORITHM;
var init_constants6 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/constants.js"() {
init_import_meta_url();
RequestChecksumCalculation = {
WHEN_SUPPORTED: "WHEN_SUPPORTED",
WHEN_REQUIRED: "WHEN_REQUIRED"
};
DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED;
ResponseChecksumValidation = {
WHEN_SUPPORTED: "WHEN_SUPPORTED",
WHEN_REQUIRED: "WHEN_REQUIRED"
};
DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED;
(function(ChecksumAlgorithm2) {
ChecksumAlgorithm2["MD5"] = "MD5";
ChecksumAlgorithm2["CRC32"] = "CRC32";
ChecksumAlgorithm2["CRC32C"] = "CRC32C";
ChecksumAlgorithm2["SHA1"] = "SHA1";
ChecksumAlgorithm2["SHA256"] = "SHA256";
})(ChecksumAlgorithm || (ChecksumAlgorithm = {}));
(function(ChecksumLocation2) {
ChecksumLocation2["HEADER"] = "header";
ChecksumLocation2["TRAILER"] = "trailer";
})(ChecksumLocation || (ChecksumLocation = {}));
DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.MD5;
S3_EXPRESS_DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.CRC32;
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/stringUnionSelector.js
var SelectorType, stringUnionSelector;
var init_stringUnionSelector = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/stringUnionSelector.js"() {
init_import_meta_url();
(function(SelectorType3) {
SelectorType3["ENV"] = "env";
SelectorType3["CONFIG"] = "shared config entry";
})(SelectorType || (SelectorType = {}));
stringUnionSelector = /* @__PURE__ */ __name((obj, key, union, type) => {
if (!(key in obj))
return void 0;
const value = obj[key].toUpperCase();
if (!Object.values(union).includes(value)) {
throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union)}, got '${obj[key]}'.`);
}
return value;
}, "stringUnionSelector");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS.js
var ENV_REQUEST_CHECKSUM_CALCULATION, CONFIG_REQUEST_CHECKSUM_CALCULATION, NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS;
var init_NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS.js"() {
init_import_meta_url();
init_constants6();
init_stringUnionSelector();
ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION";
CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation";
NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => stringUnionSelector(env6, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.ENV), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.CONFIG), "configFileSelector"),
default: DEFAULT_REQUEST_CHECKSUM_CALCULATION
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS.js
var ENV_RESPONSE_CHECKSUM_VALIDATION, CONFIG_RESPONSE_CHECKSUM_VALIDATION, NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS;
var init_NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS.js"() {
init_import_meta_url();
init_constants6();
init_stringUnionSelector();
ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION";
CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation";
NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => stringUnionSelector(env6, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.ENV), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.CONFIG), "configFileSelector"),
default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js
var state, emitWarningIfUnsupportedVersion;
var init_emitWarningIfUnsupportedVersion = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() {
init_import_meta_url();
state = {
warningEmitted: false
};
emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version5) => {
if (version5 && !state.warningEmitted && parseInt(version5.substring(1, version5.indexOf("."))) < 18) {
state.warningEmitted = true;
process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
no longer support Node.js 16.x on January 6, 2025.
To continue receiving updates to AWS services, bug fixes, and security
updates please upgrade to a supported Node.js LTS version.
More information can be found at: https://a.co/74kJMmI`);
}
}, "emitWarningIfUnsupportedVersion");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js
function setCredentialFeature(credentials, feature, value) {
if (!credentials.$source) {
credentials.$source = {};
}
credentials.$source[feature] = value;
return credentials;
}
var init_setCredentialFeature = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() {
init_import_meta_url();
__name(setCredentialFeature, "setCredentialFeature");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js
function setFeature(context2, feature, value) {
if (!context2.__aws_sdk_context) {
context2.__aws_sdk_context = {
features: {}
};
} else if (!context2.__aws_sdk_context.features) {
context2.__aws_sdk_context.features = {};
}
context2.__aws_sdk_context.features[feature] = value;
}
var init_setFeature = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() {
init_import_meta_url();
__name(setFeature, "setFeature");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js
var init_client5 = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() {
init_import_meta_url();
init_emitWarningIfUnsupportedVersion();
init_setCredentialFeature();
init_setFeature();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
var getDateHeader;
var init_getDateHeader = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() {
init_import_meta_url();
init_dist_es2();
getDateHeader = /* @__PURE__ */ __name((response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
var getSkewCorrectedDate;
var init_getSkewCorrectedDate = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() {
init_import_meta_url();
getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
var isClockSkewed;
var init_isClockSkewed = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() {
init_import_meta_url();
init_getSkewCorrectedDate();
isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
var getUpdatedSystemClockOffset;
var init_getUpdatedSystemClockOffset = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() {
init_import_meta_url();
init_isClockSkewed();
getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => {
const clockTimeInMs = Date.parse(clockTime);
if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
return clockTimeInMs - Date.now();
}
return currentSystemClockOffset;
}, "getUpdatedSystemClockOffset");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
var init_utils7 = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() {
init_import_meta_url();
init_getDateHeader();
init_getSkewCorrectedDate();
init_getUpdatedSystemClockOffset();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
var throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer;
var init_AwsSdkSigV4Signer = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() {
init_import_meta_url();
init_dist_es2();
init_utils7();
throwSigningPropertyError = /* @__PURE__ */ __name((name2, property) => {
if (!property) {
throw new Error(`Property \`${name2}\` is not resolved for AWS SDK SigV4Auth`);
}
return property;
}, "throwSigningPropertyError");
validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => {
const context2 = throwSigningPropertyError("context", signingProperties.context);
const config = throwSigningPropertyError("config", signingProperties.config);
const authScheme = context2.endpointV2?.properties?.authSchemes?.[0];
const signerFunction = throwSigningPropertyError("signer", config.signer);
const signer = await signerFunction(authScheme);
const signingRegion = signingProperties?.signingRegion;
const signingRegionSet = signingProperties?.signingRegionSet;
const signingName = signingProperties?.signingName;
return {
config,
signer,
signingRegion,
signingRegionSet,
signingName
};
}, "validateSigningProperties");
AwsSdkSigV4Signer = class {
static {
__name(this, "AwsSdkSigV4Signer");
}
async sign(httpRequest2, identity, signingProperties) {
if (!HttpRequest.isInstance(httpRequest2)) {
throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
}
const validatedProps = await validateSigningProperties(signingProperties);
const { config, signer } = validatedProps;
let { signingRegion, signingName } = validatedProps;
const handlerExecutionContext = signingProperties.context;
if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
const [first, second] = handlerExecutionContext.authSchemes;
if (first?.name === "sigv4a" && second?.name === "sigv4") {
signingRegion = second?.signingRegion ?? signingRegion;
signingName = second?.signingName ?? signingName;
}
}
const signedRequest = await signer.sign(httpRequest2, {
signingDate: getSkewCorrectedDate(config.systemClockOffset),
signingRegion,
signingService: signingName
});
return signedRequest;
}
errorHandler(signingProperties) {
return (error2) => {
const serverTime = error2.ServerTime ?? getDateHeader(error2.$response);
if (serverTime) {
const config = throwSigningPropertyError("config", signingProperties.config);
const initialSystemClockOffset = config.systemClockOffset;
config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
if (clockSkewCorrected && error2.$metadata) {
error2.$metadata.clockSkewCorrected = true;
}
}
throw error2;
};
}
successHandler(httpResponse, signingProperties) {
const dateHeader = getDateHeader(httpResponse);
if (dateHeader) {
const config = throwSigningPropertyError("config", signingProperties.config);
config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
}
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js
var AwsSdkSigV4ASigner;
var init_AwsSdkSigV4ASigner = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js"() {
init_import_meta_url();
init_dist_es2();
init_utils7();
init_AwsSdkSigV4Signer();
AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer {
static {
__name(this, "AwsSdkSigV4ASigner");
}
async sign(httpRequest2, identity, signingProperties) {
if (!HttpRequest.isInstance(httpRequest2)) {
throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
}
const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);
const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.();
const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(",");
const signedRequest = await signer.sign(httpRequest2, {
signingDate: getSkewCorrectedDate(config.systemClockOffset),
signingRegion: multiRegionOverride,
signingService: signingName
});
return signedRequest;
}
};
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/getSmithyContext.js
var init_getSmithyContext = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/getSmithyContext.js"() {
init_import_meta_url();
init_dist_es();
}
});
// ../../node_modules/.pnpm/@smithy+util-middleware@3.0.11/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js
var getSmithyContext;
var init_getSmithyContext2 = __esm({
"../../node_modules/.pnpm/@smithy+util-middleware@3.0.11/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"() {
init_import_meta_url();
init_dist_es();
getSmithyContext = /* @__PURE__ */ __name((context2) => context2[SMITHY_CONTEXT_KEY] || (context2[SMITHY_CONTEXT_KEY] = {}), "getSmithyContext");
}
});
// ../../node_modules/.pnpm/@smithy+util-middleware@3.0.11/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js
var normalizeProvider;
var init_normalizeProvider = __esm({
"../../node_modules/.pnpm/@smithy+util-middleware@3.0.11/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"() {
init_import_meta_url();
normalizeProvider = /* @__PURE__ */ __name((input) => {
if (typeof input === "function")
return input;
const promisified = Promise.resolve(input);
return () => promisified;
}, "normalizeProvider");
}
});
// ../../node_modules/.pnpm/@smithy+util-middleware@3.0.11/node_modules/@smithy/util-middleware/dist-es/index.js
var init_dist_es4 = __esm({
"../../node_modules/.pnpm/@smithy+util-middleware@3.0.11/node_modules/@smithy/util-middleware/dist-es/index.js"() {
init_import_meta_url();
init_getSmithyContext2();
init_normalizeProvider();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
function convertHttpAuthSchemesToMap(httpAuthSchemes) {
const map2 = /* @__PURE__ */ new Map();
for (const scheme of httpAuthSchemes) {
map2.set(scheme.schemeId, scheme);
}
return map2;
}
var httpAuthSchemeMiddleware;
var init_httpAuthSchemeMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() {
init_import_meta_url();
init_dist_es();
init_dist_es4();
__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap");
httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context2) => async (args) => {
const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context2, args.input));
const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
const smithyContext = getSmithyContext(context2);
const failureReasons = [];
for (const option of options) {
const scheme = authSchemes.get(option.schemeId);
if (!scheme) {
failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
continue;
}
const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));
if (!identityProvider) {
failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
continue;
}
const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context2) || {};
option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
smithyContext.selectedHttpAuthScheme = {
httpAuthOption: option,
identity: await identityProvider(option.identityProperties),
signer: scheme.signer
};
break;
}
if (!smithyContext.selectedHttpAuthScheme) {
throw new Error(failureReasons.join("\n"));
}
return next(args);
}, "httpAuthSchemeMiddleware");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() {
init_import_meta_url();
init_httpAuthSchemeMiddleware();
httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware"
};
getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
httpAuthSchemeParametersProvider,
identityProviderConfigProvider
}), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
}, "applyToStack")
}), "getHttpAuthSchemeEndpointRuleSetPlugin");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js
var deserializerMiddleware;
var init_deserializerMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js"() {
init_import_meta_url();
deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next) => async (args) => {
const { response } = await next(args);
try {
const parsed = await deserializer(response, options);
return {
response,
output: parsed
};
} catch (error2) {
Object.defineProperty(error2, "$response", {
value: response
});
if (!("$metadata" in error2)) {
const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
error2.message += "\n " + hint;
if (typeof error2.$responseBodyText !== "undefined") {
if (error2.$response) {
error2.$response.body = error2.$responseBodyText;
}
}
}
throw error2;
}
}, "deserializerMiddleware");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js
var serializerMiddleware;
var init_serializerMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js"() {
init_import_meta_url();
serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context2) => async (args) => {
const endpoint = context2.endpointV2?.url && options.urlParser ? async () => options.urlParser(context2.endpointV2.url) : options.endpoint;
if (!endpoint) {
throw new Error("No valid endpoint provider available.");
}
const request4 = await serializer(args.input, { ...options, endpoint });
return next({
...args,
request: request4
});
}, "serializerMiddleware");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js
function getSerdePlugin(config, serializer, deserializer) {
return {
applyToStack: /* @__PURE__ */ __name((commandStack) => {
commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
}, "applyToStack")
};
}
var deserializerMiddlewareOption, serializerMiddlewareOption;
var init_serdePlugin = __esm({
"../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js"() {
init_import_meta_url();
init_deserializerMiddleware();
init_serializerMiddleware();
deserializerMiddlewareOption = {
name: "deserializerMiddleware",
step: "deserialize",
tags: ["DESERIALIZER"],
override: true
};
serializerMiddlewareOption = {
name: "serializerMiddleware",
step: "serialize",
tags: ["SERIALIZER"],
override: true
};
__name(getSerdePlugin, "getSerdePlugin");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/index.js
var init_dist_es5 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-serde@3.0.11/node_modules/@smithy/middleware-serde/dist-es/index.js"() {
init_import_meta_url();
init_deserializerMiddleware();
init_serdePlugin();
init_serializerMiddleware();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var httpAuthSchemeMiddlewareOptions;
var init_getHttpAuthSchemePlugin = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() {
init_import_meta_url();
init_dist_es5();
init_httpAuthSchemeMiddleware();
httpAuthSchemeMiddlewareOptions = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: serializerMiddlewareOption.name
};
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() {
init_import_meta_url();
init_httpAuthSchemeMiddleware();
init_getHttpAuthSchemeEndpointRuleSetPlugin();
init_getHttpAuthSchemePlugin();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
var init_httpSigningMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es();
init_dist_es4();
defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error2) => {
throw error2;
}, "defaultErrorHandler");
defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => {
}, "defaultSuccessHandler");
httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context2) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
const smithyContext = getSmithyContext(context2);
const scheme = smithyContext.selectedHttpAuthScheme;
if (!scheme) {
throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
}
const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
const output = await next({
...args,
request: await signer.sign(args.request, identity, signingProperties)
}).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
(signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
return output;
}, "httpSigningMiddleware");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var httpSigningMiddlewareOptions, getHttpSigningPlugin;
var init_getHttpSigningMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() {
init_import_meta_url();
init_httpSigningMiddleware();
httpSigningMiddlewareOptions = {
step: "finalizeRequest",
tags: ["HTTP_SIGNING"],
name: "httpSigningMiddleware",
aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
override: true,
relation: "after",
toMiddleware: "retryMiddleware"
};
getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
}, "applyToStack")
}), "getHttpSigningPlugin");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() {
init_import_meta_url();
init_httpSigningMiddleware();
init_getHttpSigningMiddleware();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider2;
var init_normalizeProvider2 = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/normalizeProvider.js"() {
init_import_meta_url();
normalizeProvider2 = /* @__PURE__ */ __name((input) => {
if (typeof input === "function")
return input;
const promisified = Promise.resolve(input);
return () => promisified;
}, "normalizeProvider");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/pagination/createPaginator.js
function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) {
let token = config.startingToken || void 0;
let hasNext = true;
let page;
while (hasNext) {
input[inputTokenName] = token;
if (pageSizeTokenName) {
input[pageSizeTokenName] = input[pageSizeTokenName] ?? config.pageSize;
}
if (config.client instanceof ClientCtor) {
page = await makePagedClientRequest(CommandCtor, config.client, input, ...additionalArguments);
} else {
throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
}
yield page;
const prevToken = token;
token = get(page, outputTokenName);
hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
}
return void 0;
}, "paginateOperation");
}
var makePagedClientRequest, get;
var init_createPaginator = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() {
init_import_meta_url();
makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, ...args) => {
return await client.send(new CommandCtor(input), ...args);
}, "makePagedClientRequest");
__name(createPaginator, "createPaginator");
get = /* @__PURE__ */ __name((fromObject, path72) => {
let cursor = fromObject;
const pathComponents = path72.split(".");
for (const step of pathComponents) {
if (!cursor || typeof cursor !== "object") {
return void 0;
}
cursor = cursor[step];
}
return cursor;
}, "get");
}
});
// ../../node_modules/.pnpm/@smithy+is-array-buffer@3.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js
var isArrayBuffer;
var init_dist_es6 = __esm({
"../../node_modules/.pnpm/@smithy+is-array-buffer@3.0.0/node_modules/@smithy/is-array-buffer/dist-es/index.js"() {
init_import_meta_url();
isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer");
}
});
// ../../node_modules/.pnpm/@smithy+util-buffer-from@3.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js
var import_buffer, fromArrayBuffer, fromString;
var init_dist_es7 = __esm({
"../../node_modules/.pnpm/@smithy+util-buffer-from@3.0.0/node_modules/@smithy/util-buffer-from/dist-es/index.js"() {
init_import_meta_url();
init_dist_es6();
import_buffer = require("buffer");
fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => {
if (!isArrayBuffer(input)) {
throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
}
return import_buffer.Buffer.from(input, offset, length);
}, "fromArrayBuffer");
fromString = /* @__PURE__ */ __name((input, encoding) => {
if (typeof input !== "string") {
throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
}
return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input);
}, "fromString");
}
});
// ../../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js
var BASE64_REGEX, fromBase64;
var init_fromBase64 = __esm({
"../../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-es/fromBase64.js"() {
init_import_meta_url();
init_dist_es7();
BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
fromBase64 = /* @__PURE__ */ __name((input) => {
if (input.length * 3 % 4 !== 0) {
throw new TypeError(`Incorrect padding on base64 string.`);
}
if (!BASE64_REGEX.exec(input)) {
throw new TypeError(`Invalid base64 string.`);
}
const buffer = fromString(input, "base64");
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}, "fromBase64");
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
var fromUtf8;
var init_fromUtf8 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"() {
init_import_meta_url();
init_dist_es7();
fromUtf8 = /* @__PURE__ */ __name((input) => {
const buf = fromString(input, "utf8");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}, "fromUtf8");
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var toUint8Array;
var init_toUint8Array = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
init_import_meta_url();
init_fromUtf8();
toUint8Array = /* @__PURE__ */ __name((data) => {
if (typeof data === "string") {
return fromUtf8(data);
}
if (ArrayBuffer.isView(data)) {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}
return new Uint8Array(data);
}, "toUint8Array");
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
var toUtf8;
var init_toUtf8 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js"() {
init_import_meta_url();
init_dist_es7();
toUtf8 = /* @__PURE__ */ __name((input) => {
if (typeof input === "string") {
return input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
}
return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
}, "toUtf8");
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es8 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-es/index.js"() {
init_import_meta_url();
init_fromUtf8();
init_toUint8Array();
init_toUtf8();
}
});
// ../../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js
var toBase64;
var init_toBase64 = __esm({
"../../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-es/toBase64.js"() {
init_import_meta_url();
init_dist_es7();
init_dist_es8();
toBase64 = /* @__PURE__ */ __name((_input) => {
let input;
if (typeof _input === "string") {
input = fromUtf8(_input);
} else {
input = _input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
}
return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64");
}, "toBase64");
}
});
// ../../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-es/index.js
var init_dist_es9 = __esm({
"../../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-es/index.js"() {
init_import_meta_url();
init_fromBase64();
init_toBase64();
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/blob/transforms.js
function transformToString(payload, encoding = "utf-8") {
if (encoding === "base64") {
return toBase64(payload);
}
return toUtf8(payload);
}
function transformFromString(str, encoding) {
if (encoding === "base64") {
return Uint8ArrayBlobAdapter.mutate(fromBase64(str));
}
return Uint8ArrayBlobAdapter.mutate(fromUtf8(str));
}
var init_transforms = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/blob/transforms.js"() {
init_import_meta_url();
init_dist_es9();
init_dist_es8();
init_Uint8ArrayBlobAdapter();
__name(transformToString, "transformToString");
__name(transformFromString, "transformFromString");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js
var Uint8ArrayBlobAdapter;
var init_Uint8ArrayBlobAdapter = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js"() {
init_import_meta_url();
init_transforms();
Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array {
static {
__name(this, "Uint8ArrayBlobAdapter");
}
static fromString(source, encoding = "utf-8") {
switch (typeof source) {
case "string":
return transformFromString(source, encoding);
default:
throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
}
}
static mutate(source) {
Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype);
return source;
}
transformToString(encoding = "utf-8") {
return transformToString(this, encoding);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js
var import_stream4, getAwsChunkedEncodingStream;
var init_getAwsChunkedEncodingStream = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js"() {
init_import_meta_url();
import_stream4 = require("stream");
getAwsChunkedEncodingStream = /* @__PURE__ */ __name((readableStream, options) => {
const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options;
const checksumRequired = base64Encoder !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0;
const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : void 0;
const awsChunkedEncodingStream = new import_stream4.Readable({ read: /* @__PURE__ */ __name(() => {
}, "read") });
readableStream.on("data", (data) => {
const length = bodyLengthChecker(data) || 0;
awsChunkedEncodingStream.push(`${length.toString(16)}\r
`);
awsChunkedEncodingStream.push(data);
awsChunkedEncodingStream.push("\r\n");
});
readableStream.on("end", async () => {
awsChunkedEncodingStream.push(`0\r
`);
if (checksumRequired) {
const checksum = base64Encoder(await digest);
awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r
`);
awsChunkedEncodingStream.push(`\r
`);
}
awsChunkedEncodingStream.push(null);
});
return awsChunkedEncodingStream;
}, "getAwsChunkedEncodingStream");
}
});
// ../../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js
var escapeUri, hexEncode;
var init_escape_uri = __esm({
"../../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"() {
init_import_meta_url();
escapeUri = /* @__PURE__ */ __name((uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode), "escapeUri");
hexEncode = /* @__PURE__ */ __name((c6) => `%${c6.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode");
}
});
// ../../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js
var init_escape_uri_path = __esm({
"../../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js"() {
init_import_meta_url();
init_escape_uri();
}
});
// ../../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js
var init_dist_es10 = __esm({
"../../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-es/index.js"() {
init_import_meta_url();
init_escape_uri();
init_escape_uri_path();
}
});
// ../../node_modules/.pnpm/@smithy+querystring-builder@3.0.11/node_modules/@smithy/querystring-builder/dist-es/index.js
function buildQueryString(query) {
const parts = [];
for (let key of Object.keys(query).sort()) {
const value = query[key];
key = escapeUri(key);
if (Array.isArray(value)) {
for (let i5 = 0, iLen = value.length; i5 < iLen; i5++) {
parts.push(`${key}=${escapeUri(value[i5])}`);
}
} else {
let qsEntry = key;
if (value || typeof value === "string") {
qsEntry += `=${escapeUri(value)}`;
}
parts.push(qsEntry);
}
}
return parts.join("&");
}
var init_dist_es11 = __esm({
"../../node_modules/.pnpm/@smithy+querystring-builder@3.0.11/node_modules/@smithy/querystring-builder/dist-es/index.js"() {
init_import_meta_url();
init_dist_es10();
__name(buildQueryString, "buildQueryString");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/constants.js
var NODEJS_TIMEOUT_ERROR_CODES;
var init_constants7 = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/constants.js"() {
init_import_meta_url();
NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js
var getTransformedHeaders;
var init_get_transformed_headers = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js"() {
init_import_meta_url();
getTransformedHeaders = /* @__PURE__ */ __name((headers) => {
const transformedHeaders = {};
for (const name2 of Object.keys(headers)) {
const headerValues = headers[name2];
transformedHeaders[name2] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
}
return transformedHeaders;
}, "getTransformedHeaders");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/timing.js
var timing;
var init_timing = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/timing.js"() {
init_import_meta_url();
timing = {
setTimeout: /* @__PURE__ */ __name((cb2, ms) => setTimeout(cb2, ms), "setTimeout"),
clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout")
};
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js
var DEFER_EVENT_LISTENER_TIME, setConnectionTimeout;
var init_set_connection_timeout = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js"() {
init_import_meta_url();
init_timing();
DEFER_EVENT_LISTENER_TIME = 1e3;
setConnectionTimeout = /* @__PURE__ */ __name((request4, reject, timeoutInMs = 0) => {
if (!timeoutInMs) {
return -1;
}
const registerTimeout = /* @__PURE__ */ __name((offset) => {
const timeoutId = timing.setTimeout(() => {
request4.destroy();
reject(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
name: "TimeoutError"
}));
}, timeoutInMs - offset);
const doWithSocket = /* @__PURE__ */ __name((socket) => {
if (socket?.connecting) {
socket.on("connect", () => {
timing.clearTimeout(timeoutId);
});
} else {
timing.clearTimeout(timeoutId);
}
}, "doWithSocket");
if (request4.socket) {
doWithSocket(request4.socket);
} else {
request4.on("socket", doWithSocket);
}
}, "registerTimeout");
if (timeoutInMs < 2e3) {
registerTimeout(0);
return 0;
}
return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
}, "setConnectionTimeout");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js
var DEFER_EVENT_LISTENER_TIME2, setSocketKeepAlive;
var init_set_socket_keep_alive = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js"() {
init_import_meta_url();
init_timing();
DEFER_EVENT_LISTENER_TIME2 = 3e3;
setSocketKeepAlive = /* @__PURE__ */ __name((request4, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => {
if (keepAlive !== true) {
return -1;
}
const registerListener = /* @__PURE__ */ __name(() => {
if (request4.socket) {
request4.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
} else {
request4.on("socket", (socket) => {
socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
});
}
}, "registerListener");
if (deferTimeMs === 0) {
registerListener();
return 0;
}
return timing.setTimeout(registerListener, deferTimeMs);
}, "setSocketKeepAlive");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js
var DEFER_EVENT_LISTENER_TIME3, setSocketTimeout;
var init_set_socket_timeout = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js"() {
init_import_meta_url();
init_timing();
DEFER_EVENT_LISTENER_TIME3 = 3e3;
setSocketTimeout = /* @__PURE__ */ __name((request4, reject, timeoutInMs = 0) => {
const registerTimeout = /* @__PURE__ */ __name((offset) => {
const timeout2 = timeoutInMs - offset;
const onTimeout = /* @__PURE__ */ __name(() => {
request4.destroy();
reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
}, "onTimeout");
if (request4.socket) {
request4.socket.setTimeout(timeout2, onTimeout);
} else {
request4.setTimeout(timeout2, onTimeout);
}
}, "registerTimeout");
if (0 < timeoutInMs && timeoutInMs < 6e3) {
registerTimeout(0);
return 0;
}
return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3);
}, "setSocketTimeout");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js
async function writeRequestBody(httpRequest2, request4, maxContinueTimeoutMs = MIN_WAIT_TIME) {
const headers = request4.headers ?? {};
const expect = headers["Expect"] || headers["expect"];
let timeoutId = -1;
let sendBody = true;
if (expect === "100-continue") {
sendBody = await Promise.race([
new Promise((resolve25) => {
timeoutId = Number(timing.setTimeout(resolve25, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
}),
new Promise((resolve25) => {
httpRequest2.on("continue", () => {
timing.clearTimeout(timeoutId);
resolve25(true);
});
httpRequest2.on("response", () => {
timing.clearTimeout(timeoutId);
resolve25(false);
});
httpRequest2.on("error", () => {
timing.clearTimeout(timeoutId);
resolve25(false);
});
})
]);
}
if (sendBody) {
writeBody(httpRequest2, request4.body);
}
}
function writeBody(httpRequest2, body) {
if (body instanceof import_stream5.Readable) {
body.pipe(httpRequest2);
return;
}
if (body) {
if (Buffer.isBuffer(body) || typeof body === "string") {
httpRequest2.end(body);
return;
}
const uint8 = body;
if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
return;
}
httpRequest2.end(Buffer.from(body));
return;
}
httpRequest2.end();
}
var import_stream5, MIN_WAIT_TIME;
var init_write_request_body = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/write-request-body.js"() {
init_import_meta_url();
import_stream5 = require("stream");
init_timing();
MIN_WAIT_TIME = 1e3;
__name(writeRequestBody, "writeRequestBody");
__name(writeBody, "writeBody");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js
var import_http, import_https, NodeHttpHandler;
var init_node_http_handler = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es11();
import_http = require("http");
import_https = require("https");
init_constants7();
init_get_transformed_headers();
init_set_connection_timeout();
init_set_socket_keep_alive();
init_set_socket_timeout();
init_timing();
init_write_request_body();
NodeHttpHandler = class _NodeHttpHandler {
static {
__name(this, "NodeHttpHandler");
}
static create(instanceOrOptions) {
if (typeof instanceOrOptions?.handle === "function") {
return instanceOrOptions;
}
return new _NodeHttpHandler(instanceOrOptions);
}
static checkSocketUsage(agent, socketWarningTimestamp, logger4 = console) {
const { sockets, requests, maxSockets } = agent;
if (typeof maxSockets !== "number" || maxSockets === Infinity) {
return socketWarningTimestamp;
}
const interval = 15e3;
if (Date.now() - interval < socketWarningTimestamp) {
return socketWarningTimestamp;
}
if (sockets && requests) {
for (const origin in sockets) {
const socketsInUse = sockets[origin]?.length ?? 0;
const requestsEnqueued = requests[origin]?.length ?? 0;
if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
logger4?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);
return Date.now();
}
}
}
return socketWarningTimestamp;
}
constructor(options) {
this.socketWarningTimestamp = 0;
this.metadata = { handlerProtocol: "http/1.1" };
this.configProvider = new Promise((resolve25, reject) => {
if (typeof options === "function") {
options().then((_options) => {
resolve25(this.resolveDefaultConfig(_options));
}).catch(reject);
} else {
resolve25(this.resolveDefaultConfig(options));
}
});
}
resolveDefaultConfig(options) {
const { requestTimeout: requestTimeout2, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {};
const keepAlive = true;
const maxSockets = 50;
return {
connectionTimeout,
requestTimeout: requestTimeout2 ?? socketTimeout,
httpAgent: (() => {
if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") {
return httpAgent;
}
return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent });
})(),
httpsAgent: (() => {
if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") {
return httpsAgent;
}
return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
})(),
logger: console
};
}
destroy() {
this.config?.httpAgent?.destroy();
this.config?.httpsAgent?.destroy();
}
async handle(request4, { abortSignal } = {}) {
if (!this.config) {
this.config = await this.configProvider;
}
return new Promise((_resolve, _reject) => {
let writeRequestBodyPromise = void 0;
const timeouts = [];
const resolve25 = /* @__PURE__ */ __name(async (arg) => {
await writeRequestBodyPromise;
timeouts.forEach(timing.clearTimeout);
_resolve(arg);
}, "resolve");
const reject = /* @__PURE__ */ __name(async (arg) => {
await writeRequestBodyPromise;
timeouts.forEach(timing.clearTimeout);
_reject(arg);
}, "reject");
if (!this.config) {
throw new Error("Node HTTP request handler config is not resolved");
}
if (abortSignal?.aborted) {
const abortError = new Error("Request aborted");
abortError.name = "AbortError";
reject(abortError);
return;
}
const isSSL = request4.protocol === "https:";
const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
timeouts.push(timing.setTimeout(() => {
this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, this.config.logger);
}, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)));
const queryString = buildQueryString(request4.query || {});
let auth = void 0;
if (request4.username != null || request4.password != null) {
const username = request4.username ?? "";
const password = request4.password ?? "";
auth = `${username}:${password}`;
}
let path72 = request4.path;
if (queryString) {
path72 += `?${queryString}`;
}
if (request4.fragment) {
path72 += `#${request4.fragment}`;
}
let hostname2 = request4.hostname ?? "";
if (hostname2[0] === "[" && hostname2.endsWith("]")) {
hostname2 = request4.hostname.slice(1, -1);
} else {
hostname2 = request4.hostname;
}
const nodeHttpsOptions = {
headers: request4.headers,
host: hostname2,
method: request4.method,
path: path72,
port: request4.port,
agent,
auth
};
const requestFunc = isSSL ? import_https.request : import_http.request;
const req = requestFunc(nodeHttpsOptions, (res) => {
const httpResponse = new HttpResponse({
statusCode: res.statusCode || -1,
reason: res.statusMessage,
headers: getTransformedHeaders(res.headers),
body: res
});
resolve25({ response: httpResponse });
});
req.on("error", (err) => {
if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {
reject(Object.assign(err, { name: "TimeoutError" }));
} else {
reject(err);
}
});
if (abortSignal) {
const onAbort = /* @__PURE__ */ __name(() => {
req.destroy();
const abortError = new Error("Request aborted");
abortError.name = "AbortError";
reject(abortError);
}, "onAbort");
if (typeof abortSignal.addEventListener === "function") {
const signal = abortSignal;
signal.addEventListener("abort", onAbort, { once: true });
req.once("close", () => signal.removeEventListener("abort", onAbort));
} else {
abortSignal.onabort = onAbort;
}
}
timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout));
timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout));
const httpAgent = nodeHttpsOptions.agent;
if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
timeouts.push(setSocketKeepAlive(req, {
keepAlive: httpAgent.keepAlive,
keepAliveMsecs: httpAgent.keepAliveMsecs
}));
}
writeRequestBodyPromise = writeRequestBody(req, request4, this.config.requestTimeout).catch((e7) => {
timeouts.forEach(timing.clearTimeout);
return _reject(e7);
});
});
}
updateHttpClientConfig(key, value) {
this.config = void 0;
this.configProvider = this.configProvider.then((config) => {
return {
...config,
[key]: value
};
});
}
httpHandlerConfigs() {
return this.config ?? {};
}
};
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js
var init_node_http2_connection_pool = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js
var init_node_http2_connection_manager = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js"() {
init_import_meta_url();
init_node_http2_connection_pool();
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js
var init_node_http2_handler = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es11();
init_get_transformed_headers();
init_node_http2_connection_manager();
init_write_request_body();
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js
var import_stream6, Collector;
var init_collector = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js"() {
init_import_meta_url();
import_stream6 = require("stream");
Collector = class extends import_stream6.Writable {
static {
__name(this, "Collector");
}
constructor() {
super(...arguments);
this.bufferedBytes = [];
}
_write(chunk, encoding, callback) {
this.bufferedBytes.push(chunk);
callback();
}
};
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js
async function collectReadableStream(stream2) {
const chunks = [];
const reader = stream2.getReader();
let isDone = false;
let length = 0;
while (!isDone) {
const { done, value } = await reader.read();
if (value) {
chunks.push(value);
length += value.length;
}
isDone = done;
}
const collected = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
collected.set(chunk, offset);
offset += chunk.length;
}
return collected;
}
var streamCollector, isReadableStreamInstance;
var init_stream_collector = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"() {
init_import_meta_url();
init_collector();
streamCollector = /* @__PURE__ */ __name((stream2) => {
if (isReadableStreamInstance(stream2)) {
return collectReadableStream(stream2);
}
return new Promise((resolve25, reject) => {
const collector = new Collector();
stream2.pipe(collector);
stream2.on("error", (err) => {
collector.end();
reject(err);
});
collector.on("error", reject);
collector.on("finish", function() {
const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
resolve25(bytes);
});
});
}, "streamCollector");
isReadableStreamInstance = /* @__PURE__ */ __name((stream2) => typeof ReadableStream === "function" && stream2 instanceof ReadableStream, "isReadableStreamInstance");
__name(collectReadableStream, "collectReadableStream");
}
});
// ../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/index.js
var init_dist_es12 = __esm({
"../../node_modules/.pnpm/@smithy+node-http-handler@3.3.3/node_modules/@smithy/node-http-handler/dist-es/index.js"() {
init_import_meta_url();
init_node_http_handler();
init_node_http2_handler();
init_stream_collector();
}
});
// ../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js
var init_create_request = __esm({
"../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js
var init_request_timeout = __esm({
"../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js
var init_fetch_http_handler = __esm({
"../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es11();
init_create_request();
init_request_timeout();
}
});
// ../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js
async function collectBlob(blob) {
const base642 = await readToBase64(blob);
const arrayBuffer2 = fromBase64(base642);
return new Uint8Array(arrayBuffer2);
}
async function collectStream(stream2) {
const chunks = [];
const reader = stream2.getReader();
let isDone = false;
let length = 0;
while (!isDone) {
const { done, value } = await reader.read();
if (value) {
chunks.push(value);
length += value.length;
}
isDone = done;
}
const collected = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
collected.set(chunk, offset);
offset += chunk.length;
}
return collected;
}
function readToBase64(blob) {
return new Promise((resolve25, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
if (reader.readyState !== 2) {
return reject(new Error("Reader aborted too early"));
}
const result = reader.result ?? "";
const commaIndex = result.indexOf(",");
const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
resolve25(result.substring(dataOffset));
};
reader.onabort = () => reject(new Error("Read aborted"));
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
}
var streamCollector2;
var init_stream_collector2 = __esm({
"../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() {
init_import_meta_url();
init_dist_es9();
streamCollector2 = /* @__PURE__ */ __name(async (stream2) => {
if (typeof Blob === "function" && stream2 instanceof Blob || stream2.constructor?.name === "Blob") {
if (Blob.prototype.arrayBuffer !== void 0) {
return new Uint8Array(await stream2.arrayBuffer());
}
return collectBlob(stream2);
}
return collectStream(stream2);
}, "streamCollector");
__name(collectBlob, "collectBlob");
__name(collectStream, "collectStream");
__name(readToBase64, "readToBase64");
}
});
// ../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/index.js
var init_dist_es13 = __esm({
"../../node_modules/.pnpm/@smithy+fetch-http-handler@4.1.3/node_modules/@smithy/fetch-http-handler/dist-es/index.js"() {
init_import_meta_url();
init_fetch_http_handler();
init_stream_collector2();
}
});
// ../../node_modules/.pnpm/@smithy+util-hex-encoding@3.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js
function fromHex(encoded) {
if (encoded.length % 2 !== 0) {
throw new Error("Hex encoded strings must have an even number length");
}
const out = new Uint8Array(encoded.length / 2);
for (let i5 = 0; i5 < encoded.length; i5 += 2) {
const encodedByte = encoded.slice(i5, i5 + 2).toLowerCase();
if (encodedByte in HEX_TO_SHORT) {
out[i5 / 2] = HEX_TO_SHORT[encodedByte];
} else {
throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
}
}
return out;
}
function toHex(bytes) {
let out = "";
for (let i5 = 0; i5 < bytes.byteLength; i5++) {
out += SHORT_TO_HEX[bytes[i5]];
}
return out;
}
var SHORT_TO_HEX, HEX_TO_SHORT;
var init_dist_es14 = __esm({
"../../node_modules/.pnpm/@smithy+util-hex-encoding@3.0.0/node_modules/@smithy/util-hex-encoding/dist-es/index.js"() {
init_import_meta_url();
SHORT_TO_HEX = {};
HEX_TO_SHORT = {};
for (let i5 = 0; i5 < 256; i5++) {
let encodedByte = i5.toString(16).toLowerCase();
if (encodedByte.length === 1) {
encodedByte = `0${encodedByte}`;
}
SHORT_TO_HEX[i5] = encodedByte;
HEX_TO_SHORT[encodedByte] = i5;
}
__name(fromHex, "fromHex");
__name(toHex, "toHex");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/stream-type-check.js
var isReadableStream, isBlob2;
var init_stream_type_check = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() {
init_import_meta_url();
isReadableStream = /* @__PURE__ */ __name((stream2) => typeof ReadableStream === "function" && (stream2?.constructor?.name === ReadableStream.name || stream2 instanceof ReadableStream), "isReadableStream");
isBlob2 = /* @__PURE__ */ __name((blob) => {
return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob);
}, "isBlob");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js
var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED, sdkStreamMixin, isBlobInstance;
var init_sdk_stream_mixin_browser = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js"() {
init_import_meta_url();
init_dist_es13();
init_dist_es9();
init_dist_es14();
init_dist_es8();
init_stream_type_check();
ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
sdkStreamMixin = /* @__PURE__ */ __name((stream2) => {
if (!isBlobInstance(stream2) && !isReadableStream(stream2)) {
const name2 = stream2?.__proto__?.constructor?.name || stream2;
throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name2}`);
}
let transformed = false;
const transformToByteArray = /* @__PURE__ */ __name(async () => {
if (transformed) {
throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
}
transformed = true;
return await streamCollector2(stream2);
}, "transformToByteArray");
const blobToWebStream = /* @__PURE__ */ __name((blob) => {
if (typeof blob.stream !== "function") {
throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
}
return blob.stream();
}, "blobToWebStream");
return Object.assign(stream2, {
transformToByteArray,
transformToString: /* @__PURE__ */ __name(async (encoding) => {
const buf = await transformToByteArray();
if (encoding === "base64") {
return toBase64(buf);
} else if (encoding === "hex") {
return toHex(buf);
} else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
return toUtf8(buf);
} else if (typeof TextDecoder === "function") {
return new TextDecoder(encoding).decode(buf);
} else {
throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
}
}, "transformToString"),
transformToWebStream: /* @__PURE__ */ __name(() => {
if (transformed) {
throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
}
transformed = true;
if (isBlobInstance(stream2)) {
return blobToWebStream(stream2);
} else if (isReadableStream(stream2)) {
return stream2;
} else {
throw new Error(`Cannot transform payload to web stream, got ${stream2}`);
}
}, "transformToWebStream")
});
}, "sdkStreamMixin");
isBlobInstance = /* @__PURE__ */ __name((stream2) => typeof Blob === "function" && stream2 instanceof Blob, "isBlobInstance");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js
var import_stream7, ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2, sdkStreamMixin2;
var init_sdk_stream_mixin = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js"() {
init_import_meta_url();
init_dist_es12();
init_dist_es7();
import_stream7 = require("stream");
init_sdk_stream_mixin_browser();
ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2 = "The stream has already been transformed.";
sdkStreamMixin2 = /* @__PURE__ */ __name((stream2) => {
if (!(stream2 instanceof import_stream7.Readable)) {
try {
return sdkStreamMixin(stream2);
} catch (e7) {
const name2 = stream2?.__proto__?.constructor?.name || stream2;
throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name2}`);
}
}
let transformed = false;
const transformToByteArray = /* @__PURE__ */ __name(async () => {
if (transformed) {
throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);
}
transformed = true;
return await streamCollector(stream2);
}, "transformToByteArray");
return Object.assign(stream2, {
transformToByteArray,
transformToString: /* @__PURE__ */ __name(async (encoding) => {
const buf = await transformToByteArray();
if (encoding === void 0 || Buffer.isEncoding(encoding)) {
return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
} else {
const decoder = new TextDecoder(encoding);
return decoder.decode(buf);
}
}, "transformToString"),
transformToWebStream: /* @__PURE__ */ __name(() => {
if (transformed) {
throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);
}
if (stream2.readableFlowing !== null) {
throw new Error("The stream has been consumed by other callbacks.");
}
if (typeof import_stream7.Readable.toWeb !== "function") {
throw new Error("Readable.toWeb() is not supported. Please make sure you are using Node.js >= 17.0.0, or polyfill is available.");
}
transformed = true;
return import_stream7.Readable.toWeb(stream2);
}, "transformToWebStream")
});
}, "sdkStreamMixin");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js
async function splitStream(stream2) {
if (typeof stream2.stream === "function") {
stream2 = stream2.stream();
}
const readableStream = stream2;
return readableStream.tee();
}
var init_splitStream_browser = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js"() {
init_import_meta_url();
__name(splitStream, "splitStream");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/splitStream.js
async function splitStream2(stream2) {
if (isReadableStream(stream2) || isBlob2(stream2)) {
return splitStream(stream2);
}
const stream1 = new import_stream8.PassThrough();
const stream22 = new import_stream8.PassThrough();
stream2.pipe(stream1);
stream2.pipe(stream22);
return [stream1, stream22];
}
var import_stream8;
var init_splitStream = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/splitStream.js"() {
init_import_meta_url();
import_stream8 = require("stream");
init_splitStream_browser();
init_stream_type_check();
__name(splitStream2, "splitStream");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/headStream.browser.js
async function headStream(stream2, bytes) {
let byteLengthCounter = 0;
const chunks = [];
const reader = stream2.getReader();
let isDone = false;
while (!isDone) {
const { done, value } = await reader.read();
if (value) {
chunks.push(value);
byteLengthCounter += value?.byteLength ?? 0;
}
if (byteLengthCounter >= bytes) {
break;
}
isDone = done;
}
reader.releaseLock();
const collected = new Uint8Array(Math.min(bytes, byteLengthCounter));
let offset = 0;
for (const chunk of chunks) {
if (chunk.byteLength > collected.byteLength - offset) {
collected.set(chunk.subarray(0, collected.byteLength - offset), offset);
break;
} else {
collected.set(chunk, offset);
}
offset += chunk.length;
}
return collected;
}
var init_headStream_browser = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/headStream.browser.js"() {
init_import_meta_url();
__name(headStream, "headStream");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/headStream.js
var import_stream9, headStream2, Collector2;
var init_headStream = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/headStream.js"() {
init_import_meta_url();
import_stream9 = require("stream");
init_headStream_browser();
init_stream_type_check();
headStream2 = /* @__PURE__ */ __name((stream2, bytes) => {
if (isReadableStream(stream2)) {
return headStream(stream2, bytes);
}
return new Promise((resolve25, reject) => {
const collector = new Collector2();
collector.limit = bytes;
stream2.pipe(collector);
stream2.on("error", (err) => {
collector.end();
reject(err);
});
collector.on("error", reject);
collector.on("finish", function() {
const bytes2 = new Uint8Array(Buffer.concat(this.buffers));
resolve25(bytes2);
});
});
}, "headStream");
Collector2 = class extends import_stream9.Writable {
static {
__name(this, "Collector");
}
constructor() {
super(...arguments);
this.buffers = [];
this.limit = Infinity;
this.bytesBuffered = 0;
}
_write(chunk, encoding, callback) {
this.buffers.push(chunk);
this.bytesBuffered += chunk.byteLength ?? 0;
if (this.bytesBuffered >= this.limit) {
const excess = this.bytesBuffered - this.limit;
const tailBuffer = this.buffers[this.buffers.length - 1];
this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess);
this.emit("finish");
}
callback();
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js
var import_stream10, ChecksumStream;
var init_ChecksumStream = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js"() {
init_import_meta_url();
init_dist_es9();
import_stream10 = require("stream");
ChecksumStream = class extends import_stream10.Duplex {
static {
__name(this, "ChecksumStream");
}
constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) {
super();
if (typeof source.pipe === "function") {
this.source = source;
} else {
throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);
}
this.base64Encoder = base64Encoder ?? toBase64;
this.expectedChecksum = expectedChecksum;
this.checksum = checksum;
this.checksumSourceLocation = checksumSourceLocation;
this.source.pipe(this);
}
_read(size) {
}
_write(chunk, encoding, callback) {
try {
this.checksum.update(chunk);
this.push(chunk);
} catch (e7) {
return callback(e7);
}
return callback();
}
async _final(callback) {
try {
const digest = await this.checksum.digest();
const received = this.base64Encoder(digest);
if (this.expectedChecksum !== received) {
return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}" in response header "${this.checksumSourceLocation}".`));
}
} catch (e7) {
return callback(e7);
}
this.push(null);
return callback();
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js
var ReadableStreamRef, ChecksumStream2;
var init_ChecksumStream_browser = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js"() {
init_import_meta_url();
ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() {
};
ChecksumStream2 = class extends ReadableStreamRef {
static {
__name(this, "ChecksumStream");
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js
var createChecksumStream;
var init_createChecksumStream_browser = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js"() {
init_import_meta_url();
init_dist_es9();
init_stream_type_check();
init_ChecksumStream_browser();
createChecksumStream = /* @__PURE__ */ __name(({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) => {
if (!isReadableStream(source)) {
throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);
}
const encoder = base64Encoder ?? toBase64;
if (typeof TransformStream !== "function") {
throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");
}
const transform = new TransformStream({
start() {
},
async transform(chunk, controller) {
checksum.update(chunk);
controller.enqueue(chunk);
},
async flush(controller) {
const digest = await checksum.digest();
const received = encoder(digest);
if (expectedChecksum !== received) {
const error2 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`);
controller.error(error2);
} else {
controller.terminate();
}
}
});
source.pipeThrough(transform);
const readable = transform.readable;
Object.setPrototypeOf(readable, ChecksumStream2.prototype);
return readable;
}, "createChecksumStream");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js
function createChecksumStream2(init3) {
if (typeof ReadableStream === "function" && isReadableStream(init3.source)) {
return createChecksumStream(init3);
}
return new ChecksumStream(init3);
}
var init_createChecksumStream = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js"() {
init_import_meta_url();
init_stream_type_check();
init_ChecksumStream();
init_createChecksumStream_browser();
__name(createChecksumStream2, "createChecksumStream");
}
});
// ../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/index.js
var init_dist_es15 = __esm({
"../../node_modules/.pnpm/@smithy+util-stream@3.3.4/node_modules/@smithy/util-stream/dist-es/index.js"() {
init_import_meta_url();
init_Uint8ArrayBlobAdapter();
init_getAwsChunkedEncodingStream();
init_sdk_stream_mixin();
init_splitStream();
init_headStream();
init_stream_type_check();
init_createChecksumStream();
init_ChecksumStream();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
var collectBody;
var init_collect_stream_body = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() {
init_import_meta_url();
init_dist_es15();
collectBody = /* @__PURE__ */ __name(async (streamBody = new Uint8Array(), context2) => {
if (streamBody instanceof Uint8Array) {
return Uint8ArrayBlobAdapter.mutate(streamBody);
}
if (!streamBody) {
return Uint8ArrayBlobAdapter.mutate(new Uint8Array());
}
const fromContext = context2.streamCollector(streamBody);
return Uint8ArrayBlobAdapter.mutate(await fromContext);
}, "collectBody");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
function extendedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c6) {
return "%" + c6.charCodeAt(0).toString(16).toUpperCase();
});
}
var init_extended_encode_uri_component = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() {
init_import_meta_url();
__name(extendedEncodeURIComponent, "extendedEncodeURIComponent");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
var resolvedPath;
var init_resolve_path = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() {
init_import_meta_url();
init_extended_encode_uri_component();
resolvedPath = /* @__PURE__ */ __name((resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
if (input != null && input[memberName] !== void 0) {
const labelValue = labelValueProvider();
if (labelValue.length <= 0) {
throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
}
resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue));
} else {
throw new Error("No value provided for input HTTP label: " + memberName + ".");
}
return resolvedPath2;
}, "resolvedPath");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
function requestBuilder(input, context2) {
return new RequestBuilder(input, context2);
}
var RequestBuilder;
var init_requestBuilder = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() {
init_import_meta_url();
init_dist_es2();
init_resolve_path();
__name(requestBuilder, "requestBuilder");
RequestBuilder = class {
static {
__name(this, "RequestBuilder");
}
constructor(input, context2) {
this.input = input;
this.context = context2;
this.query = {};
this.method = "";
this.headers = {};
this.path = "";
this.body = null;
this.hostname = "";
this.resolvePathStack = [];
}
async build() {
const { hostname: hostname2, protocol = "https", port, path: basePath } = await this.context.endpoint();
this.path = basePath;
for (const resolvePath3 of this.resolvePathStack) {
resolvePath3(this.path);
}
return new HttpRequest({
protocol,
hostname: this.hostname || hostname2,
port,
method: this.method,
path: this.path,
query: this.query,
body: this.body,
headers: this.headers
});
}
hn(hostname2) {
this.hostname = hostname2;
return this;
}
bp(uriLabel) {
this.resolvePathStack.push((basePath) => {
this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
});
return this;
}
p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
this.resolvePathStack.push((path72) => {
this.path = resolvedPath(path72, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
});
return this;
}
h(headers) {
this.headers = headers;
return this;
}
q(query) {
this.query = query;
return this;
}
b(body) {
this.body = body;
return this;
}
m(method) {
this.method = method;
return this;
}
};
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
var init_protocols = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() {
init_import_meta_url();
init_collect_stream_body();
init_extended_encode_uri_component();
init_requestBuilder();
init_resolve_path();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
var init_requestBuilder2 = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
init_import_meta_url();
init_protocols();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/setFeature.js
function setFeature2(context2, feature, value) {
if (!context2.__smithy_context) {
context2.__smithy_context = {
features: {}
};
} else if (!context2.__smithy_context.features) {
context2.__smithy_context.features = {};
}
context2.__smithy_context.features[feature] = value;
}
var init_setFeature2 = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/setFeature.js"() {
init_import_meta_url();
__name(setFeature2, "setFeature");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var DefaultIdentityProviderConfig;
var init_DefaultIdentityProviderConfig = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() {
init_import_meta_url();
DefaultIdentityProviderConfig = class {
static {
__name(this, "DefaultIdentityProviderConfig");
}
constructor(config) {
this.authSchemes = /* @__PURE__ */ new Map();
for (const [key, value] of Object.entries(config)) {
if (value !== void 0) {
this.authSchemes.set(key, value);
}
}
}
getIdentityProvider(schemeId) {
return this.authSchemes.get(schemeId);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var init_httpApiKeyAuth = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var init_httpBearerAuth = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() {
init_import_meta_url();
init_dist_es2();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var NoAuthSigner;
var init_noAuth = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() {
init_import_meta_url();
NoAuthSigner = class {
static {
__name(this, "NoAuthSigner");
}
async sign(httpRequest2, identity, signingProperties) {
return httpRequest2;
}
};
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() {
init_import_meta_url();
init_httpApiKeyAuth();
init_httpBearerAuth();
init_noAuth();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
var init_memoizeIdentityProvider = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() {
init_import_meta_url();
createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction");
EXPIRATION_MS = 3e5;
isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh");
memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => {
if (provider === void 0) {
return void 0;
}
const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
let resolved;
let pending;
let hasResult;
let isConstant = false;
const coalesceProvider = /* @__PURE__ */ __name(async (options) => {
if (!pending) {
pending = normalizedProvider(options);
}
try {
resolved = await pending;
hasResult = true;
isConstant = false;
} finally {
pending = void 0;
}
return resolved;
}, "coalesceProvider");
if (isExpired === void 0) {
return async (options) => {
if (!hasResult || options?.forceRefresh) {
resolved = await coalesceProvider(options);
}
return resolved;
};
}
return async (options) => {
if (!hasResult || options?.forceRefresh) {
resolved = await coalesceProvider(options);
}
if (isConstant) {
return resolved;
}
if (!requiresRefresh(resolved)) {
isConstant = true;
return resolved;
}
if (isExpired(resolved)) {
await coalesceProvider(options);
return resolved;
}
return resolved;
};
}, "memoizeIdentityProvider");
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() {
init_import_meta_url();
init_DefaultIdentityProviderConfig();
init_httpAuthSchemes();
init_memoizeIdentityProvider();
}
});
// ../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/index.js
var init_dist_es16 = __esm({
"../../node_modules/.pnpm/@smithy+core@2.5.7/node_modules/@smithy/core/dist-es/index.js"() {
init_import_meta_url();
init_getSmithyContext();
init_middleware_http_auth_scheme();
init_middleware_http_signing();
init_normalizeProvider2();
init_createPaginator();
init_requestBuilder2();
init_setFeature2();
init_util_identity_and_auth();
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/ProviderError.js
var ProviderError;
var init_ProviderError = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/ProviderError.js"() {
init_import_meta_url();
ProviderError = class _ProviderError extends Error {
static {
__name(this, "ProviderError");
}
constructor(message, options = true) {
let logger4;
let tryNextLink = true;
if (typeof options === "boolean") {
logger4 = void 0;
tryNextLink = options;
} else if (options != null && typeof options === "object") {
logger4 = options.logger;
tryNextLink = options.tryNextLink ?? true;
}
super(message);
this.name = "ProviderError";
this.tryNextLink = tryNextLink;
Object.setPrototypeOf(this, _ProviderError.prototype);
logger4?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
}
static from(error2, options = true) {
return Object.assign(new this(error2.message, options), error2);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js
var CredentialsProviderError;
var init_CredentialsProviderError = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js"() {
init_import_meta_url();
init_ProviderError();
CredentialsProviderError = class _CredentialsProviderError extends ProviderError {
static {
__name(this, "CredentialsProviderError");
}
constructor(message, options = true) {
super(message, options);
this.name = "CredentialsProviderError";
Object.setPrototypeOf(this, _CredentialsProviderError.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js
var TokenProviderError;
var init_TokenProviderError = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/TokenProviderError.js"() {
init_import_meta_url();
init_ProviderError();
TokenProviderError = class _TokenProviderError extends ProviderError {
static {
__name(this, "TokenProviderError");
}
constructor(message, options = true) {
super(message, options);
this.name = "TokenProviderError";
Object.setPrototypeOf(this, _TokenProviderError.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/chain.js
var chain;
var init_chain = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/chain.js"() {
init_import_meta_url();
init_ProviderError();
chain = /* @__PURE__ */ __name((...providers) => async () => {
if (providers.length === 0) {
throw new ProviderError("No providers in chain");
}
let lastProviderError;
for (const provider of providers) {
try {
const credentials = await provider();
return credentials;
} catch (err) {
lastProviderError = err;
if (err?.tryNextLink) {
continue;
}
throw err;
}
}
throw lastProviderError;
}, "chain");
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/fromStatic.js
var fromStatic;
var init_fromStatic = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/fromStatic.js"() {
init_import_meta_url();
fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic");
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/memoize.js
var memoize;
var init_memoize = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/memoize.js"() {
init_import_meta_url();
memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => {
let resolved;
let pending;
let hasResult;
let isConstant = false;
const coalesceProvider = /* @__PURE__ */ __name(async () => {
if (!pending) {
pending = provider();
}
try {
resolved = await pending;
hasResult = true;
isConstant = false;
} finally {
pending = void 0;
}
return resolved;
}, "coalesceProvider");
if (isExpired === void 0) {
return async (options) => {
if (!hasResult || options?.forceRefresh) {
resolved = await coalesceProvider();
}
return resolved;
};
}
return async (options) => {
if (!hasResult || options?.forceRefresh) {
resolved = await coalesceProvider();
}
if (isConstant) {
return resolved;
}
if (requiresRefresh && !requiresRefresh(resolved)) {
isConstant = true;
return resolved;
}
if (isExpired(resolved)) {
await coalesceProvider();
return resolved;
}
return resolved;
};
}, "memoize");
}
});
// ../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/index.js
var init_dist_es17 = __esm({
"../../node_modules/.pnpm/@smithy+property-provider@3.1.11/node_modules/@smithy/property-provider/dist-es/index.js"() {
init_import_meta_url();
init_CredentialsProviderError();
init_ProviderError();
init_TokenProviderError();
init_chain();
init_fromStatic();
init_memoize();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
var resolveAwsSdkSigV4AConfig, NODE_SIGV4A_CONFIG_OPTIONS;
var init_resolveAwsSdkSigV4AConfig = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() {
init_import_meta_url();
init_dist_es16();
init_dist_es17();
resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => {
config.sigv4aSigningRegionSet = normalizeProvider2(config.sigv4aSigningRegionSet);
return config;
}, "resolveAwsSdkSigV4AConfig");
NODE_SIGV4A_CONFIG_OPTIONS = {
environmentVariableSelector(env6) {
if (env6.AWS_SIGV4A_SIGNING_REGION_SET) {
return env6.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_4) => _4.trim());
}
throw new ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", {
tryNextLink: true
});
},
configFileSelector(profile) {
if (profile.sigv4a_signing_region_set) {
return (profile.sigv4a_signing_region_set ?? "").split(",").map((_4) => _4.trim());
}
throw new ProviderError("sigv4a_signing_region_set not set in profile.", {
tryNextLink: true
});
},
default: void 0
};
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/constants.js
var ALGORITHM_QUERY_PARAM, CREDENTIAL_QUERY_PARAM, AMZ_DATE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, EXPIRES_QUERY_PARAM, SIGNATURE_QUERY_PARAM, TOKEN_QUERY_PARAM, AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER, GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER, TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER, EVENT_ALGORITHM_IDENTIFIER, UNSIGNED_PAYLOAD, MAX_CACHE_SIZE, KEY_TYPE_IDENTIFIER, MAX_PRESIGNED_TTL;
var init_constants8 = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/constants.js"() {
init_import_meta_url();
ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
EXPIRES_QUERY_PARAM = "X-Amz-Expires";
SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
AUTH_HEADER = "authorization";
AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
DATE_HEADER = "date";
GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
SHA256_HEADER = "x-amz-content-sha256";
TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
ALWAYS_UNSIGNABLE_HEADERS = {
authorization: true,
"cache-control": true,
connection: true,
expect: true,
from: true,
"keep-alive": true,
"max-forwards": true,
pragma: true,
referer: true,
te: true,
trailer: true,
"transfer-encoding": true,
upgrade: true,
"user-agent": true,
"x-amzn-trace-id": true
};
PROXY_HEADER_PATTERN = /^proxy-/;
SEC_HEADER_PATTERN = /^sec-/;
ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
MAX_CACHE_SIZE = 50;
KEY_TYPE_IDENTIFIER = "aws4_request";
MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js
var signingKeyCache, cacheQueue, createScope, getSigningKey, hmac;
var init_credentialDerivation = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js"() {
init_import_meta_url();
init_dist_es14();
init_dist_es8();
init_constants8();
signingKeyCache = {};
cacheQueue = [];
createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope");
getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => {
const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
const cacheKey = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`;
if (cacheKey in signingKeyCache) {
return signingKeyCache[cacheKey];
}
cacheQueue.push(cacheKey);
while (cacheQueue.length > MAX_CACHE_SIZE) {
delete signingKeyCache[cacheQueue.shift()];
}
let key = `AWS4${credentials.secretAccessKey}`;
for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
key = await hmac(sha256Constructor, key, signable);
}
return signingKeyCache[cacheKey] = key;
}, "getSigningKey");
hmac = /* @__PURE__ */ __name((ctor, secret, data) => {
const hash = new ctor(secret);
hash.update(toUint8Array(data));
return hash.digest();
}, "hmac");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js
var getCanonicalHeaders;
var init_getCanonicalHeaders = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js"() {
init_import_meta_url();
init_constants8();
getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => {
const canonical = {};
for (const headerName of Object.keys(headers).sort()) {
if (headers[headerName] == void 0) {
continue;
}
const canonicalHeaderName = headerName.toLowerCase();
if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
continue;
}
}
canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
}
return canonical;
}, "getCanonicalHeaders");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js
var getCanonicalQuery;
var init_getCanonicalQuery = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js"() {
init_import_meta_url();
init_dist_es10();
init_constants8();
getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => {
const keys = [];
const serialized = {};
for (const key of Object.keys(query)) {
if (key.toLowerCase() === SIGNATURE_HEADER) {
continue;
}
const encodedKey = escapeUri(key);
keys.push(encodedKey);
const value = query[key];
if (typeof value === "string") {
serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`;
} else if (Array.isArray(value)) {
serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${escapeUri(value2)}`]), []).sort().join("&");
}
}
return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
}, "getCanonicalQuery");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js
var getPayloadHash;
var init_getPayloadHash = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js"() {
init_import_meta_url();
init_dist_es6();
init_dist_es14();
init_dist_es8();
init_constants8();
getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => {
for (const headerName of Object.keys(headers)) {
if (headerName.toLowerCase() === SHA256_HEADER) {
return headers[headerName];
}
}
if (body == void 0) {
return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
} else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) {
const hashCtor = new hashConstructor();
hashCtor.update(toUint8Array(body));
return toHex(await hashCtor.digest());
}
return UNSIGNED_PAYLOAD;
}, "getPayloadHash");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js
function negate(bytes) {
for (let i5 = 0; i5 < 8; i5++) {
bytes[i5] ^= 255;
}
for (let i5 = 7; i5 > -1; i5--) {
bytes[i5]++;
if (bytes[i5] !== 0)
break;
}
}
var HeaderFormatter, HEADER_VALUE_TYPE, UUID_PATTERN, Int64;
var init_HeaderFormatter = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js"() {
init_import_meta_url();
init_dist_es14();
init_dist_es8();
HeaderFormatter = class {
static {
__name(this, "HeaderFormatter");
}
format(headers) {
const chunks = [];
for (const headerName of Object.keys(headers)) {
const bytes = fromUtf8(headerName);
chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
}
const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
let position = 0;
for (const chunk of chunks) {
out.set(chunk, position);
position += chunk.byteLength;
}
return out;
}
formatHeaderValue(header) {
switch (header.type) {
case "boolean":
return Uint8Array.from([header.value ? 0 : 1]);
case "byte":
return Uint8Array.from([2, header.value]);
case "short":
const shortView = new DataView(new ArrayBuffer(3));
shortView.setUint8(0, 3);
shortView.setInt16(1, header.value, false);
return new Uint8Array(shortView.buffer);
case "integer":
const intView = new DataView(new ArrayBuffer(5));
intView.setUint8(0, 4);
intView.setInt32(1, header.value, false);
return new Uint8Array(intView.buffer);
case "long":
const longBytes = new Uint8Array(9);
longBytes[0] = 5;
longBytes.set(header.value.bytes, 1);
return longBytes;
case "binary":
const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
binView.setUint8(0, 6);
binView.setUint16(1, header.value.byteLength, false);
const binBytes = new Uint8Array(binView.buffer);
binBytes.set(header.value, 3);
return binBytes;
case "string":
const utf8Bytes = fromUtf8(header.value);
const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
strView.setUint8(0, 7);
strView.setUint16(1, utf8Bytes.byteLength, false);
const strBytes = new Uint8Array(strView.buffer);
strBytes.set(utf8Bytes, 3);
return strBytes;
case "timestamp":
const tsBytes = new Uint8Array(9);
tsBytes[0] = 8;
tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
return tsBytes;
case "uuid":
if (!UUID_PATTERN.test(header.value)) {
throw new Error(`Invalid UUID received: ${header.value}`);
}
const uuidBytes = new Uint8Array(17);
uuidBytes[0] = 9;
uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
return uuidBytes;
}
}
};
(function(HEADER_VALUE_TYPE3) {
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid";
})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
Int64 = class _Int64 {
static {
__name(this, "Int64");
}
constructor(bytes) {
this.bytes = bytes;
if (bytes.byteLength !== 8) {
throw new Error("Int64 buffers must be exactly 8 bytes");
}
}
static fromNumber(number) {
if (number > 9223372036854776e3 || number < -9223372036854776e3) {
throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
}
const bytes = new Uint8Array(8);
for (let i5 = 7, remaining = Math.abs(Math.round(number)); i5 > -1 && remaining > 0; i5--, remaining /= 256) {
bytes[i5] = remaining;
}
if (number < 0) {
negate(bytes);
}
return new _Int64(bytes);
}
valueOf() {
const bytes = this.bytes.slice(0);
const negative = bytes[0] & 128;
if (negative) {
negate(bytes);
}
return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
}
toString() {
return String(this.valueOf());
}
};
__name(negate, "negate");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/headerUtil.js
var hasHeader;
var init_headerUtil = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/headerUtil.js"() {
init_import_meta_url();
hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => {
soughtHeader = soughtHeader.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (soughtHeader === headerName.toLowerCase()) {
return true;
}
}
return false;
}, "hasHeader");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js
var moveHeadersToQuery;
var init_moveHeadersToQuery = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js"() {
init_import_meta_url();
init_dist_es2();
moveHeadersToQuery = /* @__PURE__ */ __name((request4, options = {}) => {
const { headers, query = {} } = HttpRequest.clone(request4);
for (const name2 of Object.keys(headers)) {
const lname = name2.toLowerCase();
if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) {
query[name2] = headers[name2];
delete headers[name2];
}
}
return {
...request4,
headers,
query
};
}, "moveHeadersToQuery");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js
var prepareRequest;
var init_prepareRequest = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js"() {
init_import_meta_url();
init_dist_es2();
init_constants8();
prepareRequest = /* @__PURE__ */ __name((request4) => {
request4 = HttpRequest.clone(request4);
for (const headerName of Object.keys(request4.headers)) {
if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
delete request4.headers[headerName];
}
}
return request4;
}, "prepareRequest");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/utilDate.js
var iso8601, toDate2;
var init_utilDate = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/utilDate.js"() {
init_import_meta_url();
iso8601 = /* @__PURE__ */ __name((time) => toDate2(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601");
toDate2 = /* @__PURE__ */ __name((time) => {
if (typeof time === "number") {
return new Date(time * 1e3);
}
if (typeof time === "string") {
if (Number(time)) {
return new Date(Number(time) * 1e3);
}
return new Date(time);
}
return time;
}, "toDate");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js
var SignatureV4, formatDate, getCanonicalHeaderList;
var init_SignatureV4 = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js"() {
init_import_meta_url();
init_dist_es14();
init_dist_es4();
init_dist_es10();
init_dist_es8();
init_constants8();
init_credentialDerivation();
init_getCanonicalHeaders();
init_getCanonicalQuery();
init_getPayloadHash();
init_HeaderFormatter();
init_headerUtil();
init_moveHeadersToQuery();
init_prepareRequest();
init_utilDate();
SignatureV4 = class {
static {
__name(this, "SignatureV4");
}
constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
this.headerFormatter = new HeaderFormatter();
this.service = service;
this.sha256 = sha256;
this.uriEscapePath = uriEscapePath;
this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
this.regionProvider = normalizeProvider(region);
this.credentialProvider = normalizeProvider(credentials);
}
async presign(originalRequest, options = {}) {
const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options;
const credentials = await this.credentialProvider();
this.validateResolvedCredentials(credentials);
const region = signingRegion ?? await this.regionProvider();
const { longDate, shortDate } = formatDate(signingDate);
if (expiresIn > MAX_PRESIGNED_TTL) {
return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
}
const scope = createScope(shortDate, region, signingService ?? this.service);
const request4 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
if (credentials.sessionToken) {
request4.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;
}
request4.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
request4.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
request4.query[AMZ_DATE_QUERY_PARAM] = longDate;
request4.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
const canonicalHeaders = getCanonicalHeaders(request4, unsignableHeaders, signableHeaders);
request4.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders);
request4.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request4, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
return request4;
}
async sign(toSign, options) {
if (typeof toSign === "string") {
return this.signString(toSign, options);
} else if (toSign.headers && toSign.payload) {
return this.signEvent(toSign, options);
} else if (toSign.message) {
return this.signMessage(toSign, options);
} else {
return this.signRequest(toSign, options);
}
}
async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) {
const region = signingRegion ?? await this.regionProvider();
const { shortDate, longDate } = formatDate(signingDate);
const scope = createScope(shortDate, region, signingService ?? this.service);
const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
const hash = new this.sha256();
hash.update(headers);
const hashedHeaders = toHex(await hash.digest());
const stringToSign = [
EVENT_ALGORITHM_IDENTIFIER,
longDate,
scope,
priorSignature,
hashedHeaders,
hashedPayload
].join("\n");
return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
}
async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
const promise = this.signEvent({
headers: this.headerFormatter.format(signableMessage.message.headers),
payload: signableMessage.message.body
}, {
signingDate,
signingRegion,
signingService,
priorSignature: signableMessage.priorSignature
});
return promise.then((signature) => {
return { message: signableMessage.message, signature };
});
}
async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) {
const credentials = await this.credentialProvider();
this.validateResolvedCredentials(credentials);
const region = signingRegion ?? await this.regionProvider();
const { shortDate } = formatDate(signingDate);
const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
hash.update(toUint8Array(stringToSign));
return toHex(await hash.digest());
}
async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
const credentials = await this.credentialProvider();
this.validateResolvedCredentials(credentials);
const region = signingRegion ?? await this.regionProvider();
const request4 = prepareRequest(requestToSign);
const { longDate, shortDate } = formatDate(signingDate);
const scope = createScope(shortDate, region, signingService ?? this.service);
request4.headers[AMZ_DATE_HEADER] = longDate;
if (credentials.sessionToken) {
request4.headers[TOKEN_HEADER] = credentials.sessionToken;
}
const payloadHash = await getPayloadHash(request4, this.sha256);
if (!hasHeader(SHA256_HEADER, request4.headers) && this.applyChecksum) {
request4.headers[SHA256_HEADER] = payloadHash;
}
const canonicalHeaders = getCanonicalHeaders(request4, unsignableHeaders, signableHeaders);
const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request4, canonicalHeaders, payloadHash));
request4.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
return request4;
}
createCanonicalRequest(request4, canonicalHeaders, payloadHash) {
const sortedHeaders = Object.keys(canonicalHeaders).sort();
return `${request4.method}
${this.getCanonicalPath(request4)}
${getCanonicalQuery(request4)}
${sortedHeaders.map((name2) => `${name2}:${canonicalHeaders[name2]}`).join("\n")}
${sortedHeaders.join(";")}
${payloadHash}`;
}
async createStringToSign(longDate, credentialScope, canonicalRequest) {
const hash = new this.sha256();
hash.update(toUint8Array(canonicalRequest));
const hashedRequest = await hash.digest();
return `${ALGORITHM_IDENTIFIER}
${longDate}
${credentialScope}
${toHex(hashedRequest)}`;
}
getCanonicalPath({ path: path72 }) {
if (this.uriEscapePath) {
const normalizedPathSegments = [];
for (const pathSegment of path72.split("/")) {
if (pathSegment?.length === 0)
continue;
if (pathSegment === ".")
continue;
if (pathSegment === "..") {
normalizedPathSegments.pop();
} else {
normalizedPathSegments.push(pathSegment);
}
}
const normalizedPath = `${path72?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path72?.endsWith("/") ? "/" : ""}`;
const doubleEncoded = escapeUri(normalizedPath);
return doubleEncoded.replace(/%2F/g, "/");
}
return path72;
}
async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest);
const hash = new this.sha256(await keyPromise);
hash.update(toUint8Array(stringToSign));
return toHex(await hash.digest());
}
getSigningKey(credentials, region, shortDate, service) {
return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
}
validateResolvedCredentials(credentials) {
if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
throw new Error("Resolved credential object is not valid");
}
}
};
formatDate = /* @__PURE__ */ __name((now) => {
const longDate = iso8601(now).replace(/[\-:]/g, "");
return {
longDate,
shortDate: longDate.slice(0, 8)
};
}, "formatDate");
getCanonicalHeaderList = /* @__PURE__ */ __name((headers) => Object.keys(headers).sort().join(";"), "getCanonicalHeaderList");
}
});
// ../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/index.js
var init_dist_es18 = __esm({
"../../node_modules/.pnpm/@smithy+signature-v4@4.2.4/node_modules/@smithy/signature-v4/dist-es/index.js"() {
init_import_meta_url();
init_SignatureV4();
init_getCanonicalHeaders();
init_getCanonicalQuery();
init_getPayloadHash();
init_moveHeadersToQuery();
init_prepareRequest();
init_credentialDerivation();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
var resolveAwsSdkSigV4Config;
var init_resolveAwsSdkSigV4Config = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() {
init_import_meta_url();
init_client5();
init_dist_es16();
init_dist_es18();
resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => {
let isUserSupplied = false;
let credentialsProvider;
if (config.credentials) {
isUserSupplied = true;
credentialsProvider = memoizeIdentityProvider(config.credentials, isIdentityExpired, doesIdentityRequireRefresh);
}
if (!credentialsProvider) {
if (config.credentialDefaultProvider) {
credentialsProvider = normalizeProvider2(config.credentialDefaultProvider(Object.assign({}, config, {
parentClientConfig: config
})));
} else {
credentialsProvider = /* @__PURE__ */ __name(async () => {
throw new Error("`credentials` is missing");
}, "credentialsProvider");
}
}
const boundCredentialsProvider = /* @__PURE__ */ __name(async () => credentialsProvider({ callerClientConfig: config }), "boundCredentialsProvider");
const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256 } = config;
let signer;
if (config.signer) {
signer = normalizeProvider2(config.signer);
} else if (config.regionInfoProvider) {
signer = /* @__PURE__ */ __name(() => normalizeProvider2(config.region)().then(async (region) => [
await config.regionInfoProvider(region, {
useFipsEndpoint: await config.useFipsEndpoint(),
useDualstackEndpoint: await config.useDualstackEndpoint()
}) || {},
region
]).then(([regionInfo, region]) => {
const { signingRegion, signingService } = regionInfo;
config.signingRegion = config.signingRegion || signingRegion || region;
config.signingName = config.signingName || signingService || config.serviceId;
const params = {
...config,
credentials: boundCredentialsProvider,
region: config.signingRegion,
service: config.signingName,
sha256,
uriEscapePath: signingEscapePath
};
const SignerCtor = config.signerConstructor || SignatureV4;
return new SignerCtor(params);
}), "signer");
} else {
signer = /* @__PURE__ */ __name(async (authScheme) => {
authScheme = Object.assign({}, {
name: "sigv4",
signingName: config.signingName || config.defaultSigningName,
signingRegion: await normalizeProvider2(config.region)(),
properties: {}
}, authScheme);
const signingRegion = authScheme.signingRegion;
const signingService = authScheme.signingName;
config.signingRegion = config.signingRegion || signingRegion;
config.signingName = config.signingName || signingService || config.serviceId;
const params = {
...config,
credentials: boundCredentialsProvider,
region: config.signingRegion,
service: config.signingName,
sha256,
uriEscapePath: signingEscapePath
};
const SignerCtor = config.signerConstructor || SignatureV4;
return new SignerCtor(params);
}, "signer");
}
return {
...config,
systemClockOffset,
signingEscapePath,
credentials: isUserSupplied ? async () => boundCredentialsProvider().then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e")) : boundCredentialsProvider,
signer
};
}, "resolveAwsSdkSigV4Config");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
var init_aws_sdk = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() {
init_import_meta_url();
init_AwsSdkSigV4Signer();
init_AwsSdkSigV4ASigner();
init_resolveAwsSdkSigV4AConfig();
init_resolveAwsSdkSigV4Config();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
var init_httpAuthSchemes2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() {
init_import_meta_url();
init_aws_sdk();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
var init_coercing_serializers = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-stack@3.0.11/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js
var getAllAliases, getMiddlewareNameWithAliases, constructStack, stepWeights, priorityWeights;
var init_MiddlewareStack = __esm({
"../../node_modules/.pnpm/@smithy+middleware-stack@3.0.11/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"() {
init_import_meta_url();
getAllAliases = /* @__PURE__ */ __name((name2, aliases2) => {
const _aliases = [];
if (name2) {
_aliases.push(name2);
}
if (aliases2) {
for (const alias of aliases2) {
_aliases.push(alias);
}
}
return _aliases;
}, "getAllAliases");
getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name2, aliases2) => {
return `${name2 || "anonymous"}${aliases2 && aliases2.length > 0 ? ` (a.k.a. ${aliases2.join(",")})` : ""}`;
}, "getMiddlewareNameWithAliases");
constructStack = /* @__PURE__ */ __name(() => {
let absoluteEntries = [];
let relativeEntries = [];
let identifyOnResolve = false;
const entriesNameSet = /* @__PURE__ */ new Set();
const sort = /* @__PURE__ */ __name((entries) => entries.sort((a5, b6) => stepWeights[b6.step] - stepWeights[a5.step] || priorityWeights[b6.priority || "normal"] - priorityWeights[a5.priority || "normal"]), "sort");
const removeByName = /* @__PURE__ */ __name((toRemove) => {
let isRemoved = false;
const filterCb = /* @__PURE__ */ __name((entry) => {
const aliases2 = getAllAliases(entry.name, entry.aliases);
if (aliases2.includes(toRemove)) {
isRemoved = true;
for (const alias of aliases2) {
entriesNameSet.delete(alias);
}
return false;
}
return true;
}, "filterCb");
absoluteEntries = absoluteEntries.filter(filterCb);
relativeEntries = relativeEntries.filter(filterCb);
return isRemoved;
}, "removeByName");
const removeByReference = /* @__PURE__ */ __name((toRemove) => {
let isRemoved = false;
const filterCb = /* @__PURE__ */ __name((entry) => {
if (entry.middleware === toRemove) {
isRemoved = true;
for (const alias of getAllAliases(entry.name, entry.aliases)) {
entriesNameSet.delete(alias);
}
return false;
}
return true;
}, "filterCb");
absoluteEntries = absoluteEntries.filter(filterCb);
relativeEntries = relativeEntries.filter(filterCb);
return isRemoved;
}, "removeByReference");
const cloneTo = /* @__PURE__ */ __name((toStack) => {
absoluteEntries.forEach((entry) => {
toStack.add(entry.middleware, { ...entry });
});
relativeEntries.forEach((entry) => {
toStack.addRelativeTo(entry.middleware, { ...entry });
});
toStack.identifyOnResolve?.(stack.identifyOnResolve());
return toStack;
}, "cloneTo");
const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => {
const expandedMiddlewareList = [];
from.before.forEach((entry) => {
if (entry.before.length === 0 && entry.after.length === 0) {
expandedMiddlewareList.push(entry);
} else {
expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
}
});
expandedMiddlewareList.push(from);
from.after.reverse().forEach((entry) => {
if (entry.before.length === 0 && entry.after.length === 0) {
expandedMiddlewareList.push(entry);
} else {
expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
}
});
return expandedMiddlewareList;
}, "expandRelativeMiddlewareList");
const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => {
const normalizedAbsoluteEntries = [];
const normalizedRelativeEntries = [];
const normalizedEntriesNameMap = {};
absoluteEntries.forEach((entry) => {
const normalizedEntry = {
...entry,
before: [],
after: []
};
for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
normalizedEntriesNameMap[alias] = normalizedEntry;
}
normalizedAbsoluteEntries.push(normalizedEntry);
});
relativeEntries.forEach((entry) => {
const normalizedEntry = {
...entry,
before: [],
after: []
};
for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
normalizedEntriesNameMap[alias] = normalizedEntry;
}
normalizedRelativeEntries.push(normalizedEntry);
});
normalizedRelativeEntries.forEach((entry) => {
if (entry.toMiddleware) {
const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
if (toMiddleware === void 0) {
if (debug) {
return;
}
throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`);
}
if (entry.relation === "after") {
toMiddleware.after.push(entry);
}
if (entry.relation === "before") {
toMiddleware.before.push(entry);
}
}
});
const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => {
wholeList.push(...expandedMiddlewareList);
return wholeList;
}, []);
return mainChain;
}, "getMiddlewareList");
const stack = {
add: /* @__PURE__ */ __name((middleware, options = {}) => {
const { name: name2, override, aliases: _aliases } = options;
const entry = {
step: "initialize",
priority: "normal",
middleware,
...options
};
const aliases2 = getAllAliases(name2, _aliases);
if (aliases2.length > 0) {
if (aliases2.some((alias) => entriesNameSet.has(alias))) {
if (!override)
throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name2, _aliases)}'`);
for (const alias of aliases2) {
const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias));
if (toOverrideIndex === -1) {
continue;
}
const toOverride = absoluteEntries[toOverrideIndex];
if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name2, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);
}
absoluteEntries.splice(toOverrideIndex, 1);
}
}
for (const alias of aliases2) {
entriesNameSet.add(alias);
}
}
absoluteEntries.push(entry);
}, "add"),
addRelativeTo: /* @__PURE__ */ __name((middleware, options) => {
const { name: name2, override, aliases: _aliases } = options;
const entry = {
middleware,
...options
};
const aliases2 = getAllAliases(name2, _aliases);
if (aliases2.length > 0) {
if (aliases2.some((alias) => entriesNameSet.has(alias))) {
if (!override)
throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name2, _aliases)}'`);
for (const alias of aliases2) {
const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias));
if (toOverrideIndex === -1) {
continue;
}
const toOverride = relativeEntries[toOverrideIndex];
if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name2, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);
}
relativeEntries.splice(toOverrideIndex, 1);
}
}
for (const alias of aliases2) {
entriesNameSet.add(alias);
}
}
relativeEntries.push(entry);
}, "addRelativeTo"),
clone: /* @__PURE__ */ __name(() => cloneTo(constructStack()), "clone"),
use: /* @__PURE__ */ __name((plugin) => {
plugin.applyToStack(stack);
}, "use"),
remove: /* @__PURE__ */ __name((toRemove) => {
if (typeof toRemove === "string")
return removeByName(toRemove);
else
return removeByReference(toRemove);
}, "remove"),
removeByTag: /* @__PURE__ */ __name((toRemove) => {
let isRemoved = false;
const filterCb = /* @__PURE__ */ __name((entry) => {
const { tags, name: name2, aliases: _aliases } = entry;
if (tags && tags.includes(toRemove)) {
const aliases2 = getAllAliases(name2, _aliases);
for (const alias of aliases2) {
entriesNameSet.delete(alias);
}
isRemoved = true;
return false;
}
return true;
}, "filterCb");
absoluteEntries = absoluteEntries.filter(filterCb);
relativeEntries = relativeEntries.filter(filterCb);
return isRemoved;
}, "removeByTag"),
concat: /* @__PURE__ */ __name((from) => {
const cloned = cloneTo(constructStack());
cloned.use(from);
cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));
return cloned;
}, "concat"),
applyToStack: cloneTo,
identify: /* @__PURE__ */ __name(() => {
return getMiddlewareList(true).map((mw) => {
const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
});
}, "identify"),
identifyOnResolve(toggle) {
if (typeof toggle === "boolean")
identifyOnResolve = toggle;
return identifyOnResolve;
},
resolve: /* @__PURE__ */ __name((handler, context2) => {
for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
handler = middleware(handler, context2);
}
if (identifyOnResolve) {
console.log(stack.identify());
}
return handler;
}, "resolve")
};
return stack;
}, "constructStack");
stepWeights = {
initialize: 5,
serialize: 4,
build: 3,
finalizeRequest: 2,
deserialize: 1
};
priorityWeights = {
high: 3,
normal: 2,
low: 1
};
}
});
// ../../node_modules/.pnpm/@smithy+middleware-stack@3.0.11/node_modules/@smithy/middleware-stack/dist-es/index.js
var init_dist_es19 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-stack@3.0.11/node_modules/@smithy/middleware-stack/dist-es/index.js"() {
init_import_meta_url();
init_MiddlewareStack();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/client.js
var Client;
var init_client6 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/client.js"() {
init_import_meta_url();
init_dist_es19();
Client = class {
static {
__name(this, "Client");
}
constructor(config) {
this.config = config;
this.middlewareStack = constructStack();
}
send(command2, optionsOrCb, cb2) {
const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb2;
const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true;
let handler;
if (useHandlerCache) {
if (!this.handlers) {
this.handlers = /* @__PURE__ */ new WeakMap();
}
const handlers2 = this.handlers;
if (handlers2.has(command2.constructor)) {
handler = handlers2.get(command2.constructor);
} else {
handler = command2.resolveMiddleware(this.middlewareStack, this.config, options);
handlers2.set(command2.constructor, handler);
}
} else {
delete this.handlers;
handler = command2.resolveMiddleware(this.middlewareStack, this.config, options);
}
if (callback) {
handler(command2).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {
});
} else {
return handler(command2).then((result) => result.output);
}
}
destroy() {
this.config?.requestHandler?.destroy?.();
delete this.handlers;
}
};
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
var init_collect_stream_body2 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js"() {
init_import_meta_url();
init_protocols();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/command.js
var Command, ClassBuilder;
var init_command4 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/command.js"() {
init_import_meta_url();
init_dist_es19();
init_dist_es();
Command = class {
static {
__name(this, "Command");
}
constructor() {
this.middlewareStack = constructStack();
}
static classBuilder() {
return new ClassBuilder();
}
resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
this.middlewareStack.use(mw);
}
const stack = clientStack.concat(this.middlewareStack);
const { logger: logger4 } = configuration;
const handlerExecutionContext = {
logger: logger4,
clientName,
commandName,
inputFilterSensitiveLog,
outputFilterSensitiveLog,
[SMITHY_CONTEXT_KEY]: {
commandInstance: this,
...smithyContext
},
...additionalContext
};
const { requestHandler } = configuration;
return stack.resolve((request4) => requestHandler.handle(request4.request, options || {}), handlerExecutionContext);
}
};
ClassBuilder = class {
static {
__name(this, "ClassBuilder");
}
constructor() {
this._init = () => {
};
this._ep = {};
this._middlewareFn = () => [];
this._commandName = "";
this._clientName = "";
this._additionalContext = {};
this._smithyContext = {};
this._inputFilterSensitiveLog = (_4) => _4;
this._outputFilterSensitiveLog = (_4) => _4;
this._serializer = null;
this._deserializer = null;
}
init(cb2) {
this._init = cb2;
}
ep(endpointParameterInstructions) {
this._ep = endpointParameterInstructions;
return this;
}
m(middlewareSupplier) {
this._middlewareFn = middlewareSupplier;
return this;
}
s(service, operation, smithyContext = {}) {
this._smithyContext = {
service,
operation,
...smithyContext
};
return this;
}
c(additionalContext = {}) {
this._additionalContext = additionalContext;
return this;
}
n(clientName, commandName) {
this._clientName = clientName;
this._commandName = commandName;
return this;
}
f(inputFilter = (_4) => _4, outputFilter = (_4) => _4) {
this._inputFilterSensitiveLog = inputFilter;
this._outputFilterSensitiveLog = outputFilter;
return this;
}
ser(serializer) {
this._serializer = serializer;
return this;
}
de(deserializer) {
this._deserializer = deserializer;
return this;
}
build() {
const closure = this;
let CommandRef;
return CommandRef = class extends Command {
static {
__name(this, "CommandRef");
}
static getEndpointParameterInstructions() {
return closure._ep;
}
constructor(...[input]) {
super();
this.serialize = closure._serializer;
this.deserialize = closure._deserializer;
this.input = input ?? {};
closure._init(this);
}
resolveMiddleware(stack, configuration, options) {
return this.resolveMiddlewareWithContext(stack, configuration, options, {
CommandCtor: CommandRef,
middlewareFn: closure._middlewareFn,
clientName: closure._clientName,
commandName: closure._commandName,
inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
smithyContext: closure._smithyContext,
additionalContext: closure._additionalContext
});
}
};
}
};
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/constants.js
var SENSITIVE_STRING;
var init_constants9 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/constants.js"() {
init_import_meta_url();
SENSITIVE_STRING = "***SensitiveInformation***";
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
var createAggregatedClient;
var init_create_aggregated_client = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() {
init_import_meta_url();
createAggregatedClient = /* @__PURE__ */ __name((commands5, Client2) => {
for (const command2 of Object.keys(commands5)) {
const CommandCtor = commands5[command2];
const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb2) {
const command3 = new CommandCtor(args);
if (typeof optionsOrCb === "function") {
this.send(command3, optionsOrCb);
} else if (typeof cb2 === "function") {
if (typeof optionsOrCb !== "object")
throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
this.send(command3, optionsOrCb || {}, cb2);
} else {
return this.send(command3, optionsOrCb);
}
}, "methodImpl");
const methodName = (command2[0].toLowerCase() + command2.slice(1)).replace(/Command$/, "");
Client2.prototype[methodName] = methodImpl;
}
}, "createAggregatedClient");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/parse-utils.js
var parseBoolean, expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectObject, expectString, expectUnion, strictParseFloat32, NUMBER_REGEX, parseNumber, strictParseLong, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger2;
var init_parse_utils = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/parse-utils.js"() {
init_import_meta_url();
parseBoolean = /* @__PURE__ */ __name((value) => {
switch (value) {
case "true":
return true;
case "false":
return false;
default:
throw new Error(`Unable to parse boolean value "${value}"`);
}
}, "parseBoolean");
expectNumber = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (typeof value === "string") {
const parsed = parseFloat(value);
if (!Number.isNaN(parsed)) {
if (String(parsed) !== String(value)) {
logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
}
return parsed;
}
}
if (typeof value === "number") {
return value;
}
throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
}, "expectNumber");
MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
expectFloat32 = /* @__PURE__ */ __name((value) => {
const expected = expectNumber(value);
if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
if (Math.abs(expected) > MAX_FLOAT) {
throw new TypeError(`Expected 32-bit float, got ${value}`);
}
}
return expected;
}, "expectFloat32");
expectLong = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (Number.isInteger(value) && !Number.isNaN(value)) {
return value;
}
throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
}, "expectLong");
expectInt32 = /* @__PURE__ */ __name((value) => expectSizedInt(value, 32), "expectInt32");
expectShort = /* @__PURE__ */ __name((value) => expectSizedInt(value, 16), "expectShort");
expectByte = /* @__PURE__ */ __name((value) => expectSizedInt(value, 8), "expectByte");
expectSizedInt = /* @__PURE__ */ __name((value, size) => {
const expected = expectLong(value);
if (expected !== void 0 && castInt(expected, size) !== expected) {
throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
}
return expected;
}, "expectSizedInt");
castInt = /* @__PURE__ */ __name((value, size) => {
switch (size) {
case 32:
return Int32Array.of(value)[0];
case 16:
return Int16Array.of(value)[0];
case 8:
return Int8Array.of(value)[0];
}
}, "castInt");
expectNonNull = /* @__PURE__ */ __name((value, location) => {
if (value === null || value === void 0) {
if (location) {
throw new TypeError(`Expected a non-null value for ${location}`);
}
throw new TypeError("Expected a non-null value");
}
return value;
}, "expectNonNull");
expectObject = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (typeof value === "object" && !Array.isArray(value)) {
return value;
}
const receivedType = Array.isArray(value) ? "array" : typeof value;
throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
}, "expectObject");
expectString = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (typeof value === "string") {
return value;
}
if (["boolean", "number", "bigint"].includes(typeof value)) {
logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
return String(value);
}
throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
}, "expectString");
expectUnion = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
const asObject = expectObject(value);
const setKeys = Object.entries(asObject).filter(([, v7]) => v7 != null).map(([k6]) => k6);
if (setKeys.length === 0) {
throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
}
if (setKeys.length > 1) {
throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
}
return asObject;
}, "expectUnion");
strictParseFloat32 = /* @__PURE__ */ __name((value) => {
if (typeof value == "string") {
return expectFloat32(parseNumber(value));
}
return expectFloat32(value);
}, "strictParseFloat32");
NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
parseNumber = /* @__PURE__ */ __name((value) => {
const matches = value.match(NUMBER_REGEX);
if (matches === null || matches[0].length !== value.length) {
throw new TypeError(`Expected real number, got implicit NaN`);
}
return parseFloat(value);
}, "parseNumber");
strictParseLong = /* @__PURE__ */ __name((value) => {
if (typeof value === "string") {
return expectLong(parseNumber(value));
}
return expectLong(value);
}, "strictParseLong");
strictParseInt32 = /* @__PURE__ */ __name((value) => {
if (typeof value === "string") {
return expectInt32(parseNumber(value));
}
return expectInt32(value);
}, "strictParseInt32");
strictParseShort = /* @__PURE__ */ __name((value) => {
if (typeof value === "string") {
return expectShort(parseNumber(value));
}
return expectShort(value);
}, "strictParseShort");
strictParseByte = /* @__PURE__ */ __name((value) => {
if (typeof value === "string") {
return expectByte(parseNumber(value));
}
return expectByte(value);
}, "strictParseByte");
stackTraceWarning = /* @__PURE__ */ __name((message) => {
return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s5) => !s5.includes("stackTraceWarning")).join("\n");
}, "stackTraceWarning");
logger2 = {
warn: console.warn
};
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/date-utils.js
function dateToUtcString(date) {
const year = date.getUTCFullYear();
const month = date.getUTCMonth();
const dayOfWeek = date.getUTCDay();
const dayOfMonthInt = date.getUTCDate();
const hoursInt = date.getUTCHours();
const minutesInt = date.getUTCMinutes();
const secondsInt = date.getUTCSeconds();
const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;
const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;
const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;
const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;
return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`;
}
var DAYS, MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseRfc7231DateTime, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
var init_date_utils = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/date-utils.js"() {
init_import_meta_url();
init_parse_utils();
DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
__name(dateToUtcString, "dateToUtcString");
RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
parseRfc3339DateTime = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (typeof value !== "string") {
throw new TypeError("RFC-3339 date-times must be expressed as strings");
}
const match2 = RFC3339.exec(value);
if (!match2) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const [_4, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
const year = strictParseShort(stripLeadingZeroes(yearStr));
const month = parseDateValue(monthStr, "month", 1, 12);
const day = parseDateValue(dayStr, "day", 1, 31);
return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
}, "parseRfc3339DateTime");
RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
parseRfc3339DateTimeWithOffset = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (typeof value !== "string") {
throw new TypeError("RFC-3339 date-times must be expressed as strings");
}
const match2 = RFC3339_WITH_OFFSET.exec(value);
if (!match2) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const [_4, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2;
const year = strictParseShort(stripLeadingZeroes(yearStr));
const month = parseDateValue(monthStr, "month", 1, 12);
const day = parseDateValue(dayStr, "day", 1, 31);
const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
if (offsetStr.toUpperCase() != "Z") {
date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));
}
return date;
}, "parseRfc3339DateTimeWithOffset");
IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
parseRfc7231DateTime = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return void 0;
}
if (typeof value !== "string") {
throw new TypeError("RFC-7231 date-times must be expressed as strings");
}
let match2 = IMF_FIXDATE.exec(value);
if (match2) {
const [_4, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
}
match2 = RFC_850_DATE.exec(value);
if (match2) {
const [_4, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), {
hours,
minutes,
seconds,
fractionalMilliseconds
}));
}
match2 = ASC_TIME.exec(value);
if (match2) {
const [_4, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match2;
return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
}
throw new TypeError("Invalid RFC-7231 date-time value");
}, "parseRfc7231DateTime");
buildDate = /* @__PURE__ */ __name((year, month, day, time) => {
const adjustedMonth = month - 1;
validateDayOfMonth(year, adjustedMonth, day);
return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
}, "buildDate");
parseTwoDigitYear = /* @__PURE__ */ __name((value) => {
const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear();
const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value));
if (valueInThisCentury < thisYear) {
return valueInThisCentury + 100;
}
return valueInThisCentury;
}, "parseTwoDigitYear");
FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
adjustRfc850Year = /* @__PURE__ */ __name((input) => {
if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) {
return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds()));
}
return input;
}, "adjustRfc850Year");
parseMonthByShortName = /* @__PURE__ */ __name((value) => {
const monthIdx = MONTHS.indexOf(value);
if (monthIdx < 0) {
throw new TypeError(`Invalid month: ${value}`);
}
return monthIdx + 1;
}, "parseMonthByShortName");
DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
validateDayOfMonth = /* @__PURE__ */ __name((year, month, day) => {
let maxDays = DAYS_IN_MONTH[month];
if (month === 1 && isLeapYear(year)) {
maxDays = 29;
}
if (day > maxDays) {
throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
}
}, "validateDayOfMonth");
isLeapYear = /* @__PURE__ */ __name((year) => {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}, "isLeapYear");
parseDateValue = /* @__PURE__ */ __name((value, type, lower, upper) => {
const dateVal = strictParseByte(stripLeadingZeroes(value));
if (dateVal < lower || dateVal > upper) {
throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);
}
return dateVal;
}, "parseDateValue");
parseMilliseconds = /* @__PURE__ */ __name((value) => {
if (value === null || value === void 0) {
return 0;
}
return strictParseFloat32("0." + value) * 1e3;
}, "parseMilliseconds");
parseOffsetToMilliseconds = /* @__PURE__ */ __name((value) => {
const directionStr = value[0];
let direction = 1;
if (directionStr == "+") {
direction = 1;
} else if (directionStr == "-") {
direction = -1;
} else {
throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
}
const hour = Number(value.substring(1, 3));
const minute = Number(value.substring(4, 6));
return direction * (hour * 60 + minute) * 60 * 1e3;
}, "parseOffsetToMilliseconds");
stripLeadingZeroes = /* @__PURE__ */ __name((value) => {
let idx = 0;
while (idx < value.length - 1 && value.charAt(idx) === "0") {
idx++;
}
if (idx === 0) {
return value;
}
return value.slice(idx);
}, "stripLeadingZeroes");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/exceptions.js
var ServiceException, decorateServiceException;
var init_exceptions = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/exceptions.js"() {
init_import_meta_url();
ServiceException = class _ServiceException extends Error {
static {
__name(this, "ServiceException");
}
constructor(options) {
super(options.message);
Object.setPrototypeOf(this, _ServiceException.prototype);
this.name = options.name;
this.$fault = options.$fault;
this.$metadata = options.$metadata;
}
static isInstance(value) {
if (!value)
return false;
const candidate = value;
return Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
}
};
decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => {
Object.entries(additions).filter(([, v7]) => v7 !== void 0).forEach(([k6, v7]) => {
if (exception[k6] == void 0 || exception[k6] === "") {
exception[k6] = v7;
}
});
const message = exception.message || exception.Message || "UnknownError";
exception.message = message;
delete exception.Message;
return exception;
}, "decorateServiceException");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
var throwDefaultError, withBaseException, deserializeMetadata;
var init_default_error_handler = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js"() {
init_import_meta_url();
init_exceptions();
throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => {
const $metadata = deserializeMetadata(output);
const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
const response = new exceptionCtor({
name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
$fault: "client",
$metadata
});
throw decorateServiceException(response, parsedBody);
}, "throwDefaultError");
withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => {
return ({ output, parsedBody, errorCode }) => {
throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
};
}, "withBaseException");
deserializeMetadata = /* @__PURE__ */ __name((output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"]
}), "deserializeMetadata");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
var loadConfigsForDefaultMode;
var init_defaults_mode = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"() {
init_import_meta_url();
loadConfigsForDefaultMode = /* @__PURE__ */ __name((mode) => {
switch (mode) {
case "standard":
return {
retryMode: "standard",
connectionTimeout: 3100
};
case "in-region":
return {
retryMode: "standard",
connectionTimeout: 1100
};
case "cross-region":
return {
retryMode: "standard",
connectionTimeout: 3100
};
case "mobile":
return {
retryMode: "standard",
connectionTimeout: 3e4
};
default:
return {};
}
}, "loadConfigsForDefaultMode");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
var warningEmitted, emitWarningIfUnsupportedVersion2;
var init_emitWarningIfUnsupportedVersion2 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"() {
init_import_meta_url();
warningEmitted = false;
emitWarningIfUnsupportedVersion2 = /* @__PURE__ */ __name((version5) => {
if (version5 && !warningEmitted && parseInt(version5.substring(1, version5.indexOf("."))) < 16) {
warningEmitted = true;
}
}, "emitWarningIfUnsupportedVersion");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
var init_extended_encode_uri_component2 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js"() {
init_import_meta_url();
init_protocols();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
var getChecksumConfiguration2, resolveChecksumRuntimeConfig2;
var init_checksum3 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js"() {
init_import_meta_url();
init_dist_es();
getChecksumConfiguration2 = /* @__PURE__ */ __name((runtimeConfig) => {
const checksumAlgorithms = [];
for (const id in AlgorithmId) {
const algorithmId = AlgorithmId[id];
if (runtimeConfig[algorithmId] === void 0) {
continue;
}
checksumAlgorithms.push({
algorithmId: /* @__PURE__ */ __name(() => algorithmId, "algorithmId"),
checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig[algorithmId], "checksumConstructor")
});
}
return {
_checksumAlgorithms: checksumAlgorithms,
addChecksumAlgorithm(algo) {
this._checksumAlgorithms.push(algo);
},
checksumAlgorithms() {
return this._checksumAlgorithms;
}
};
}, "getChecksumConfiguration");
resolveChecksumRuntimeConfig2 = /* @__PURE__ */ __name((clientConfig) => {
const runtimeConfig = {};
clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
});
return runtimeConfig;
}, "resolveChecksumRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
var getRetryConfiguration, resolveRetryRuntimeConfig;
var init_retry3 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js"() {
init_import_meta_url();
getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
let _retryStrategy = runtimeConfig.retryStrategy;
return {
setRetryStrategy(retryStrategy) {
_retryStrategy = retryStrategy;
},
retryStrategy() {
return _retryStrategy;
}
};
}, "getRetryConfiguration");
resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => {
const runtimeConfig = {};
runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
return runtimeConfig;
}, "resolveRetryRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
var getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig;
var init_defaultExtensionConfiguration2 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"() {
init_import_meta_url();
init_checksum3();
init_retry3();
getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
return {
...getChecksumConfiguration2(runtimeConfig),
...getRetryConfiguration(runtimeConfig)
};
}, "getDefaultExtensionConfiguration");
resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => {
return {
...resolveChecksumRuntimeConfig2(config),
...resolveRetryRuntimeConfig(config)
};
}, "resolveDefaultRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/index.js
var init_extensions3 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/extensions/index.js"() {
init_import_meta_url();
init_defaultExtensionConfiguration2();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
var getArrayIfSingleItem;
var init_get_array_if_single_item = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js"() {
init_import_meta_url();
getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
var getValueFromTextNode;
var init_get_value_from_text_node = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js"() {
init_import_meta_url();
getValueFromTextNode = /* @__PURE__ */ __name((obj) => {
const textNodeName = "#text";
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) {
obj[key] = obj[key][textNodeName];
} else if (typeof obj[key] === "object" && obj[key] !== null) {
obj[key] = getValueFromTextNode(obj[key]);
}
}
return obj;
}, "getValueFromTextNode");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
var isSerializableHeaderValue;
var init_is_serializable_header_value = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js"() {
init_import_meta_url();
isSerializableHeaderValue = /* @__PURE__ */ __name((value) => {
return value != null;
}, "isSerializableHeaderValue");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/lazy-json.js
var LazyJsonString;
var init_lazy_json = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/lazy-json.js"() {
init_import_meta_url();
LazyJsonString = /* @__PURE__ */ __name(function LazyJsonString2(val2) {
const str = Object.assign(new String(val2), {
deserializeJSON() {
return JSON.parse(String(val2));
},
toString() {
return String(val2);
},
toJSON() {
return String(val2);
}
});
return str;
}, "LazyJsonString");
LazyJsonString.from = (object) => {
if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) {
return object;
} else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) {
return LazyJsonString(String(object));
}
return LazyJsonString(JSON.stringify(object));
};
LazyJsonString.fromObject = LazyJsonString.from;
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
var NoOpLogger;
var init_NoOpLogger = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"() {
init_import_meta_url();
NoOpLogger = class {
static {
__name(this, "NoOpLogger");
}
trace() {
}
debug() {
}
info() {
}
warn() {
}
error() {
}
};
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/object-mapping.js
function map(arg0, arg1, arg2) {
let target;
let filter;
let instructions;
if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
target = {};
instructions = arg0;
} else {
target = arg0;
if (typeof arg1 === "function") {
filter = arg1;
instructions = arg2;
return mapWithFilter(target, filter, instructions);
} else {
instructions = arg1;
}
}
for (const key of Object.keys(instructions)) {
if (!Array.isArray(instructions[key])) {
target[key] = instructions[key];
continue;
}
applyInstruction(target, null, instructions, key);
}
return target;
}
var take, mapWithFilter, applyInstruction, nonNullish, pass;
var init_object_mapping = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/object-mapping.js"() {
init_import_meta_url();
__name(map, "map");
take = /* @__PURE__ */ __name((source, instructions) => {
const out = {};
for (const key in instructions) {
applyInstruction(out, source, instructions, key);
}
return out;
}, "take");
mapWithFilter = /* @__PURE__ */ __name((target, filter, instructions) => {
return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
if (Array.isArray(value)) {
_instructions[key] = value;
} else {
if (typeof value === "function") {
_instructions[key] = [filter, value()];
} else {
_instructions[key] = [filter, value];
}
}
return _instructions;
}, {}));
}, "mapWithFilter");
applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => {
if (source !== null) {
let instruction = instructions[targetKey];
if (typeof instruction === "function") {
instruction = [, instruction];
}
const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) {
target[targetKey] = valueFn(source[sourceKey]);
}
return;
}
let [filter, value] = instructions[targetKey];
if (typeof value === "function") {
let _value;
const defaultFilterPassed = filter === void 0 && (_value = value()) != null;
const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter;
if (defaultFilterPassed) {
target[targetKey] = _value;
} else if (customFilterPassed) {
target[targetKey] = value();
}
} else {
const defaultFilterPassed = filter === void 0 && value != null;
const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter;
if (defaultFilterPassed || customFilterPassed) {
target[targetKey] = value;
}
}
}, "applyInstruction");
nonNullish = /* @__PURE__ */ __name((_4) => _4 != null, "nonNullish");
pass = /* @__PURE__ */ __name((_4) => _4, "pass");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/quote-header.js
function quoteHeader(part) {
if (part.includes(",") || part.includes('"')) {
part = `"${part.replace(/"/g, '\\"')}"`;
}
return part;
}
var init_quote_header = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/quote-header.js"() {
init_import_meta_url();
__name(quoteHeader, "quoteHeader");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/resolve-path.js
var init_resolve_path2 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/resolve-path.js"() {
init_import_meta_url();
init_protocols();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/ser-utils.js
var serializeDateTime;
var init_ser_utils = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/ser-utils.js"() {
init_import_meta_url();
serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/serde-json.js
var _json;
var init_serde_json = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/serde-json.js"() {
init_import_meta_url();
_json = /* @__PURE__ */ __name((obj) => {
if (obj == null) {
return {};
}
if (Array.isArray(obj)) {
return obj.filter((_4) => _4 != null).map(_json);
}
if (typeof obj === "object") {
const target = {};
for (const key of Object.keys(obj)) {
if (obj[key] == null) {
continue;
}
target[key] = _json(obj[key]);
}
return target;
}
return obj;
}, "_json");
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/split-every.js
var init_split_every = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/split-every.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/split-header.js
var init_split_header = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/split-header.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/index.js
var init_dist_es20 = __esm({
"../../node_modules/.pnpm/@smithy+smithy-client@3.7.0/node_modules/@smithy/smithy-client/dist-es/index.js"() {
init_import_meta_url();
init_client6();
init_collect_stream_body2();
init_command4();
init_constants9();
init_create_aggregated_client();
init_date_utils();
init_default_error_handler();
init_defaults_mode();
init_emitWarningIfUnsupportedVersion2();
init_exceptions();
init_extended_encode_uri_component2();
init_extensions3();
init_get_array_if_single_item();
init_get_value_from_text_node();
init_is_serializable_header_value();
init_lazy_json();
init_NoOpLogger();
init_object_mapping();
init_parse_utils();
init_quote_header();
init_resolve_path2();
init_ser_utils();
init_serde_json();
init_split_every();
init_split_header();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
var init_awsExpectUnion = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() {
init_import_meta_url();
init_dist_es20();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
var collectBodyString;
var init_common2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() {
init_import_meta_url();
init_dist_es20();
collectBodyString = /* @__PURE__ */ __name((streamBody, context2) => collectBody(streamBody, context2).then((body) => context2.utf8Encoder(body)), "collectBodyString");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
var init_parseJsonBody = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() {
init_import_meta_url();
init_common2();
parseJsonBody = /* @__PURE__ */ __name((streamBody, context2) => collectBodyString(streamBody, context2).then((encoded) => {
if (encoded.length) {
try {
return JSON.parse(encoded);
} catch (e7) {
if (e7?.name === "SyntaxError") {
Object.defineProperty(e7, "$responseBodyText", {
value: encoded
});
}
throw e7;
}
}
return {};
}), "parseJsonBody");
parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context2) => {
const value = await parseJsonBody(errorBody, context2);
value.message = value.message ?? value.Message;
return value;
}, "parseJsonErrorBody");
loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => {
const findKey2 = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k6) => k6.toLowerCase() === key.toLowerCase()), "findKey");
const sanitizeErrorCode = /* @__PURE__ */ __name((rawValue) => {
let cleanValue = rawValue;
if (typeof cleanValue === "number") {
cleanValue = cleanValue.toString();
}
if (cleanValue.indexOf(",") >= 0) {
cleanValue = cleanValue.split(",")[0];
}
if (cleanValue.indexOf(":") >= 0) {
cleanValue = cleanValue.split(":")[0];
}
if (cleanValue.indexOf("#") >= 0) {
cleanValue = cleanValue.split("#")[1];
}
return cleanValue;
}, "sanitizeErrorCode");
const headerKey = findKey2(output.headers, "x-amzn-errortype");
if (headerKey !== void 0) {
return sanitizeErrorCode(output.headers[headerKey]);
}
if (data.code !== void 0) {
return sanitizeErrorCode(data.code);
}
if (data["__type"] !== void 0) {
return sanitizeErrorCode(data["__type"]);
}
}, "loadRestJsonErrorCode");
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js
var require_util9 = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports2) {
"use strict";
init_import_meta_url();
var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
var regexName = new RegExp("^" + nameRegexp + "$");
var getAllMatches = /* @__PURE__ */ __name(function(string, regex2) {
const matches = [];
let match2 = regex2.exec(string);
while (match2) {
const allmatches = [];
allmatches.startIndex = regex2.lastIndex - match2[0].length;
const len = match2.length;
for (let index = 0; index < len; index++) {
allmatches.push(match2[index]);
}
matches.push(allmatches);
match2 = regex2.exec(string);
}
return matches;
}, "getAllMatches");
var isName = /* @__PURE__ */ __name(function(string) {
const match2 = regexName.exec(string);
return !(match2 === null || typeof match2 === "undefined");
}, "isName");
exports2.isExist = function(v7) {
return typeof v7 !== "undefined";
};
exports2.isEmptyObject = function(obj) {
return Object.keys(obj).length === 0;
};
exports2.merge = function(target, a5, arrayMode) {
if (a5) {
const keys = Object.keys(a5);
const len = keys.length;
for (let i5 = 0; i5 < len; i5++) {
if (arrayMode === "strict") {
target[keys[i5]] = [a5[keys[i5]]];
} else {
target[keys[i5]] = a5[keys[i5]];
}
}
}
};
exports2.getValue = function(v7) {
if (exports2.isExist(v7)) {
return v7;
} else {
return "";
}
};
exports2.isName = isName;
exports2.getAllMatches = getAllMatches;
exports2.nameRegexp = nameRegexp;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js
var require_validator = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports2) {
"use strict";
init_import_meta_url();
var util3 = require_util9();
var defaultOptions3 = {
allowBooleanAttributes: false,
//A tag can have attributes without any value
unpairedTags: []
};
exports2.validate = function(xmlData, options) {
options = Object.assign({}, defaultOptions3, options);
const tags = [];
let tagFound = false;
let reachedRoot = false;
if (xmlData[0] === "\uFEFF") {
xmlData = xmlData.substr(1);
}
for (let i5 = 0; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "<" && xmlData[i5 + 1] === "?") {
i5 += 2;
i5 = readPI(xmlData, i5);
if (i5.err) return i5;
} else if (xmlData[i5] === "<") {
let tagStartPos = i5;
i5++;
if (xmlData[i5] === "!") {
i5 = readCommentAndCDATA(xmlData, i5);
continue;
} else {
let closingTag = false;
if (xmlData[i5] === "/") {
closingTag = true;
i5++;
}
let tagName = "";
for (; i5 < xmlData.length && xmlData[i5] !== ">" && xmlData[i5] !== " " && xmlData[i5] !== " " && xmlData[i5] !== "\n" && xmlData[i5] !== "\r"; i5++) {
tagName += xmlData[i5];
}
tagName = tagName.trim();
if (tagName[tagName.length - 1] === "/") {
tagName = tagName.substring(0, tagName.length - 1);
i5--;
}
if (!validateTagName(tagName)) {
let msg;
if (tagName.trim().length === 0) {
msg = "Invalid space after '<'.";
} else {
msg = "Tag '" + tagName + "' is an invalid name.";
}
return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i5));
}
const result = readAttributeStr(xmlData, i5);
if (result === false) {
return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i5));
}
let attrStr = result.value;
i5 = result.index;
if (attrStr[attrStr.length - 1] === "/") {
const attrStrStart = i5 - attrStr.length;
attrStr = attrStr.substring(0, attrStr.length - 1);
const isValid2 = validateAttributeString(attrStr, options);
if (isValid2 === true) {
tagFound = true;
} else {
return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
}
} else if (closingTag) {
if (!result.tagClosed) {
return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i5));
} else if (attrStr.trim().length > 0) {
return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
} else if (tags.length === 0) {
return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
} else {
const otg = tags.pop();
if (tagName !== otg.tagName) {
let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
return getErrorObject(
"InvalidTag",
"Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
getLineNumberForPosition(xmlData, tagStartPos)
);
}
if (tags.length == 0) {
reachedRoot = true;
}
}
} else {
const isValid2 = validateAttributeString(attrStr, options);
if (isValid2 !== true) {
return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i5 - attrStr.length + isValid2.err.line));
}
if (reachedRoot === true) {
return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i5));
} else if (options.unpairedTags.indexOf(tagName) !== -1) {
} else {
tags.push({ tagName, tagStartPos });
}
tagFound = true;
}
for (i5++; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "<") {
if (xmlData[i5 + 1] === "!") {
i5++;
i5 = readCommentAndCDATA(xmlData, i5);
continue;
} else if (xmlData[i5 + 1] === "?") {
i5 = readPI(xmlData, ++i5);
if (i5.err) return i5;
} else {
break;
}
} else if (xmlData[i5] === "&") {
const afterAmp = validateAmpersand(xmlData, i5);
if (afterAmp == -1)
return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i5));
i5 = afterAmp;
} else {
if (reachedRoot === true && !isWhiteSpace2(xmlData[i5])) {
return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i5));
}
}
}
if (xmlData[i5] === "<") {
i5--;
}
}
} else {
if (isWhiteSpace2(xmlData[i5])) {
continue;
}
return getErrorObject("InvalidChar", "char '" + xmlData[i5] + "' is not expected.", getLineNumberForPosition(xmlData, i5));
}
}
if (!tagFound) {
return getErrorObject("InvalidXml", "Start tag expected.", 1);
} else if (tags.length == 1) {
return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
} else if (tags.length > 0) {
return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t7) => t7.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
}
return true;
};
function isWhiteSpace2(char) {
return char === " " || char === " " || char === "\n" || char === "\r";
}
__name(isWhiteSpace2, "isWhiteSpace");
function readPI(xmlData, i5) {
const start = i5;
for (; i5 < xmlData.length; i5++) {
if (xmlData[i5] == "?" || xmlData[i5] == " ") {
const tagname = xmlData.substr(start, i5 - start);
if (i5 > 5 && tagname === "xml") {
return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i5));
} else if (xmlData[i5] == "?" && xmlData[i5 + 1] == ">") {
i5++;
break;
} else {
continue;
}
}
}
return i5;
}
__name(readPI, "readPI");
function readCommentAndCDATA(xmlData, i5) {
if (xmlData.length > i5 + 5 && xmlData[i5 + 1] === "-" && xmlData[i5 + 2] === "-") {
for (i5 += 3; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "-" && xmlData[i5 + 1] === "-" && xmlData[i5 + 2] === ">") {
i5 += 2;
break;
}
}
} else if (xmlData.length > i5 + 8 && xmlData[i5 + 1] === "D" && xmlData[i5 + 2] === "O" && xmlData[i5 + 3] === "C" && xmlData[i5 + 4] === "T" && xmlData[i5 + 5] === "Y" && xmlData[i5 + 6] === "P" && xmlData[i5 + 7] === "E") {
let angleBracketsCount = 1;
for (i5 += 8; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "<") {
angleBracketsCount++;
} else if (xmlData[i5] === ">") {
angleBracketsCount--;
if (angleBracketsCount === 0) {
break;
}
}
}
} else if (xmlData.length > i5 + 9 && xmlData[i5 + 1] === "[" && xmlData[i5 + 2] === "C" && xmlData[i5 + 3] === "D" && xmlData[i5 + 4] === "A" && xmlData[i5 + 5] === "T" && xmlData[i5 + 6] === "A" && xmlData[i5 + 7] === "[") {
for (i5 += 8; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "]" && xmlData[i5 + 1] === "]" && xmlData[i5 + 2] === ">") {
i5 += 2;
break;
}
}
}
return i5;
}
__name(readCommentAndCDATA, "readCommentAndCDATA");
var doubleQuote = '"';
var singleQuote = "'";
function readAttributeStr(xmlData, i5) {
let attrStr = "";
let startChar = "";
let tagClosed = false;
for (; i5 < xmlData.length; i5++) {
if (xmlData[i5] === doubleQuote || xmlData[i5] === singleQuote) {
if (startChar === "") {
startChar = xmlData[i5];
} else if (startChar !== xmlData[i5]) {
} else {
startChar = "";
}
} else if (xmlData[i5] === ">") {
if (startChar === "") {
tagClosed = true;
break;
}
}
attrStr += xmlData[i5];
}
if (startChar !== "") {
return false;
}
return {
value: attrStr,
index: i5,
tagClosed
};
}
__name(readAttributeStr, "readAttributeStr");
var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
function validateAttributeString(attrStr, options) {
const matches = util3.getAllMatches(attrStr, validAttrStrRegxp);
const attrNames = {};
for (let i5 = 0; i5 < matches.length; i5++) {
if (matches[i5][1].length === 0) {
return getErrorObject("InvalidAttr", "Attribute '" + matches[i5][2] + "' has no space in starting.", getPositionFromMatch(matches[i5]));
} else if (matches[i5][3] !== void 0 && matches[i5][4] === void 0) {
return getErrorObject("InvalidAttr", "Attribute '" + matches[i5][2] + "' is without value.", getPositionFromMatch(matches[i5]));
} else if (matches[i5][3] === void 0 && !options.allowBooleanAttributes) {
return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i5][2] + "' is not allowed.", getPositionFromMatch(matches[i5]));
}
const attrName = matches[i5][2];
if (!validateAttrName(attrName)) {
return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i5]));
}
if (!attrNames.hasOwnProperty(attrName)) {
attrNames[attrName] = 1;
} else {
return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i5]));
}
}
return true;
}
__name(validateAttributeString, "validateAttributeString");
function validateNumberAmpersand(xmlData, i5) {
let re = /\d/;
if (xmlData[i5] === "x") {
i5++;
re = /[\da-fA-F]/;
}
for (; i5 < xmlData.length; i5++) {
if (xmlData[i5] === ";")
return i5;
if (!xmlData[i5].match(re))
break;
}
return -1;
}
__name(validateNumberAmpersand, "validateNumberAmpersand");
function validateAmpersand(xmlData, i5) {
i5++;
if (xmlData[i5] === ";")
return -1;
if (xmlData[i5] === "#") {
i5++;
return validateNumberAmpersand(xmlData, i5);
}
let count = 0;
for (; i5 < xmlData.length; i5++, count++) {
if (xmlData[i5].match(/\w/) && count < 20)
continue;
if (xmlData[i5] === ";")
break;
return -1;
}
return i5;
}
__name(validateAmpersand, "validateAmpersand");
function getErrorObject(code, message, lineNumber) {
return {
err: {
code,
msg: message,
line: lineNumber.line || lineNumber,
col: lineNumber.col
}
};
}
__name(getErrorObject, "getErrorObject");
function validateAttrName(attrName) {
return util3.isName(attrName);
}
__name(validateAttrName, "validateAttrName");
function validateTagName(tagname) {
return util3.isName(tagname);
}
__name(validateTagName, "validateTagName");
function getLineNumberForPosition(xmlData, index) {
const lines = xmlData.substring(0, index).split(/\r?\n/);
return {
line: lines.length,
// column number is last line's length + 1, because column numbering starts at 1:
col: lines[lines.length - 1].length + 1
};
}
__name(getLineNumberForPosition, "getLineNumberForPosition");
function getPositionFromMatch(match2) {
return match2.startIndex + match2[1].length;
}
__name(getPositionFromMatch, "getPositionFromMatch");
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var require_OptionsBuilder = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) {
init_import_meta_url();
var defaultOptions3 = {
preserveOrder: false,
attributeNamePrefix: "@_",
attributesGroupName: false,
textNodeName: "#text",
ignoreAttributes: true,
removeNSPrefix: false,
// remove NS from tag name or attribute name if true
allowBooleanAttributes: false,
//a tag can have attributes without any value
//ignoreRootElement : false,
parseTagValue: true,
parseAttributeValue: false,
trimValues: true,
//Trim string values of tag and attributes
cdataPropName: false,
numberParseOptions: {
hex: true,
leadingZeros: true,
eNotation: true
},
tagValueProcessor: /* @__PURE__ */ __name(function(tagName, val2) {
return val2;
}, "tagValueProcessor"),
attributeValueProcessor: /* @__PURE__ */ __name(function(attrName, val2) {
return val2;
}, "attributeValueProcessor"),
stopNodes: [],
//nested tags will not be parsed even for errors
alwaysCreateTextNode: false,
isArray: /* @__PURE__ */ __name(() => false, "isArray"),
commentPropName: false,
unpairedTags: [],
processEntities: true,
htmlEntities: false,
ignoreDeclaration: false,
ignorePiTags: false,
transformTagName: false,
transformAttributeName: false,
updateTag: /* @__PURE__ */ __name(function(tagName, jPath, attrs) {
return tagName;
}, "updateTag")
// skipEmptyListItem: false
};
var buildOptions = /* @__PURE__ */ __name(function(options) {
return Object.assign({}, defaultOptions3, options);
}, "buildOptions");
exports2.buildOptions = buildOptions;
exports2.defaultOptions = defaultOptions3;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var require_xmlNode = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var XmlNode2 = class {
static {
__name(this, "XmlNode");
}
constructor(tagname) {
this.tagname = tagname;
this.child = [];
this[":@"] = {};
}
add(key, val2) {
if (key === "__proto__") key = "#__proto__";
this.child.push({ [key]: val2 });
}
addChild(node2) {
if (node2.tagname === "__proto__") node2.tagname = "#__proto__";
if (node2[":@"] && Object.keys(node2[":@"]).length > 0) {
this.child.push({ [node2.tagname]: node2.child, [":@"]: node2[":@"] });
} else {
this.child.push({ [node2.tagname]: node2.child });
}
}
};
module3.exports = XmlNode2;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
var require_DocTypeReader = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module3) {
init_import_meta_url();
var util3 = require_util9();
function readDocType(xmlData, i5) {
const entities = {};
if (xmlData[i5 + 3] === "O" && xmlData[i5 + 4] === "C" && xmlData[i5 + 5] === "T" && xmlData[i5 + 6] === "Y" && xmlData[i5 + 7] === "P" && xmlData[i5 + 8] === "E") {
i5 = i5 + 9;
let angleBracketsCount = 1;
let hasBody = false, comment = false;
let exp = "";
for (; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "<" && !comment) {
if (hasBody && isEntity(xmlData, i5)) {
i5 += 7;
[entityName, val, i5] = readEntityExp(xmlData, i5 + 1);
if (val.indexOf("&") === -1)
entities[validateEntityName(entityName)] = {
regx: RegExp(`&${entityName};`, "g"),
val
};
} else if (hasBody && isElement2(xmlData, i5)) i5 += 8;
else if (hasBody && isAttlist(xmlData, i5)) i5 += 8;
else if (hasBody && isNotation(xmlData, i5)) i5 += 9;
else if (isComment) comment = true;
else throw new Error("Invalid DOCTYPE");
angleBracketsCount++;
exp = "";
} else if (xmlData[i5] === ">") {
if (comment) {
if (xmlData[i5 - 1] === "-" && xmlData[i5 - 2] === "-") {
comment = false;
angleBracketsCount--;
}
} else {
angleBracketsCount--;
}
if (angleBracketsCount === 0) {
break;
}
} else if (xmlData[i5] === "[") {
hasBody = true;
} else {
exp += xmlData[i5];
}
}
if (angleBracketsCount !== 0) {
throw new Error(`Unclosed DOCTYPE`);
}
} else {
throw new Error(`Invalid Tag instead of DOCTYPE`);
}
return { entities, i: i5 };
}
__name(readDocType, "readDocType");
function readEntityExp(xmlData, i5) {
let entityName2 = "";
for (; i5 < xmlData.length && (xmlData[i5] !== "'" && xmlData[i5] !== '"'); i5++) {
entityName2 += xmlData[i5];
}
entityName2 = entityName2.trim();
if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported");
const startChar = xmlData[i5++];
let val2 = "";
for (; i5 < xmlData.length && xmlData[i5] !== startChar; i5++) {
val2 += xmlData[i5];
}
return [entityName2, val2, i5];
}
__name(readEntityExp, "readEntityExp");
function isComment(xmlData, i5) {
if (xmlData[i5 + 1] === "!" && xmlData[i5 + 2] === "-" && xmlData[i5 + 3] === "-") return true;
return false;
}
__name(isComment, "isComment");
function isEntity(xmlData, i5) {
if (xmlData[i5 + 1] === "!" && xmlData[i5 + 2] === "E" && xmlData[i5 + 3] === "N" && xmlData[i5 + 4] === "T" && xmlData[i5 + 5] === "I" && xmlData[i5 + 6] === "T" && xmlData[i5 + 7] === "Y") return true;
return false;
}
__name(isEntity, "isEntity");
function isElement2(xmlData, i5) {
if (xmlData[i5 + 1] === "!" && xmlData[i5 + 2] === "E" && xmlData[i5 + 3] === "L" && xmlData[i5 + 4] === "E" && xmlData[i5 + 5] === "M" && xmlData[i5 + 6] === "E" && xmlData[i5 + 7] === "N" && xmlData[i5 + 8] === "T") return true;
return false;
}
__name(isElement2, "isElement");
function isAttlist(xmlData, i5) {
if (xmlData[i5 + 1] === "!" && xmlData[i5 + 2] === "A" && xmlData[i5 + 3] === "T" && xmlData[i5 + 4] === "T" && xmlData[i5 + 5] === "L" && xmlData[i5 + 6] === "I" && xmlData[i5 + 7] === "S" && xmlData[i5 + 8] === "T") return true;
return false;
}
__name(isAttlist, "isAttlist");
function isNotation(xmlData, i5) {
if (xmlData[i5 + 1] === "!" && xmlData[i5 + 2] === "N" && xmlData[i5 + 3] === "O" && xmlData[i5 + 4] === "T" && xmlData[i5 + 5] === "A" && xmlData[i5 + 6] === "T" && xmlData[i5 + 7] === "I" && xmlData[i5 + 8] === "O" && xmlData[i5 + 9] === "N") return true;
return false;
}
__name(isNotation, "isNotation");
function validateEntityName(name2) {
if (util3.isName(name2))
return name2;
else
throw new Error(`Invalid entity name ${name2}`);
}
__name(validateEntityName, "validateEntityName");
module3.exports = readDocType;
}
});
// ../../node_modules/.pnpm/strnum@1.0.5/node_modules/strnum/strnum.js
var require_strnum = __commonJS({
"../../node_modules/.pnpm/strnum@1.0.5/node_modules/strnum/strnum.js"(exports2, module3) {
init_import_meta_url();
var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
if (!Number.parseInt && window.parseInt) {
Number.parseInt = window.parseInt;
}
if (!Number.parseFloat && window.parseFloat) {
Number.parseFloat = window.parseFloat;
}
var consider = {
hex: true,
leadingZeros: true,
decimalPoint: ".",
eNotation: true
//skipLike: /regex/
};
function toNumber(str, options = {}) {
options = Object.assign({}, consider, options);
if (!str || typeof str !== "string") return str;
let trimmedStr = str.trim();
if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
else if (options.hex && hexRegex.test(trimmedStr)) {
return Number.parseInt(trimmedStr, 16);
} else {
const match2 = numRegex.exec(trimmedStr);
if (match2) {
const sign = match2[1];
const leadingZeros = match2[2];
let numTrimmedByZeros = trimZeros(match2[3]);
const eNotation = match2[4] || match2[6];
if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str;
else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str;
else {
const num = Number(trimmedStr);
const numStr = "" + num;
if (numStr.search(/[eE]/) !== -1) {
if (options.eNotation) return num;
else return str;
} else if (eNotation) {
if (options.eNotation) return num;
else return str;
} else if (trimmedStr.indexOf(".") !== -1) {
if (numStr === "0" && numTrimmedByZeros === "") return num;
else if (numStr === numTrimmedByZeros) return num;
else if (sign && numStr === "-" + numTrimmedByZeros) return num;
else return str;
}
if (leadingZeros) {
if (numTrimmedByZeros === numStr) return num;
else if (sign + numTrimmedByZeros === numStr) return num;
else return str;
}
if (trimmedStr === numStr) return num;
else if (trimmedStr === sign + numStr) return num;
return str;
}
} else {
return str;
}
}
}
__name(toNumber, "toNumber");
function trimZeros(numStr) {
if (numStr && numStr.indexOf(".") !== -1) {
numStr = numStr.replace(/0+$/, "");
if (numStr === ".") numStr = "0";
else if (numStr[0] === ".") numStr = "0" + numStr;
else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1);
return numStr;
}
return numStr;
}
__name(trimZeros, "trimZeros");
module3.exports = toNumber;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
var require_OrderedObjParser = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var util3 = require_util9();
var xmlNode = require_xmlNode();
var readDocType = require_DocTypeReader();
var toNumber = require_strnum();
var OrderedObjParser = class {
static {
__name(this, "OrderedObjParser");
}
constructor(options) {
this.options = options;
this.currentNode = null;
this.tagsNodeStack = [];
this.docTypeEntities = {};
this.lastEntities = {
"apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
"gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
"lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
"quot": { regex: /&(quot|#34|#x22);/g, val: '"' }
};
this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
this.htmlEntities = {
"space": { regex: /&(nbsp|#160);/g, val: " " },
// "lt" : { regex: /&(lt|#60);/g, val: "<" },
// "gt" : { regex: /&(gt|#62);/g, val: ">" },
// "amp" : { regex: /&(amp|#38);/g, val: "&" },
// "quot" : { regex: /&(quot|#34);/g, val: "\"" },
// "apos" : { regex: /&(apos|#39);/g, val: "'" },
"cent": { regex: /&(cent|#162);/g, val: "\xA2" },
"pound": { regex: /&(pound|#163);/g, val: "\xA3" },
"yen": { regex: /&(yen|#165);/g, val: "\xA5" },
"euro": { regex: /&(euro|#8364);/g, val: "\u20AC" },
"copyright": { regex: /&(copy|#169);/g, val: "\xA9" },
"reg": { regex: /&(reg|#174);/g, val: "\xAE" },
"inr": { regex: /&(inr|#8377);/g, val: "\u20B9" },
"num_dec": { regex: /&#([0-9]{1,7});/g, val: /* @__PURE__ */ __name((_4, str) => String.fromCharCode(Number.parseInt(str, 10)), "val") },
"num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: /* @__PURE__ */ __name((_4, str) => String.fromCharCode(Number.parseInt(str, 16)), "val") }
};
this.addExternalEntities = addExternalEntities;
this.parseXml = parseXml;
this.parseTextData = parseTextData;
this.resolveNameSpace = resolveNameSpace;
this.buildAttributesMap = buildAttributesMap;
this.isItStopNode = isItStopNode;
this.replaceEntitiesValue = replaceEntitiesValue;
this.readStopNodeData = readStopNodeData;
this.saveTextToParentTag = saveTextToParentTag;
this.addChild = addChild;
}
};
function addExternalEntities(externalEntities) {
const entKeys = Object.keys(externalEntities);
for (let i5 = 0; i5 < entKeys.length; i5++) {
const ent = entKeys[i5];
this.lastEntities[ent] = {
regex: new RegExp("&" + ent + ";", "g"),
val: externalEntities[ent]
};
}
}
__name(addExternalEntities, "addExternalEntities");
function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
if (val2 !== void 0) {
if (this.options.trimValues && !dontTrim) {
val2 = val2.trim();
}
if (val2.length > 0) {
if (!escapeEntities) val2 = this.replaceEntitiesValue(val2);
const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
if (newval === null || newval === void 0) {
return val2;
} else if (typeof newval !== typeof val2 || newval !== val2) {
return newval;
} else if (this.options.trimValues) {
return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
} else {
const trimmedVal = val2.trim();
if (trimmedVal === val2) {
return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
} else {
return val2;
}
}
}
}
}
__name(parseTextData, "parseTextData");
function resolveNameSpace(tagname) {
if (this.options.removeNSPrefix) {
const tags = tagname.split(":");
const prefix = tagname.charAt(0) === "/" ? "/" : "";
if (tags[0] === "xmlns") {
return "";
}
if (tags.length === 2) {
tagname = prefix + tags[1];
}
}
return tagname;
}
__name(resolveNameSpace, "resolveNameSpace");
var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
function buildAttributesMap(attrStr, jPath, tagName) {
if (!this.options.ignoreAttributes && typeof attrStr === "string") {
const matches = util3.getAllMatches(attrStr, attrsRegx);
const len = matches.length;
const attrs = {};
for (let i5 = 0; i5 < len; i5++) {
const attrName = this.resolveNameSpace(matches[i5][1]);
let oldVal = matches[i5][4];
let aName = this.options.attributeNamePrefix + attrName;
if (attrName.length) {
if (this.options.transformAttributeName) {
aName = this.options.transformAttributeName(aName);
}
if (aName === "__proto__") aName = "#__proto__";
if (oldVal !== void 0) {
if (this.options.trimValues) {
oldVal = oldVal.trim();
}
oldVal = this.replaceEntitiesValue(oldVal);
const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
if (newVal === null || newVal === void 0) {
attrs[aName] = oldVal;
} else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
attrs[aName] = newVal;
} else {
attrs[aName] = parseValue(
oldVal,
this.options.parseAttributeValue,
this.options.numberParseOptions
);
}
} else if (this.options.allowBooleanAttributes) {
attrs[aName] = true;
}
}
}
if (!Object.keys(attrs).length) {
return;
}
if (this.options.attributesGroupName) {
const attrCollection = {};
attrCollection[this.options.attributesGroupName] = attrs;
return attrCollection;
}
return attrs;
}
}
__name(buildAttributesMap, "buildAttributesMap");
var parseXml = /* @__PURE__ */ __name(function(xmlData) {
xmlData = xmlData.replace(/\r\n?/g, "\n");
const xmlObj = new xmlNode("!xml");
let currentNode = xmlObj;
let textData = "";
let jPath = "";
for (let i5 = 0; i5 < xmlData.length; i5++) {
const ch2 = xmlData[i5];
if (ch2 === "<") {
if (xmlData[i5 + 1] === "/") {
const closeIndex = findClosingIndex(xmlData, ">", i5, "Closing Tag is not closed.");
let tagName = xmlData.substring(i5 + 2, closeIndex).trim();
if (this.options.removeNSPrefix) {
const colonIndex = tagName.indexOf(":");
if (colonIndex !== -1) {
tagName = tagName.substr(colonIndex + 1);
}
}
if (this.options.transformTagName) {
tagName = this.options.transformTagName(tagName);
}
if (currentNode) {
textData = this.saveTextToParentTag(textData, currentNode, jPath);
}
const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
}
let propIndex = 0;
if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1);
this.tagsNodeStack.pop();
} else {
propIndex = jPath.lastIndexOf(".");
}
jPath = jPath.substring(0, propIndex);
currentNode = this.tagsNodeStack.pop();
textData = "";
i5 = closeIndex;
} else if (xmlData[i5 + 1] === "?") {
let tagData = readTagExp(xmlData, i5, false, "?>");
if (!tagData) throw new Error("Pi Tag is not closed.");
textData = this.saveTextToParentTag(textData, currentNode, jPath);
if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) {
} else {
const childNode = new xmlNode(tagData.tagName);
childNode.add(this.options.textNodeName, "");
if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
}
this.addChild(currentNode, childNode, jPath);
}
i5 = tagData.closeIndex + 1;
} else if (xmlData.substr(i5 + 1, 3) === "!--") {
const endIndex = findClosingIndex(xmlData, "-->", i5 + 4, "Comment is not closed.");
if (this.options.commentPropName) {
const comment = xmlData.substring(i5 + 4, endIndex - 2);
textData = this.saveTextToParentTag(textData, currentNode, jPath);
currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
}
i5 = endIndex;
} else if (xmlData.substr(i5 + 1, 2) === "!D") {
const result = readDocType(xmlData, i5);
this.docTypeEntities = result.entities;
i5 = result.i;
} else if (xmlData.substr(i5 + 1, 2) === "![") {
const closeIndex = findClosingIndex(xmlData, "]]>", i5, "CDATA is not closed.") - 2;
const tagExp = xmlData.substring(i5 + 9, closeIndex);
textData = this.saveTextToParentTag(textData, currentNode, jPath);
let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
if (val2 == void 0) val2 = "";
if (this.options.cdataPropName) {
currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
} else {
currentNode.add(this.options.textNodeName, val2);
}
i5 = closeIndex + 2;
} else {
let result = readTagExp(xmlData, i5, this.options.removeNSPrefix);
let tagName = result.tagName;
const rawTagName = result.rawTagName;
let tagExp = result.tagExp;
let attrExpPresent = result.attrExpPresent;
let closeIndex = result.closeIndex;
if (this.options.transformTagName) {
tagName = this.options.transformTagName(tagName);
}
if (currentNode && textData) {
if (currentNode.tagname !== "!xml") {
textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
}
}
const lastTag = currentNode;
if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
currentNode = this.tagsNodeStack.pop();
jPath = jPath.substring(0, jPath.lastIndexOf("."));
}
if (tagName !== xmlObj.tagname) {
jPath += jPath ? "." + tagName : tagName;
}
if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
let tagContent = "";
if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
if (tagName[tagName.length - 1] === "/") {
tagName = tagName.substr(0, tagName.length - 1);
jPath = jPath.substr(0, jPath.length - 1);
tagExp = tagName;
} else {
tagExp = tagExp.substr(0, tagExp.length - 1);
}
i5 = result.closeIndex;
} else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
i5 = result.closeIndex;
} else {
const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
if (!result2) throw new Error(`Unexpected end of ${rawTagName}`);
i5 = result2.i;
tagContent = result2.tagContent;
}
const childNode = new xmlNode(tagName);
if (tagName !== tagExp && attrExpPresent) {
childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
}
if (tagContent) {
tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
}
jPath = jPath.substr(0, jPath.lastIndexOf("."));
childNode.add(this.options.textNodeName, tagContent);
this.addChild(currentNode, childNode, jPath);
} else {
if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
if (tagName[tagName.length - 1] === "/") {
tagName = tagName.substr(0, tagName.length - 1);
jPath = jPath.substr(0, jPath.length - 1);
tagExp = tagName;
} else {
tagExp = tagExp.substr(0, tagExp.length - 1);
}
if (this.options.transformTagName) {
tagName = this.options.transformTagName(tagName);
}
const childNode = new xmlNode(tagName);
if (tagName !== tagExp && attrExpPresent) {
childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
}
this.addChild(currentNode, childNode, jPath);
jPath = jPath.substr(0, jPath.lastIndexOf("."));
} else {
const childNode = new xmlNode(tagName);
this.tagsNodeStack.push(currentNode);
if (tagName !== tagExp && attrExpPresent) {
childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
}
this.addChild(currentNode, childNode, jPath);
currentNode = childNode;
}
textData = "";
i5 = closeIndex;
}
}
} else {
textData += xmlData[i5];
}
}
return xmlObj.child;
}, "parseXml");
function addChild(currentNode, childNode, jPath) {
const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
if (result === false) {
} else if (typeof result === "string") {
childNode.tagname = result;
currentNode.addChild(childNode);
} else {
currentNode.addChild(childNode);
}
}
__name(addChild, "addChild");
var replaceEntitiesValue = /* @__PURE__ */ __name(function(val2) {
if (this.options.processEntities) {
for (let entityName2 in this.docTypeEntities) {
const entity = this.docTypeEntities[entityName2];
val2 = val2.replace(entity.regx, entity.val);
}
for (let entityName2 in this.lastEntities) {
const entity = this.lastEntities[entityName2];
val2 = val2.replace(entity.regex, entity.val);
}
if (this.options.htmlEntities) {
for (let entityName2 in this.htmlEntities) {
const entity = this.htmlEntities[entityName2];
val2 = val2.replace(entity.regex, entity.val);
}
}
val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
}
return val2;
}, "replaceEntitiesValue");
function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
if (textData) {
if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0;
textData = this.parseTextData(
textData,
currentNode.tagname,
jPath,
false,
currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
isLeafNode
);
if (textData !== void 0 && textData !== "")
currentNode.add(this.options.textNodeName, textData);
textData = "";
}
return textData;
}
__name(saveTextToParentTag, "saveTextToParentTag");
function isItStopNode(stopNodes, jPath, currentTagName) {
const allNodesExp = "*." + currentTagName;
for (const stopNodePath in stopNodes) {
const stopNodeExp = stopNodes[stopNodePath];
if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true;
}
return false;
}
__name(isItStopNode, "isItStopNode");
function tagExpWithClosingIndex(xmlData, i5, closingChar = ">") {
let attrBoundary;
let tagExp = "";
for (let index = i5; index < xmlData.length; index++) {
let ch2 = xmlData[index];
if (attrBoundary) {
if (ch2 === attrBoundary) attrBoundary = "";
} else if (ch2 === '"' || ch2 === "'") {
attrBoundary = ch2;
} else if (ch2 === closingChar[0]) {
if (closingChar[1]) {
if (xmlData[index + 1] === closingChar[1]) {
return {
data: tagExp,
index
};
}
} else {
return {
data: tagExp,
index
};
}
} else if (ch2 === " ") {
ch2 = " ";
}
tagExp += ch2;
}
}
__name(tagExpWithClosingIndex, "tagExpWithClosingIndex");
function findClosingIndex(xmlData, str, i5, errMsg) {
const closingIndex = xmlData.indexOf(str, i5);
if (closingIndex === -1) {
throw new Error(errMsg);
} else {
return closingIndex + str.length - 1;
}
}
__name(findClosingIndex, "findClosingIndex");
function readTagExp(xmlData, i5, removeNSPrefix, closingChar = ">") {
const result = tagExpWithClosingIndex(xmlData, i5 + 1, closingChar);
if (!result) return;
let tagExp = result.data;
const closeIndex = result.index;
const separatorIndex = tagExp.search(/\s/);
let tagName = tagExp;
let attrExpPresent = true;
if (separatorIndex !== -1) {
tagName = tagExp.substring(0, separatorIndex);
tagExp = tagExp.substring(separatorIndex + 1).trimStart();
}
const rawTagName = tagName;
if (removeNSPrefix) {
const colonIndex = tagName.indexOf(":");
if (colonIndex !== -1) {
tagName = tagName.substr(colonIndex + 1);
attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
}
}
return {
tagName,
tagExp,
closeIndex,
attrExpPresent,
rawTagName
};
}
__name(readTagExp, "readTagExp");
function readStopNodeData(xmlData, tagName, i5) {
const startIndex = i5;
let openTagCount = 1;
for (; i5 < xmlData.length; i5++) {
if (xmlData[i5] === "<") {
if (xmlData[i5 + 1] === "/") {
const closeIndex = findClosingIndex(xmlData, ">", i5, `${tagName} is not closed`);
let closeTagName = xmlData.substring(i5 + 2, closeIndex).trim();
if (closeTagName === tagName) {
openTagCount--;
if (openTagCount === 0) {
return {
tagContent: xmlData.substring(startIndex, i5),
i: closeIndex
};
}
}
i5 = closeIndex;
} else if (xmlData[i5 + 1] === "?") {
const closeIndex = findClosingIndex(xmlData, "?>", i5 + 1, "StopNode is not closed.");
i5 = closeIndex;
} else if (xmlData.substr(i5 + 1, 3) === "!--") {
const closeIndex = findClosingIndex(xmlData, "-->", i5 + 3, "StopNode is not closed.");
i5 = closeIndex;
} else if (xmlData.substr(i5 + 1, 2) === "![") {
const closeIndex = findClosingIndex(xmlData, "]]>", i5, "StopNode is not closed.") - 2;
i5 = closeIndex;
} else {
const tagData = readTagExp(xmlData, i5, ">");
if (tagData) {
const openTagName = tagData && tagData.tagName;
if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
openTagCount++;
}
i5 = tagData.closeIndex;
}
}
}
}
}
__name(readStopNodeData, "readStopNodeData");
function parseValue(val2, shouldParse, options) {
if (shouldParse && typeof val2 === "string") {
const newval = val2.trim();
if (newval === "true") return true;
else if (newval === "false") return false;
else return toNumber(val2, options);
} else {
if (util3.isExist(val2)) {
return val2;
} else {
return "";
}
}
}
__name(parseValue, "parseValue");
module3.exports = OrderedObjParser;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js
var require_node2json = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) {
"use strict";
init_import_meta_url();
function prettify(node2, options) {
return compress(node2, options);
}
__name(prettify, "prettify");
function compress(arr, options, jPath) {
let text;
const compressedObj = {};
for (let i5 = 0; i5 < arr.length; i5++) {
const tagObj = arr[i5];
const property = propName(tagObj);
let newJpath = "";
if (jPath === void 0) newJpath = property;
else newJpath = jPath + "." + property;
if (property === options.textNodeName) {
if (text === void 0) text = tagObj[property];
else text += "" + tagObj[property];
} else if (property === void 0) {
continue;
} else if (tagObj[property]) {
let val2 = compress(tagObj[property], options, newJpath);
const isLeaf = isLeafTag(val2, options);
if (tagObj[":@"]) {
assignAttributes(val2, tagObj[":@"], newJpath, options);
} else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) {
val2 = val2[options.textNodeName];
} else if (Object.keys(val2).length === 0) {
if (options.alwaysCreateTextNode) val2[options.textNodeName] = "";
else val2 = "";
}
if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) {
if (!Array.isArray(compressedObj[property])) {
compressedObj[property] = [compressedObj[property]];
}
compressedObj[property].push(val2);
} else {
if (options.isArray(property, newJpath, isLeaf)) {
compressedObj[property] = [val2];
} else {
compressedObj[property] = val2;
}
}
}
}
if (typeof text === "string") {
if (text.length > 0) compressedObj[options.textNodeName] = text;
} else if (text !== void 0) compressedObj[options.textNodeName] = text;
return compressedObj;
}
__name(compress, "compress");
function propName(obj) {
const keys = Object.keys(obj);
for (let i5 = 0; i5 < keys.length; i5++) {
const key = keys[i5];
if (key !== ":@") return key;
}
}
__name(propName, "propName");
function assignAttributes(obj, attrMap, jpath, options) {
if (attrMap) {
const keys = Object.keys(attrMap);
const len = keys.length;
for (let i5 = 0; i5 < len; i5++) {
const atrrName = keys[i5];
if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
obj[atrrName] = [attrMap[atrrName]];
} else {
obj[atrrName] = attrMap[atrrName];
}
}
}
}
__name(assignAttributes, "assignAttributes");
function isLeafTag(obj, options) {
const { textNodeName } = options;
const propCount = Object.keys(obj).length;
if (propCount === 0) {
return true;
}
if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
return true;
}
return false;
}
__name(isLeafTag, "isLeafTag");
exports2.prettify = prettify;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
var require_XMLParser = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module3) {
init_import_meta_url();
var { buildOptions } = require_OptionsBuilder();
var OrderedObjParser = require_OrderedObjParser();
var { prettify } = require_node2json();
var validator = require_validator();
var XMLParser2 = class {
static {
__name(this, "XMLParser");
}
constructor(options) {
this.externalEntities = {};
this.options = buildOptions(options);
}
/**
* Parse XML dats to JS object
* @param {string|Buffer} xmlData
* @param {boolean|Object} validationOption
*/
parse(xmlData, validationOption) {
if (typeof xmlData === "string") {
} else if (xmlData.toString) {
xmlData = xmlData.toString();
} else {
throw new Error("XML data is accepted in String or Bytes[] form.");
}
if (validationOption) {
if (validationOption === true) validationOption = {};
const result = validator.validate(xmlData, validationOption);
if (result !== true) {
throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
}
}
const orderedObjParser = new OrderedObjParser(this.options);
orderedObjParser.addExternalEntities(this.externalEntities);
const orderedResult = orderedObjParser.parseXml(xmlData);
if (this.options.preserveOrder || orderedResult === void 0) return orderedResult;
else return prettify(orderedResult, this.options);
}
/**
* Add Entity which is not by default supported by this library
* @param {string} key
* @param {string} value
*/
addEntity(key, value) {
if (value.indexOf("&") !== -1) {
throw new Error("Entity value can't have '&'");
} else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");
} else if (value === "&") {
throw new Error("An entity with value '&' is not permitted");
} else {
this.externalEntities[key] = value;
}
}
};
module3.exports = XMLParser2;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
var require_orderedJs2Xml = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module3) {
init_import_meta_url();
var EOL = "\n";
function toXml(jArray, options) {
let indentation = "";
if (options.format && options.indentBy.length > 0) {
indentation = EOL;
}
return arrToStr(jArray, options, "", indentation);
}
__name(toXml, "toXml");
function arrToStr(arr, options, jPath, indentation) {
let xmlStr = "";
let isPreviousElementTag = false;
for (let i5 = 0; i5 < arr.length; i5++) {
const tagObj = arr[i5];
const tagName = propName(tagObj);
if (tagName === void 0) continue;
let newJPath = "";
if (jPath.length === 0) newJPath = tagName;
else newJPath = `${jPath}.${tagName}`;
if (tagName === options.textNodeName) {
let tagText = tagObj[tagName];
if (!isStopNode(newJPath, options)) {
tagText = options.tagValueProcessor(tagName, tagText);
tagText = replaceEntitiesValue(tagText, options);
}
if (isPreviousElementTag) {
xmlStr += indentation;
}
xmlStr += tagText;
isPreviousElementTag = false;
continue;
} else if (tagName === options.cdataPropName) {
if (isPreviousElementTag) {
xmlStr += indentation;
}
xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
isPreviousElementTag = false;
continue;
} else if (tagName === options.commentPropName) {
xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
isPreviousElementTag = true;
continue;
} else if (tagName[0] === "?") {
const attStr2 = attr_to_str(tagObj[":@"], options);
const tempInd = tagName === "?xml" ? "" : indentation;
let piTextNodeName = tagObj[tagName][0][options.textNodeName];
piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "";
xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`;
isPreviousElementTag = true;
continue;
}
let newIdentation = indentation;
if (newIdentation !== "") {
newIdentation += options.indentBy;
}
const attStr = attr_to_str(tagObj[":@"], options);
const tagStart = indentation + `<${tagName}${attStr}`;
const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
if (options.unpairedTags.indexOf(tagName) !== -1) {
if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
else xmlStr += tagStart + "/>";
} else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
xmlStr += tagStart + "/>";
} else if (tagValue && tagValue.endsWith(">")) {
xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
} else {
xmlStr += tagStart + ">";
if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
xmlStr += indentation + options.indentBy + tagValue + indentation;
} else {
xmlStr += tagValue;
}
xmlStr += `</${tagName}>`;
}
isPreviousElementTag = true;
}
return xmlStr;
}
__name(arrToStr, "arrToStr");
function propName(obj) {
const keys = Object.keys(obj);
for (let i5 = 0; i5 < keys.length; i5++) {
const key = keys[i5];
if (!obj.hasOwnProperty(key)) continue;
if (key !== ":@") return key;
}
}
__name(propName, "propName");
function attr_to_str(attrMap, options) {
let attrStr = "";
if (attrMap && !options.ignoreAttributes) {
for (let attr in attrMap) {
if (!attrMap.hasOwnProperty(attr)) continue;
let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
attrVal = replaceEntitiesValue(attrVal, options);
if (attrVal === true && options.suppressBooleanAttributes) {
attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
} else {
attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
}
}
}
return attrStr;
}
__name(attr_to_str, "attr_to_str");
function isStopNode(jPath, options) {
jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
for (let index in options.stopNodes) {
if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
}
return false;
}
__name(isStopNode, "isStopNode");
function replaceEntitiesValue(textValue, options) {
if (textValue && textValue.length > 0 && options.processEntities) {
for (let i5 = 0; i5 < options.entities.length; i5++) {
const entity = options.entities[i5];
textValue = textValue.replace(entity.regex, entity.val);
}
}
return textValue;
}
__name(replaceEntitiesValue, "replaceEntitiesValue");
module3.exports = toXml;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
var require_json2xml = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var buildFromOrderedJs = require_orderedJs2Xml();
var defaultOptions3 = {
attributeNamePrefix: "@_",
attributesGroupName: false,
textNodeName: "#text",
ignoreAttributes: true,
cdataPropName: false,
format: false,
indentBy: " ",
suppressEmptyNode: false,
suppressUnpairedNode: true,
suppressBooleanAttributes: true,
tagValueProcessor: /* @__PURE__ */ __name(function(key, a5) {
return a5;
}, "tagValueProcessor"),
attributeValueProcessor: /* @__PURE__ */ __name(function(attrName, a5) {
return a5;
}, "attributeValueProcessor"),
preserveOrder: false,
commentPropName: false,
unpairedTags: [],
entities: [
{ regex: new RegExp("&", "g"), val: "&" },
//it must be on top
{ regex: new RegExp(">", "g"), val: ">" },
{ regex: new RegExp("<", "g"), val: "<" },
{ regex: new RegExp("'", "g"), val: "'" },
{ regex: new RegExp('"', "g"), val: """ }
],
processEntities: true,
stopNodes: [],
// transformTagName: false,
// transformAttributeName: false,
oneListGroup: false
};
function Builder(options) {
this.options = Object.assign({}, defaultOptions3, options);
if (this.options.ignoreAttributes || this.options.attributesGroupName) {
this.isAttribute = function() {
return false;
};
} else {
this.attrPrefixLen = this.options.attributeNamePrefix.length;
this.isAttribute = isAttribute;
}
this.processTextOrObjNode = processTextOrObjNode;
if (this.options.format) {
this.indentate = indentate;
this.tagEndChar = ">\n";
this.newLine = "\n";
} else {
this.indentate = function() {
return "";
};
this.tagEndChar = ">";
this.newLine = "";
}
}
__name(Builder, "Builder");
Builder.prototype.build = function(jObj) {
if (this.options.preserveOrder) {
return buildFromOrderedJs(jObj, this.options);
} else {
if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
jObj = {
[this.options.arrayNodeName]: jObj
};
}
return this.j2x(jObj, 0).val;
}
};
Builder.prototype.j2x = function(jObj, level) {
let attrStr = "";
let val2 = "";
for (let key in jObj) {
if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
if (typeof jObj[key] === "undefined") {
if (this.isAttribute(key)) {
val2 += "";
}
} else if (jObj[key] === null) {
if (this.isAttribute(key)) {
val2 += "";
} else if (key[0] === "?") {
val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
} else {
val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
}
} else if (jObj[key] instanceof Date) {
val2 += this.buildTextValNode(jObj[key], key, "", level);
} else if (typeof jObj[key] !== "object") {
const attr = this.isAttribute(key);
if (attr) {
attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
} else {
if (key === this.options.textNodeName) {
let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
val2 += this.replaceEntitiesValue(newval);
} else {
val2 += this.buildTextValNode(jObj[key], key, "", level);
}
}
} else if (Array.isArray(jObj[key])) {
const arrLen = jObj[key].length;
let listTagVal = "";
let listTagAttr = "";
for (let j6 = 0; j6 < arrLen; j6++) {
const item = jObj[key][j6];
if (typeof item === "undefined") {
} else if (item === null) {
if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
} else if (typeof item === "object") {
if (this.options.oneListGroup) {
const result = this.j2x(item, level + 1);
listTagVal += result.val;
if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
listTagAttr += result.attrStr;
}
} else {
listTagVal += this.processTextOrObjNode(item, key, level);
}
} else {
if (this.options.oneListGroup) {
let textValue = this.options.tagValueProcessor(key, item);
textValue = this.replaceEntitiesValue(textValue);
listTagVal += textValue;
} else {
listTagVal += this.buildTextValNode(item, key, "", level);
}
}
}
if (this.options.oneListGroup) {
listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
}
val2 += listTagVal;
} else {
if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
const Ks = Object.keys(jObj[key]);
const L3 = Ks.length;
for (let j6 = 0; j6 < L3; j6++) {
attrStr += this.buildAttrPairStr(Ks[j6], "" + jObj[key][Ks[j6]]);
}
} else {
val2 += this.processTextOrObjNode(jObj[key], key, level);
}
}
}
return { attrStr, val: val2 };
};
Builder.prototype.buildAttrPairStr = function(attrName, val2) {
val2 = this.options.attributeValueProcessor(attrName, "" + val2);
val2 = this.replaceEntitiesValue(val2);
if (this.options.suppressBooleanAttributes && val2 === "true") {
return " " + attrName;
} else return " " + attrName + '="' + val2 + '"';
};
function processTextOrObjNode(object, key, level) {
const result = this.j2x(object, level + 1);
if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) {
return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
} else {
return this.buildObjectNode(result.val, key, result.attrStr, level);
}
}
__name(processTextOrObjNode, "processTextOrObjNode");
Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
if (val2 === "") {
if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
else {
return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
}
} else {
let tagEndExp = "</" + key + this.tagEndChar;
let piClosingChar = "";
if (key[0] === "?") {
piClosingChar = "?";
tagEndExp = "";
}
if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) {
return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp;
} else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
return this.indentate(level) + `<!--${val2}-->` + this.newLine;
} else {
return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
}
}
};
Builder.prototype.closeTag = function(key) {
let closeTag = "";
if (this.options.unpairedTags.indexOf(key) !== -1) {
if (!this.options.suppressUnpairedNode) closeTag = "/";
} else if (this.options.suppressEmptyNode) {
closeTag = "/";
} else {
closeTag = `></${key}`;
}
return closeTag;
};
Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
} else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
return this.indentate(level) + `<!--${val2}-->` + this.newLine;
} else if (key[0] === "?") {
return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
} else {
let textValue = this.options.tagValueProcessor(key, val2);
textValue = this.replaceEntitiesValue(textValue);
if (textValue === "") {
return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
} else {
return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
}
}
};
Builder.prototype.replaceEntitiesValue = function(textValue) {
if (textValue && textValue.length > 0 && this.options.processEntities) {
for (let i5 = 0; i5 < this.options.entities.length; i5++) {
const entity = this.options.entities[i5];
textValue = textValue.replace(entity.regex, entity.val);
}
}
return textValue;
};
function indentate(level) {
return this.options.indentBy.repeat(level);
}
__name(indentate, "indentate");
function isAttribute(name2) {
if (name2.startsWith(this.options.attributeNamePrefix) && name2 !== this.options.textNodeName) {
return name2.substr(this.attrPrefixLen);
} else {
return false;
}
}
__name(isAttribute, "isAttribute");
module3.exports = Builder;
}
});
// ../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js
var require_fxp = __commonJS({
"../../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var validator = require_validator();
var XMLParser2 = require_XMLParser();
var XMLBuilder = require_json2xml();
module3.exports = {
XMLParser: XMLParser2,
XMLValidator: validator,
XMLBuilder
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
var import_fast_xml_parser, parseXmlBody, parseXmlErrorBody, loadRestXmlErrorCode;
var init_parseXmlBody = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() {
init_import_meta_url();
init_dist_es20();
import_fast_xml_parser = __toESM(require_fxp());
init_common2();
parseXmlBody = /* @__PURE__ */ __name((streamBody, context2) => collectBodyString(streamBody, context2).then((encoded) => {
if (encoded.length) {
const parser2 = new import_fast_xml_parser.XMLParser({
attributeNamePrefix: "",
htmlEntities: true,
ignoreAttributes: false,
ignoreDeclaration: true,
parseTagValue: false,
trimValues: false,
tagValueProcessor: /* @__PURE__ */ __name((_4, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0, "tagValueProcessor")
});
parser2.addEntity("#xD", "\r");
parser2.addEntity("#10", "\n");
let parsedObj;
try {
parsedObj = parser2.parse(encoded, true);
} catch (e7) {
if (e7 && typeof e7 === "object") {
Object.defineProperty(e7, "$responseBodyText", {
value: encoded
});
}
throw e7;
}
const textNodeName = "#text";
const key = Object.keys(parsedObj)[0];
const parsedObjToReturn = parsedObj[key];
if (parsedObjToReturn[textNodeName]) {
parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
delete parsedObjToReturn[textNodeName];
}
return getValueFromTextNode(parsedObjToReturn);
}
return {};
}), "parseXmlBody");
parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context2) => {
const value = await parseXmlBody(errorBody, context2);
if (value.Error) {
value.Error.message = value.Error.message ?? value.Error.Message;
}
return value;
}, "parseXmlErrorBody");
loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => {
if (data?.Error?.Code !== void 0) {
return data.Error.Code;
}
if (data?.Code !== void 0) {
return data.Code;
}
if (output.statusCode == 404) {
return "NotFound";
}
}, "loadRestXmlErrorCode");
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
var init_protocols2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() {
init_import_meta_url();
init_coercing_serializers();
init_awsExpectUnion();
init_parseJsonBody();
init_parseXmlBody();
}
});
// ../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/index.js
var init_dist_es21 = __esm({
"../../node_modules/.pnpm/@aws-sdk+core@3.716.0/node_modules/@aws-sdk/core/dist-es/index.js"() {
init_import_meta_url();
init_client5();
init_httpAuthSchemes2();
init_protocols2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/types.js
var CLIENT_SUPPORTED_ALGORITHMS, PRIORITY_ORDER_ALGORITHMS;
var init_types5 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/types.js"() {
init_import_meta_url();
init_constants6();
CLIENT_SUPPORTED_ALGORITHMS = [
ChecksumAlgorithm.CRC32,
ChecksumAlgorithm.CRC32C,
ChecksumAlgorithm.SHA1,
ChecksumAlgorithm.SHA256
];
PRIORITY_ORDER_ALGORITHMS = [
ChecksumAlgorithm.SHA256,
ChecksumAlgorithm.SHA1,
ChecksumAlgorithm.CRC32,
ChecksumAlgorithm.CRC32C
];
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumAlgorithmForRequest.js
var getChecksumAlgorithmForRequest;
var init_getChecksumAlgorithmForRequest = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumAlgorithmForRequest.js"() {
init_import_meta_url();
init_constants6();
init_types5();
getChecksumAlgorithmForRequest = /* @__PURE__ */ __name((input, { requestChecksumRequired, requestAlgorithmMember }, isS3Express) => {
const defaultAlgorithm = isS3Express ? S3_EXPRESS_DEFAULT_CHECKSUM_ALGORITHM : DEFAULT_CHECKSUM_ALGORITHM;
if (!requestAlgorithmMember || !input[requestAlgorithmMember]) {
return requestChecksumRequired ? defaultAlgorithm : void 0;
}
const checksumAlgorithm = input[requestAlgorithmMember];
if (!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm)) {
throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.`);
}
return checksumAlgorithm;
}, "getChecksumAlgorithmForRequest");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumLocationName.js
var getChecksumLocationName;
var init_getChecksumLocationName = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumLocationName.js"() {
init_import_meta_url();
init_constants6();
getChecksumLocationName = /* @__PURE__ */ __name((algorithm) => algorithm === ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`, "getChecksumLocationName");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/hasHeader.js
var hasHeader2;
var init_hasHeader = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/hasHeader.js"() {
init_import_meta_url();
hasHeader2 = /* @__PURE__ */ __name((header, headers) => {
const soughtHeader = header.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (soughtHeader === headerName.toLowerCase()) {
return true;
}
}
return false;
}, "hasHeader");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/hasHeaderWithPrefix.js
var hasHeaderWithPrefix;
var init_hasHeaderWithPrefix = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/hasHeaderWithPrefix.js"() {
init_import_meta_url();
hasHeaderWithPrefix = /* @__PURE__ */ __name((headerPrefix, headers) => {
const soughtHeaderPrefix = headerPrefix.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) {
return true;
}
}
return false;
}, "hasHeaderWithPrefix");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/isStreaming.js
var isStreaming;
var init_isStreaming = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/isStreaming.js"() {
init_import_meta_url();
init_dist_es6();
isStreaming = /* @__PURE__ */ __name((body) => body !== void 0 && typeof body !== "string" && !ArrayBuffer.isView(body) && !isArrayBuffer(body), "isStreaming");
}
});
// ../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
function __awaiter(thisArg, _arguments, P3, generator) {
function adopt(value) {
return value instanceof P3 ? value : new P3(function(resolve25) {
resolve25(value);
});
}
__name(adopt, "adopt");
return new (P3 || (P3 = Promise))(function(resolve25, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e7) {
reject(e7);
}
}
__name(fulfilled, "fulfilled");
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e7) {
reject(e7);
}
}
__name(rejected, "rejected");
function step(result) {
result.done ? resolve25(result.value) : adopt(result.value).then(fulfilled, rejected);
}
__name(step, "step");
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _4 = { label: 0, sent: /* @__PURE__ */ __name(function() {
if (t7[0] & 1) throw t7[1];
return t7[1];
}, "sent"), trys: [], ops: [] }, f6, y4, t7, g6 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g6.next = verb(0), g6["throw"] = verb(1), g6["return"] = verb(2), typeof Symbol === "function" && (g6[Symbol.iterator] = function() {
return this;
}), g6;
function verb(n6) {
return function(v7) {
return step([n6, v7]);
};
}
__name(verb, "verb");
function step(op) {
if (f6) throw new TypeError("Generator is already executing.");
while (g6 && (g6 = 0, op[0] && (_4 = 0)), _4) try {
if (f6 = 1, y4 && (t7 = op[0] & 2 ? y4["return"] : op[0] ? y4["throw"] || ((t7 = y4["return"]) && t7.call(y4), 0) : y4.next) && !(t7 = t7.call(y4, op[1])).done) return t7;
if (y4 = 0, t7) op = [op[0] & 2, t7.value];
switch (op[0]) {
case 0:
case 1:
t7 = op;
break;
case 4:
_4.label++;
return { value: op[1], done: false };
case 5:
_4.label++;
y4 = op[1];
op = [0];
continue;
case 7:
op = _4.ops.pop();
_4.trys.pop();
continue;
default:
if (!(t7 = _4.trys, t7 = t7.length > 0 && t7[t7.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_4 = 0;
continue;
}
if (op[0] === 3 && (!t7 || op[1] > t7[0] && op[1] < t7[3])) {
_4.label = op[1];
break;
}
if (op[0] === 6 && _4.label < t7[1]) {
_4.label = t7[1];
t7 = op;
break;
}
if (t7 && _4.label < t7[2]) {
_4.label = t7[2];
_4.ops.push(op);
break;
}
if (t7[2]) _4.ops.pop();
_4.trys.pop();
continue;
}
op = body.call(thisArg, _4);
} catch (e7) {
op = [6, e7];
y4 = 0;
} finally {
f6 = t7 = 0;
}
if (op[0] & 5) throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
__name(step, "step");
}
function __values(o5) {
var s5 = typeof Symbol === "function" && Symbol.iterator, m6 = s5 && o5[s5], i5 = 0;
if (m6) return m6.call(o5);
if (o5 && typeof o5.length === "number") return {
next: /* @__PURE__ */ __name(function() {
if (o5 && i5 >= o5.length) o5 = void 0;
return { value: o5 && o5[i5++], done: !o5 };
}, "next")
};
throw new TypeError(s5 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
var init_tslib_es6 = __esm({
"../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() {
init_import_meta_url();
__name(__awaiter, "__awaiter");
__name(__generator, "__generator");
__name(__values, "__values");
}
});
// ../../node_modules/.pnpm/@smithy+is-array-buffer@2.2.0/node_modules/@smithy/is-array-buffer/dist-es/index.js
var init_dist_es22 = __esm({
"../../node_modules/.pnpm/@smithy+is-array-buffer@2.2.0/node_modules/@smithy/is-array-buffer/dist-es/index.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-buffer-from@2.2.0/node_modules/@smithy/util-buffer-from/dist-es/index.js
var import_buffer2, fromString2;
var init_dist_es23 = __esm({
"../../node_modules/.pnpm/@smithy+util-buffer-from@2.2.0/node_modules/@smithy/util-buffer-from/dist-es/index.js"() {
init_import_meta_url();
init_dist_es22();
import_buffer2 = require("buffer");
fromString2 = /* @__PURE__ */ __name((input, encoding) => {
if (typeof input !== "string") {
throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
}
return encoding ? import_buffer2.Buffer.from(input, encoding) : import_buffer2.Buffer.from(input);
}, "fromString");
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js
var fromUtf82;
var init_fromUtf82 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"() {
init_import_meta_url();
init_dist_es23();
fromUtf82 = /* @__PURE__ */ __name((input) => {
const buf = fromString2(input, "utf8");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}, "fromUtf8");
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var init_toUint8Array2 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
init_import_meta_url();
init_fromUtf82();
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js
var init_toUtf82 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/toUtf8.js"() {
init_import_meta_url();
init_dist_es23();
}
});
// ../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es24 = __esm({
"../../node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-es/index.js"() {
init_import_meta_url();
init_fromUtf82();
init_toUint8Array2();
init_toUtf82();
}
});
// ../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/convertToBuffer.js
function convertToBuffer(data) {
if (data instanceof Uint8Array)
return data;
if (typeof data === "string") {
return fromUtf83(data);
}
if (ArrayBuffer.isView(data)) {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}
return new Uint8Array(data);
}
var fromUtf83;
var init_convertToBuffer = __esm({
"../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/convertToBuffer.js"() {
init_import_meta_url();
init_dist_es24();
fromUtf83 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
return Buffer.from(input, "utf8");
} : fromUtf82;
__name(convertToBuffer, "convertToBuffer");
}
});
// ../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/isEmptyData.js
function isEmptyData(data) {
if (typeof data === "string") {
return data.length === 0;
}
return data.byteLength === 0;
}
var init_isEmptyData = __esm({
"../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/isEmptyData.js"() {
init_import_meta_url();
__name(isEmptyData, "isEmptyData");
}
});
// ../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/numToUint8.js
function numToUint8(num) {
return new Uint8Array([
(num & 4278190080) >> 24,
(num & 16711680) >> 16,
(num & 65280) >> 8,
num & 255
]);
}
var init_numToUint8 = __esm({
"../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/numToUint8.js"() {
init_import_meta_url();
__name(numToUint8, "numToUint8");
}
});
// ../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js
function uint32ArrayFrom(a_lookUpTable2) {
if (!Uint32Array.from) {
var return_array = new Uint32Array(a_lookUpTable2.length);
var a_index = 0;
while (a_index < a_lookUpTable2.length) {
return_array[a_index] = a_lookUpTable2[a_index];
a_index += 1;
}
return return_array;
}
return Uint32Array.from(a_lookUpTable2);
}
var init_uint32ArrayFrom = __esm({
"../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js"() {
init_import_meta_url();
__name(uint32ArrayFrom, "uint32ArrayFrom");
}
});
// ../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/index.js
var init_module = __esm({
"../../node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/module/index.js"() {
init_import_meta_url();
init_convertToBuffer();
init_isEmptyData();
init_numToUint8();
init_uint32ArrayFrom();
}
});
// ../../node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/module/aws_crc32c.js
var AwsCrc32c;
var init_aws_crc32c = __esm({
"../../node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/module/aws_crc32c.js"() {
init_import_meta_url();
init_tslib_es6();
init_module();
init_module2();
AwsCrc32c = /** @class */
function() {
function AwsCrc32c2() {
this.crc32c = new Crc32c();
}
__name(AwsCrc32c2, "AwsCrc32c");
AwsCrc32c2.prototype.update = function(toHash) {
if (isEmptyData(toHash))
return;
this.crc32c.update(convertToBuffer(toHash));
};
AwsCrc32c2.prototype.digest = function() {
return __awaiter(this, void 0, void 0, function() {
return __generator(this, function(_a4) {
return [2, numToUint8(this.crc32c.digest())];
});
});
};
AwsCrc32c2.prototype.reset = function() {
this.crc32c = new Crc32c();
};
return AwsCrc32c2;
}();
}
});
// ../../node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/module/index.js
var Crc32c, a_lookupTable, lookupTable;
var init_module2 = __esm({
"../../node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/module/index.js"() {
init_import_meta_url();
init_tslib_es6();
init_module();
init_aws_crc32c();
Crc32c = /** @class */
function() {
function Crc32c2() {
this.checksum = 4294967295;
}
__name(Crc32c2, "Crc32c");
Crc32c2.prototype.update = function(data) {
var e_1, _a4;
try {
for (var data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
var byte = data_1_1.value;
this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255];
}
} catch (e_1_1) {
e_1 = { error: e_1_1 };
} finally {
try {
if (data_1_1 && !data_1_1.done && (_a4 = data_1.return)) _a4.call(data_1);
} finally {
if (e_1) throw e_1.error;
}
}
return this;
};
Crc32c2.prototype.digest = function() {
return (this.checksum ^ 4294967295) >>> 0;
};
return Crc32c2;
}();
a_lookupTable = [
0,
4067132163,
3778769143,
324072436,
3348797215,
904991772,
648144872,
3570033899,
2329499855,
2024987596,
1809983544,
2575936315,
1296289744,
3207089363,
2893594407,
1578318884,
274646895,
3795141740,
4049975192,
51262619,
3619967088,
632279923,
922689671,
3298075524,
2592579488,
1760304291,
2075979607,
2312596564,
1562183871,
2943781820,
3156637768,
1313733451,
549293790,
3537243613,
3246849577,
871202090,
3878099393,
357341890,
102525238,
4101499445,
2858735121,
1477399826,
1264559846,
3107202533,
1845379342,
2677391885,
2361733625,
2125378298,
820201905,
3263744690,
3520608582,
598981189,
4151959214,
85089709,
373468761,
3827903834,
3124367742,
1213305469,
1526817161,
2842354314,
2107672161,
2412447074,
2627466902,
1861252501,
1098587580,
3004210879,
2688576843,
1378610760,
2262928035,
1955203488,
1742404180,
2511436119,
3416409459,
969524848,
714683780,
3639785095,
205050476,
4266873199,
3976438427,
526918040,
1361435347,
2739821008,
2954799652,
1114974503,
2529119692,
1691668175,
2005155131,
2247081528,
3690758684,
697762079,
986182379,
3366744552,
476452099,
3993867776,
4250756596,
255256311,
1640403810,
2477592673,
2164122517,
1922457750,
2791048317,
1412925310,
1197962378,
3037525897,
3944729517,
427051182,
170179418,
4165941337,
746937522,
3740196785,
3451792453,
1070968646,
1905808397,
2213795598,
2426610938,
1657317369,
3053634322,
1147748369,
1463399397,
2773627110,
4215344322,
153784257,
444234805,
3893493558,
1021025245,
3467647198,
3722505002,
797665321,
2197175160,
1889384571,
1674398607,
2443626636,
1164749927,
3070701412,
2757221520,
1446797203,
137323447,
4198817972,
3910406976,
461344835,
3484808360,
1037989803,
781091935,
3705997148,
2460548119,
1623424788,
1939049696,
2180517859,
1429367560,
2807687179,
3020495871,
1180866812,
410100952,
3927582683,
4182430767,
186734380,
3756733383,
763408580,
1053836080,
3434856499,
2722870694,
1344288421,
1131464017,
2971354706,
1708204729,
2545590714,
2229949006,
1988219213,
680717673,
3673779818,
3383336350,
1002577565,
4010310262,
493091189,
238226049,
4233660802,
2987750089,
1082061258,
1395524158,
2705686845,
1972364758,
2279892693,
2494862625,
1725896226,
952904198,
3399985413,
3656866545,
731699698,
4283874585,
222117402,
510512622,
3959836397,
3280807620,
837199303,
582374963,
3504198960,
68661723,
4135334616,
3844915500,
390545967,
1230274059,
3141532936,
2825850620,
1510247935,
2395924756,
2091215383,
1878366691,
2644384480,
3553878443,
565732008,
854102364,
3229815391,
340358836,
3861050807,
4117890627,
119113024,
1493875044,
2875275879,
3090270611,
1247431312,
2660249211,
1828433272,
2141937292,
2378227087,
3811616794,
291187481,
34330861,
4032846830,
615137029,
3603020806,
3314634738,
939183345,
1776939221,
2609017814,
2295496738,
2058945313,
2926798794,
1545135305,
1330124605,
3173225534,
4084100981,
17165430,
307568514,
3762199681,
888469610,
3332340585,
3587147933,
665062302,
2042050490,
2346497209,
2559330125,
1793573966,
3190661285,
1279665062,
1595330642,
2910671697
];
lookupTable = uint32ArrayFrom(a_lookupTable);
}
});
// ../../node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/module/aws_crc32.js
var AwsCrc32;
var init_aws_crc32 = __esm({
"../../node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/module/aws_crc32.js"() {
init_import_meta_url();
init_tslib_es6();
init_module();
init_module3();
AwsCrc32 = /** @class */
function() {
function AwsCrc322() {
this.crc32 = new Crc32();
}
__name(AwsCrc322, "AwsCrc32");
AwsCrc322.prototype.update = function(toHash) {
if (isEmptyData(toHash))
return;
this.crc32.update(convertToBuffer(toHash));
};
AwsCrc322.prototype.digest = function() {
return __awaiter(this, void 0, void 0, function() {
return __generator(this, function(_a4) {
return [2, numToUint8(this.crc32.digest())];
});
});
};
AwsCrc322.prototype.reset = function() {
this.crc32 = new Crc32();
};
return AwsCrc322;
}();
}
});
// ../../node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/module/index.js
var Crc32, a_lookUpTable, lookupTable2;
var init_module3 = __esm({
"../../node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/module/index.js"() {
init_import_meta_url();
init_tslib_es6();
init_module();
init_aws_crc32();
Crc32 = /** @class */
function() {
function Crc322() {
this.checksum = 4294967295;
}
__name(Crc322, "Crc32");
Crc322.prototype.update = function(data) {
var e_1, _a4;
try {
for (var data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
var byte = data_1_1.value;
this.checksum = this.checksum >>> 8 ^ lookupTable2[(this.checksum ^ byte) & 255];
}
} catch (e_1_1) {
e_1 = { error: e_1_1 };
} finally {
try {
if (data_1_1 && !data_1_1.done && (_a4 = data_1.return)) _a4.call(data_1);
} finally {
if (e_1) throw e_1.error;
}
}
return this;
};
Crc322.prototype.digest = function() {
return (this.checksum ^ 4294967295) >>> 0;
};
return Crc322;
}();
a_lookUpTable = [
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
];
lookupTable2 = uint32ArrayFrom(a_lookUpTable);
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getCrc32ChecksumAlgorithmFunction.js
var zlib, NodeCrc32, getCrc32ChecksumAlgorithmFunction;
var init_getCrc32ChecksumAlgorithmFunction = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getCrc32ChecksumAlgorithmFunction.js"() {
init_import_meta_url();
init_module3();
init_module();
zlib = __toESM(require("zlib"));
NodeCrc32 = class {
static {
__name(this, "NodeCrc32");
}
constructor() {
this.checksum = 0;
}
update(data) {
this.checksum = zlib.crc32(data, this.checksum);
}
async digest() {
return numToUint8(this.checksum);
}
reset() {
this.checksum = 0;
}
};
getCrc32ChecksumAlgorithmFunction = /* @__PURE__ */ __name(() => {
if (typeof zlib.crc32 === "undefined") {
return AwsCrc32;
}
return NodeCrc32;
}, "getCrc32ChecksumAlgorithmFunction");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/selectChecksumAlgorithmFunction.js
var selectChecksumAlgorithmFunction;
var init_selectChecksumAlgorithmFunction = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/selectChecksumAlgorithmFunction.js"() {
init_import_meta_url();
init_module2();
init_constants6();
init_getCrc32ChecksumAlgorithmFunction();
selectChecksumAlgorithmFunction = /* @__PURE__ */ __name((checksumAlgorithm, config) => {
switch (checksumAlgorithm) {
case ChecksumAlgorithm.MD5:
return config.md5;
case ChecksumAlgorithm.CRC32:
return getCrc32ChecksumAlgorithmFunction();
case ChecksumAlgorithm.CRC32C:
return AwsCrc32c;
case ChecksumAlgorithm.SHA1:
return config.sha1;
case ChecksumAlgorithm.SHA256:
return config.sha256;
default:
throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`);
}
}, "selectChecksumAlgorithmFunction");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/stringHasher.js
var stringHasher;
var init_stringHasher = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/stringHasher.js"() {
init_import_meta_url();
init_dist_es8();
stringHasher = /* @__PURE__ */ __name((checksumAlgorithmFn, body) => {
const hash = new checksumAlgorithmFn();
hash.update(toUint8Array(body || ""));
return hash.digest();
}, "stringHasher");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsMiddleware.js
var flexibleChecksumsMiddlewareOptions, flexibleChecksumsMiddleware;
var init_flexibleChecksumsMiddleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsMiddleware.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es2();
init_constants6();
init_getChecksumAlgorithmForRequest();
init_getChecksumLocationName();
init_hasHeader();
init_hasHeaderWithPrefix();
init_isStreaming();
init_selectChecksumAlgorithmFunction();
init_stringHasher();
flexibleChecksumsMiddlewareOptions = {
name: "flexibleChecksumsMiddleware",
step: "build",
tags: ["BODY_CHECKSUM"],
override: true
};
flexibleChecksumsMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context2) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) {
return next(args);
}
const { request: request4, input } = args;
const { body: requestBody, headers } = request4;
const { base64Encoder, streamHasher } = config;
const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig;
const checksumAlgorithm = getChecksumAlgorithmForRequest(input, {
requestChecksumRequired,
requestAlgorithmMember: requestAlgorithmMember?.name
}, !!context2.isS3ExpressBucket);
let updatedBody = requestBody;
let updatedHeaders = headers;
if (checksumAlgorithm) {
switch (checksumAlgorithm) {
case ChecksumAlgorithm.CRC32:
setFeature(context2, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U");
break;
case ChecksumAlgorithm.CRC32C:
setFeature(context2, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V");
break;
case ChecksumAlgorithm.SHA1:
setFeature(context2, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X");
break;
case ChecksumAlgorithm.SHA256:
setFeature(context2, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y");
break;
}
const checksumLocationName = getChecksumLocationName(checksumAlgorithm);
const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config);
if (isStreaming(requestBody)) {
const { getAwsChunkedEncodingStream: getAwsChunkedEncodingStream2, bodyLengthChecker } = config;
updatedBody = getAwsChunkedEncodingStream2(requestBody, {
base64Encoder,
bodyLengthChecker,
checksumLocationName,
checksumAlgorithmFn,
streamHasher
});
updatedHeaders = {
...headers,
"content-encoding": headers["content-encoding"] ? `${headers["content-encoding"]},aws-chunked` : "aws-chunked",
"transfer-encoding": "chunked",
"x-amz-decoded-content-length": headers["content-length"],
"x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
"x-amz-trailer": checksumLocationName
};
delete updatedHeaders["content-length"];
} else if (!hasHeader2(checksumLocationName, headers)) {
const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody);
updatedHeaders = {
...headers,
[checksumLocationName]: base64Encoder(rawChecksum)
};
}
}
const result = await next({
...args,
request: {
...request4,
headers: updatedHeaders,
body: updatedBody
}
});
return result;
}, "flexibleChecksumsMiddleware");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumAlgorithmListForResponse.js
var getChecksumAlgorithmListForResponse;
var init_getChecksumAlgorithmListForResponse = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumAlgorithmListForResponse.js"() {
init_import_meta_url();
init_types5();
getChecksumAlgorithmListForResponse = /* @__PURE__ */ __name((responseAlgorithms = []) => {
const validChecksumAlgorithms = [];
for (const algorithm of PRIORITY_ORDER_ALGORITHMS) {
if (!responseAlgorithms.includes(algorithm) || !CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)) {
continue;
}
validChecksumAlgorithms.push(algorithm);
}
return validChecksumAlgorithms;
}, "getChecksumAlgorithmListForResponse");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/isChecksumWithPartNumber.js
var isChecksumWithPartNumber;
var init_isChecksumWithPartNumber = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/isChecksumWithPartNumber.js"() {
init_import_meta_url();
isChecksumWithPartNumber = /* @__PURE__ */ __name((checksum) => {
const lastHyphenIndex = checksum.lastIndexOf("-");
if (lastHyphenIndex !== -1) {
const numberPart = checksum.slice(lastHyphenIndex + 1);
if (!numberPart.startsWith("0")) {
const number = parseInt(numberPart, 10);
if (!isNaN(number) && number >= 1 && number <= 1e4) {
return true;
}
}
}
return false;
}, "isChecksumWithPartNumber");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/streams/create-read-stream-on-buffer.js
function createReadStreamOnBuffer(buffer) {
const stream2 = new import_stream11.Transform();
stream2.push(buffer);
stream2.push(null);
return stream2;
}
var import_stream11;
var init_create_read_stream_on_buffer = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/streams/create-read-stream-on-buffer.js"() {
init_import_meta_url();
import_stream11 = require("stream");
__name(createReadStreamOnBuffer, "createReadStreamOnBuffer");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksum.js
var getChecksum;
var init_getChecksum = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksum.js"() {
init_import_meta_url();
init_stringHasher();
getChecksum = /* @__PURE__ */ __name(async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body)), "getChecksum");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/validateChecksumFromResponse.js
var validateChecksumFromResponse;
var init_validateChecksumFromResponse = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/validateChecksumFromResponse.js"() {
init_import_meta_url();
init_dist_es15();
init_getChecksum();
init_getChecksumAlgorithmListForResponse();
init_getChecksumLocationName();
init_isStreaming();
init_selectChecksumAlgorithmFunction();
validateChecksumFromResponse = /* @__PURE__ */ __name(async (response, { config, responseAlgorithms }) => {
const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms);
const { body: responseBody, headers: responseHeaders } = response;
for (const algorithm of checksumAlgorithms) {
const responseHeader = getChecksumLocationName(algorithm);
const checksumFromResponse = responseHeaders[responseHeader];
if (checksumFromResponse) {
const checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm, config);
const { base64Encoder } = config;
if (isStreaming(responseBody)) {
response.body = createChecksumStream2({
expectedChecksum: checksumFromResponse,
checksumSourceLocation: responseHeader,
checksum: new checksumAlgorithmFn(),
source: responseBody,
base64Encoder
});
return;
}
const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder });
if (checksum === checksumFromResponse) {
break;
}
throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`);
}
}
}, "validateChecksumFromResponse");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsResponseMiddleware.js
var flexibleChecksumsResponseMiddlewareOptions, flexibleChecksumsResponseMiddleware;
var init_flexibleChecksumsResponseMiddleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsResponseMiddleware.js"() {
init_import_meta_url();
init_dist_es2();
init_getChecksumAlgorithmListForResponse();
init_getChecksumLocationName();
init_isChecksumWithPartNumber();
init_isStreaming();
init_create_read_stream_on_buffer();
init_validateChecksumFromResponse();
flexibleChecksumsResponseMiddlewareOptions = {
name: "flexibleChecksumsResponseMiddleware",
toMiddleware: "deserializerMiddleware",
relation: "after",
tags: ["BODY_CHECKSUM"],
override: true
};
flexibleChecksumsResponseMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context2) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
const input = args.input;
const result = await next(args);
const response = result.response;
let collectedStream = void 0;
const { requestValidationModeMember, responseAlgorithms } = middlewareConfig;
if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") {
const { clientName, commandName } = context2;
const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" && commandName === "GetObjectCommand" && getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm) => {
const responseHeader = getChecksumLocationName(algorithm);
const checksumFromResponse = response.headers[responseHeader];
return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse);
});
if (isS3WholeObjectMultipartGetResponseChecksum) {
return result;
}
const isStreamingBody = isStreaming(response.body);
if (isStreamingBody) {
collectedStream = await config.streamCollector(response.body);
response.body = createReadStreamOnBuffer(collectedStream);
}
await validateChecksumFromResponse(result.response, {
config,
responseAlgorithms
});
if (isStreamingBody && collectedStream) {
response.body = createReadStreamOnBuffer(collectedStream);
}
}
return result;
}, "flexibleChecksumsResponseMiddleware");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getFlexibleChecksumsPlugin.js
var getFlexibleChecksumsPlugin;
var init_getFlexibleChecksumsPlugin = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getFlexibleChecksumsPlugin.js"() {
init_import_meta_url();
init_flexibleChecksumsMiddleware();
init_flexibleChecksumsResponseMiddleware();
getFlexibleChecksumsPlugin = /* @__PURE__ */ __name((config, middlewareConfig) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(flexibleChecksumsMiddleware(config, middlewareConfig), flexibleChecksumsMiddlewareOptions);
clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config, middlewareConfig), flexibleChecksumsResponseMiddlewareOptions);
}, "applyToStack")
}), "getFlexibleChecksumsPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/resolveFlexibleChecksumsConfig.js
var resolveFlexibleChecksumsConfig;
var init_resolveFlexibleChecksumsConfig = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/resolveFlexibleChecksumsConfig.js"() {
init_import_meta_url();
init_dist_es4();
init_constants6();
resolveFlexibleChecksumsConfig = /* @__PURE__ */ __name((input) => ({
...input,
requestChecksumCalculation: normalizeProvider(input.requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION),
responseChecksumValidation: normalizeProvider(input.responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION)
}), "resolveFlexibleChecksumsConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/index.js
var init_dist_es25 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.717.0/node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/index.js"() {
init_import_meta_url();
init_NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS();
init_NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS();
init_constants6();
init_flexibleChecksumsMiddleware();
init_getFlexibleChecksumsPlugin();
init_resolveFlexibleChecksumsConfig();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.714.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js
function resolveHostHeaderConfig(input) {
return input;
}
var hostHeaderMiddleware, hostHeaderMiddlewareOptions, getHostHeaderPlugin;
var init_dist_es26 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.714.0/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js"() {
init_import_meta_url();
init_dist_es2();
__name(resolveHostHeaderConfig, "resolveHostHeaderConfig");
hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
if (!HttpRequest.isInstance(args.request))
return next(args);
const { request: request4 } = args;
const { handlerProtocol = "" } = options.requestHandler.metadata || {};
if (handlerProtocol.indexOf("h2") >= 0 && !request4.headers[":authority"]) {
delete request4.headers["host"];
request4.headers[":authority"] = request4.hostname + (request4.port ? ":" + request4.port : "");
} else if (!request4.headers["host"]) {
let host = request4.hostname;
if (request4.port != null)
host += `:${request4.port}`;
request4.headers["host"] = host;
}
return next(args);
}, "hostHeaderMiddleware");
hostHeaderMiddlewareOptions = {
name: "hostHeaderMiddleware",
step: "build",
priority: "low",
tags: ["HOST"],
override: true
};
getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
}, "applyToStack")
}), "getHostHeaderPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-logger@3.714.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js
var loggerMiddleware, loggerMiddlewareOptions, getLoggerPlugin;
var init_loggerMiddleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-logger@3.714.0/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js"() {
init_import_meta_url();
loggerMiddleware = /* @__PURE__ */ __name(() => (next, context2) => async (args) => {
try {
const response = await next(args);
const { clientName, commandName, logger: logger4, dynamoDbDocumentClientOptions = {} } = context2;
const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context2.inputFilterSensitiveLog;
const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context2.outputFilterSensitiveLog;
const { $metadata, ...outputWithoutMetadata } = response.output;
logger4?.info?.({
clientName,
commandName,
input: inputFilterSensitiveLog(args.input),
output: outputFilterSensitiveLog(outputWithoutMetadata),
metadata: $metadata
});
return response;
} catch (error2) {
const { clientName, commandName, logger: logger4, dynamoDbDocumentClientOptions = {} } = context2;
const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context2.inputFilterSensitiveLog;
logger4?.error?.({
clientName,
commandName,
input: inputFilterSensitiveLog(args.input),
error: error2,
metadata: error2.$metadata
});
throw error2;
}
}, "loggerMiddleware");
loggerMiddlewareOptions = {
name: "loggerMiddleware",
tags: ["LOGGER"],
step: "initialize",
override: true
};
getLoggerPlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
}, "applyToStack")
}), "getLoggerPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-logger@3.714.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js
var init_dist_es27 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-logger@3.714.0/node_modules/@aws-sdk/middleware-logger/dist-es/index.js"() {
init_import_meta_url();
init_loggerMiddleware();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.714.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js
var TRACE_ID_HEADER_NAME, ENV_LAMBDA_FUNCTION_NAME, ENV_TRACE_ID, recursionDetectionMiddleware, addRecursionDetectionMiddlewareOptions, getRecursionDetectionPlugin;
var init_dist_es28 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.714.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js"() {
init_import_meta_url();
init_dist_es2();
TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
const { request: request4 } = args;
if (!HttpRequest.isInstance(request4) || options.runtime !== "node" || request4.headers.hasOwnProperty(TRACE_ID_HEADER_NAME)) {
return next(args);
}
const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
const traceId = process.env[ENV_TRACE_ID];
const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString");
if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
request4.headers[TRACE_ID_HEADER_NAME] = traceId;
}
return next({
...args,
request: request4
});
}, "recursionDetectionMiddleware");
addRecursionDetectionMiddlewareOptions = {
step: "build",
tags: ["RECURSION_DETECTION"],
name: "recursionDetectionMiddleware",
override: true,
priority: "low"
};
getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
}, "applyToStack")
}), "getRecursionDetectionPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/check-content-length-header.js
function checkContentLengthHeader() {
return (next, context2) => async (args) => {
const { request: request4 } = args;
if (HttpRequest.isInstance(request4)) {
if (!(CONTENT_LENGTH_HEADER in request4.headers)) {
const message = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`;
if (typeof context2?.logger?.warn === "function" && !(context2.logger instanceof NoOpLogger)) {
context2.logger.warn(message);
} else {
console.warn(message);
}
}
}
return next({ ...args });
};
}
var CONTENT_LENGTH_HEADER, checkContentLengthHeaderMiddlewareOptions, getCheckContentLengthHeaderPlugin;
var init_check_content_length_header = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/check-content-length-header.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es20();
CONTENT_LENGTH_HEADER = "content-length";
__name(checkContentLengthHeader, "checkContentLengthHeader");
checkContentLengthHeaderMiddlewareOptions = {
step: "finalizeRequest",
tags: ["CHECK_CONTENT_LENGTH_HEADER"],
name: "getCheckContentLengthHeaderPlugin",
override: true
};
getCheckContentLengthHeaderPlugin = /* @__PURE__ */ __name((unused) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions);
}, "applyToStack")
}), "getCheckContentLengthHeaderPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/region-redirect-endpoint-middleware.js
var regionRedirectEndpointMiddleware, regionRedirectEndpointMiddlewareOptions;
var init_region_redirect_endpoint_middleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/region-redirect-endpoint-middleware.js"() {
init_import_meta_url();
regionRedirectEndpointMiddleware = /* @__PURE__ */ __name((config) => {
return (next, context2) => async (args) => {
const originalRegion = await config.region();
const regionProviderRef = config.region;
let unlock = /* @__PURE__ */ __name(() => {
}, "unlock");
if (context2.__s3RegionRedirect) {
Object.defineProperty(config, "region", {
writable: false,
value: /* @__PURE__ */ __name(async () => {
return context2.__s3RegionRedirect;
}, "value")
});
unlock = /* @__PURE__ */ __name(() => Object.defineProperty(config, "region", {
writable: true,
value: regionProviderRef
}), "unlock");
}
try {
const result = await next(args);
if (context2.__s3RegionRedirect) {
unlock();
const region = await config.region();
if (originalRegion !== region) {
throw new Error("Region was not restored following S3 region redirect.");
}
}
return result;
} catch (e7) {
unlock();
throw e7;
}
};
}, "regionRedirectEndpointMiddleware");
regionRedirectEndpointMiddlewareOptions = {
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectEndpointMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware"
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/region-redirect-middleware.js
function regionRedirectMiddleware(clientConfig) {
return (next, context2) => async (args) => {
try {
return await next(args);
} catch (err) {
if (clientConfig.followRegionRedirects) {
if (err?.$metadata?.httpStatusCode === 301 || err?.$metadata?.httpStatusCode === 400 && err?.name === "IllegalLocationConstraintException") {
try {
const actualRegion = err.$response.headers["x-amz-bucket-region"];
context2.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`);
context2.__s3RegionRedirect = actualRegion;
} catch (e7) {
throw new Error("Region redirect failed: " + e7);
}
return next(args);
}
}
throw err;
}
};
}
var regionRedirectMiddlewareOptions, getRegionRedirectMiddlewarePlugin;
var init_region_redirect_middleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/region-redirect-middleware.js"() {
init_import_meta_url();
init_region_redirect_endpoint_middleware();
__name(regionRedirectMiddleware, "regionRedirectMiddleware");
regionRedirectMiddlewareOptions = {
step: "initialize",
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectMiddleware",
override: true
};
getRegionRedirectMiddlewarePlugin = /* @__PURE__ */ __name((clientConfig) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions);
clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions);
}, "applyToStack")
}), "getRegionRedirectMiddlewarePlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-expires-middleware.js
var s3ExpiresMiddleware, s3ExpiresMiddlewareOptions, getS3ExpiresMiddlewarePlugin;
var init_s3_expires_middleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-expires-middleware.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es20();
s3ExpiresMiddleware = /* @__PURE__ */ __name((config) => {
return (next, context2) => async (args) => {
const result = await next(args);
const { response } = result;
if (HttpResponse.isInstance(response)) {
if (response.headers.expires) {
response.headers.expiresstring = response.headers.expires;
try {
parseRfc7231DateTime(response.headers.expires);
} catch (e7) {
context2.logger?.warn(`AWS SDK Warning for ${context2.clientName}::${context2.commandName} response parsing (${response.headers.expires}): ${e7}`);
delete response.headers.expires;
}
}
}
return result;
};
}, "s3ExpiresMiddleware");
s3ExpiresMiddlewareOptions = {
tags: ["S3"],
name: "s3ExpiresMiddleware",
override: true,
relation: "after",
toMiddleware: "deserializerMiddleware"
};
getS3ExpiresMiddlewarePlugin = /* @__PURE__ */ __name((clientConfig) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.addRelativeTo(s3ExpiresMiddleware(clientConfig), s3ExpiresMiddlewareOptions);
}, "applyToStack")
}), "getS3ExpiresMiddlewarePlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityCache.js
var S3ExpressIdentityCache;
var init_S3ExpressIdentityCache = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityCache.js"() {
init_import_meta_url();
S3ExpressIdentityCache = class _S3ExpressIdentityCache {
static {
__name(this, "S3ExpressIdentityCache");
}
constructor(data = {}) {
this.data = data;
this.lastPurgeTime = Date.now();
}
get(key) {
const entry = this.data[key];
if (!entry) {
return;
}
return entry;
}
set(key, entry) {
this.data[key] = entry;
return entry;
}
delete(key) {
delete this.data[key];
}
async purgeExpired() {
const now = Date.now();
if (this.lastPurgeTime + _S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now) {
return;
}
for (const key in this.data) {
const entry = this.data[key];
if (!entry.isRefreshing) {
const credential = await entry.identity;
if (credential.expiration) {
if (credential.expiration.getTime() < now) {
delete this.data[key];
}
}
}
}
}
};
S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 3e4;
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityCacheEntry.js
var S3ExpressIdentityCacheEntry;
var init_S3ExpressIdentityCacheEntry = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityCacheEntry.js"() {
init_import_meta_url();
S3ExpressIdentityCacheEntry = class {
static {
__name(this, "S3ExpressIdentityCacheEntry");
}
constructor(_identity, isRefreshing = false, accessed = Date.now()) {
this._identity = _identity;
this.isRefreshing = isRefreshing;
this.accessed = accessed;
}
get identity() {
this.accessed = Date.now();
return this._identity;
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityProviderImpl.js
var S3ExpressIdentityProviderImpl;
var init_S3ExpressIdentityProviderImpl = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityProviderImpl.js"() {
init_import_meta_url();
init_S3ExpressIdentityCache();
init_S3ExpressIdentityCacheEntry();
S3ExpressIdentityProviderImpl = class _S3ExpressIdentityProviderImpl {
static {
__name(this, "S3ExpressIdentityProviderImpl");
}
constructor(createSessionFn, cache6 = new S3ExpressIdentityCache()) {
this.createSessionFn = createSessionFn;
this.cache = cache6;
}
async getS3ExpressIdentity(awsIdentity, identityProperties) {
const key = identityProperties.Bucket;
const { cache: cache6 } = this;
const entry = cache6.get(key);
if (entry) {
return entry.identity.then((identity) => {
const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now();
if (isExpired) {
return cache6.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity;
}
const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + _S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS;
if (isExpiringSoon && !entry.isRefreshing) {
entry.isRefreshing = true;
this.getIdentity(key).then((id) => {
cache6.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id)));
});
}
return identity;
});
}
return cache6.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity;
}
async getIdentity(key) {
await this.cache.purgeExpired().catch((error2) => {
console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error2);
});
const session = await this.createSessionFn(key);
if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) {
throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");
}
const identity = {
accessKeyId: session.Credentials.AccessKeyId,
secretAccessKey: session.Credentials.SecretAccessKey,
sessionToken: session.Credentials.SessionToken,
expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : void 0
};
return identity;
}
};
S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS = 6e4;
}
});
// ../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js
var booleanSelector;
var init_booleanSelector = __esm({
"../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"() {
init_import_meta_url();
booleanSelector = /* @__PURE__ */ __name((obj, key, type) => {
if (!(key in obj))
return void 0;
if (obj[key] === "true")
return true;
if (obj[key] === "false")
return false;
throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
}, "booleanSelector");
}
});
// ../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js
var init_numberSelector = __esm({
"../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/numberSelector.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js
var SelectorType2;
var init_types6 = __esm({
"../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/types.js"() {
init_import_meta_url();
(function(SelectorType3) {
SelectorType3["ENV"] = "env";
SelectorType3["CONFIG"] = "shared config entry";
})(SelectorType2 || (SelectorType2 = {}));
}
});
// ../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js
var init_dist_es29 = __esm({
"../../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-es/index.js"() {
init_import_meta_url();
init_booleanSelector();
init_numberSelector();
init_types6();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/constants.js
var S3_EXPRESS_BUCKET_TYPE, S3_EXPRESS_BACKEND, S3_EXPRESS_AUTH_SCHEME, SESSION_TOKEN_QUERY_PARAM, SESSION_TOKEN_HEADER, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS;
var init_constants10 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/constants.js"() {
init_import_meta_url();
init_dist_es29();
S3_EXPRESS_BUCKET_TYPE = "Directory";
S3_EXPRESS_BACKEND = "S3Express";
S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express";
SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token";
SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase();
NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";
NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth";
NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => booleanSelector(env6, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, SelectorType2.ENV), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => booleanSelector(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, SelectorType2.CONFIG), "configFileSelector"),
default: false
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/SignatureV4S3Express.js
function getCredentialsWithoutSessionToken(credentials) {
const credentialsWithoutSessionToken = {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
expiration: credentials.expiration
};
return credentialsWithoutSessionToken;
}
function setSingleOverride(privateAccess, credentialsWithoutSessionToken) {
const id = setTimeout(() => {
throw new Error("SignatureV4S3Express credential override was created but not called.");
}, 10);
const currentCredentialProvider = privateAccess.credentialProvider;
const overrideCredentialsProviderOnce = /* @__PURE__ */ __name(() => {
clearTimeout(id);
privateAccess.credentialProvider = currentCredentialProvider;
return Promise.resolve(credentialsWithoutSessionToken);
}, "overrideCredentialsProviderOnce");
privateAccess.credentialProvider = overrideCredentialsProviderOnce;
}
var SignatureV4S3Express;
var init_SignatureV4S3Express = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/SignatureV4S3Express.js"() {
init_import_meta_url();
init_dist_es18();
init_constants10();
SignatureV4S3Express = class extends SignatureV4 {
static {
__name(this, "SignatureV4S3Express");
}
async signWithCredentials(requestToSign, credentials, options) {
const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials);
requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken;
const privateAccess = this;
setSingleOverride(privateAccess, credentialsWithoutSessionToken);
return privateAccess.signRequest(requestToSign, options ?? {});
}
async presignWithCredentials(requestToSign, credentials, options) {
const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials);
delete requestToSign.headers[SESSION_TOKEN_HEADER];
requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken;
requestToSign.query = requestToSign.query ?? {};
requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken;
const privateAccess = this;
setSingleOverride(privateAccess, credentialsWithoutSessionToken);
return this.presign(requestToSign, options);
}
};
__name(getCredentialsWithoutSessionToken, "getCredentialsWithoutSessionToken");
__name(setSingleOverride, "setSingleOverride");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/s3ExpressMiddleware.js
var s3ExpressMiddleware, s3ExpressMiddlewareOptions, getS3ExpressPlugin;
var init_s3ExpressMiddleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/s3ExpressMiddleware.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es2();
init_constants10();
s3ExpressMiddleware = /* @__PURE__ */ __name((options) => {
return (next, context2) => async (args) => {
if (context2.endpointV2) {
const endpoint = context2.endpointV2;
const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME;
const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND || endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE;
if (isS3ExpressBucket) {
setFeature(context2, "S3_EXPRESS_BUCKET", "J");
context2.isS3ExpressBucket = true;
}
if (isS3ExpressAuth) {
const requestBucket = args.input.Bucket;
if (requestBucket) {
const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(), {
Bucket: requestBucket
});
context2.s3ExpressIdentity = s3ExpressIdentity;
if (HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) {
args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken;
}
}
}
}
return next(args);
};
}, "s3ExpressMiddleware");
s3ExpressMiddlewareOptions = {
name: "s3ExpressMiddleware",
step: "build",
tags: ["S3", "S3_EXPRESS"],
override: true
};
getS3ExpressPlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions);
}, "applyToStack")
}), "getS3ExpressPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/signS3Express.js
var signS3Express;
var init_signS3Express = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/signS3Express.js"() {
init_import_meta_url();
signS3Express = /* @__PURE__ */ __name(async (s3ExpressIdentity, signingOptions, request4, sigV4MultiRegionSigner) => {
const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request4, s3ExpressIdentity, {});
if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) {
throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");
}
return signedRequest;
}, "signS3Express");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/s3ExpressHttpSigningMiddleware.js
var defaultErrorHandler2, defaultSuccessHandler2, s3ExpressHttpSigningMiddleware, getS3ExpressHttpSigningPlugin;
var init_s3ExpressHttpSigningMiddleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/s3ExpressHttpSigningMiddleware.js"() {
init_import_meta_url();
init_dist_es16();
init_dist_es2();
init_dist_es();
init_dist_es4();
init_signS3Express();
defaultErrorHandler2 = /* @__PURE__ */ __name((signingProperties) => (error2) => {
throw error2;
}, "defaultErrorHandler");
defaultSuccessHandler2 = /* @__PURE__ */ __name((httpResponse, signingProperties) => {
}, "defaultSuccessHandler");
s3ExpressHttpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context2) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
const smithyContext = getSmithyContext(context2);
const scheme = smithyContext.selectedHttpAuthScheme;
if (!scheme) {
throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
}
const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
let request4;
if (context2.s3ExpressIdentity) {
request4 = await signS3Express(context2.s3ExpressIdentity, signingProperties, args.request, await config.signer());
} else {
request4 = await signer.sign(args.request, identity, signingProperties);
}
const output = await next({
...args,
request: request4
}).catch((signer.errorHandler || defaultErrorHandler2)(signingProperties));
(signer.successHandler || defaultSuccessHandler2)(output.response, signingProperties);
return output;
}, "s3ExpressHttpSigningMiddleware");
getS3ExpressHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config), httpSigningMiddlewareOptions);
}, "applyToStack")
}), "getS3ExpressHttpSigningPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/index.js
var init_s3_express = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/index.js"() {
init_import_meta_url();
init_S3ExpressIdentityCache();
init_S3ExpressIdentityCacheEntry();
init_S3ExpressIdentityProviderImpl();
init_SignatureV4S3Express();
init_constants10();
init_s3ExpressMiddleware();
init_s3ExpressHttpSigningMiddleware();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3Configuration.js
var resolveS3Config;
var init_s3Configuration = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3Configuration.js"() {
init_import_meta_url();
init_s3_express();
resolveS3Config = /* @__PURE__ */ __name((input, { session }) => {
const [s3ClientProvider, CreateSessionCommandCtor] = session;
return {
...input,
forcePathStyle: input.forcePathStyle ?? false,
useAccelerateEndpoint: input.useAccelerateEndpoint ?? false,
disableMultiregionAccessPoints: input.disableMultiregionAccessPoints ?? false,
followRegionRedirects: input.followRegionRedirects ?? false,
s3ExpressIdentityProvider: input.s3ExpressIdentityProvider ?? new S3ExpressIdentityProviderImpl(async (key) => s3ClientProvider().send(new CreateSessionCommandCtor({
Bucket: key,
SessionMode: "ReadWrite"
}))),
bucketEndpoint: input.bucketEndpoint ?? false
};
}, "resolveS3Config");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/throw-200-exceptions.js
var THROW_IF_EMPTY_BODY, MAX_BYTES_TO_INSPECT, throw200ExceptionsMiddleware, collectBody2, throw200ExceptionsMiddlewareOptions, getThrow200ExceptionsPlugin;
var init_throw_200_exceptions = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/throw-200-exceptions.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es15();
THROW_IF_EMPTY_BODY = {
CopyObjectCommand: true,
UploadPartCopyCommand: true,
CompleteMultipartUploadCommand: true
};
MAX_BYTES_TO_INSPECT = 3e3;
throw200ExceptionsMiddleware = /* @__PURE__ */ __name((config) => (next, context2) => async (args) => {
const result = await next(args);
const { response } = result;
if (!HttpResponse.isInstance(response)) {
return result;
}
const { statusCode, body: sourceBody } = response;
if (statusCode < 200 || statusCode >= 300) {
return result;
}
const isSplittableStream = typeof sourceBody?.stream === "function" || typeof sourceBody?.pipe === "function" || typeof sourceBody?.tee === "function";
if (!isSplittableStream) {
return result;
}
let bodyCopy = sourceBody;
let body = sourceBody;
if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) {
[bodyCopy, body] = await splitStream2(sourceBody);
}
response.body = body;
const bodyBytes = await collectBody2(bodyCopy, {
streamCollector: /* @__PURE__ */ __name(async (stream2) => {
return headStream2(stream2, MAX_BYTES_TO_INSPECT);
}, "streamCollector")
});
if (typeof bodyCopy?.destroy === "function") {
bodyCopy.destroy();
}
const bodyStringTail = config.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16));
if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context2.commandName]) {
const err = new Error("S3 aborted request");
err.name = "InternalError";
throw err;
}
if (bodyStringTail && bodyStringTail.endsWith("</Error>")) {
response.statusCode = 400;
}
return result;
}, "throw200ExceptionsMiddleware");
collectBody2 = /* @__PURE__ */ __name((streamBody = new Uint8Array(), context2) => {
if (streamBody instanceof Uint8Array) {
return Promise.resolve(streamBody);
}
return context2.streamCollector(streamBody) || Promise.resolve(new Uint8Array());
}, "collectBody");
throw200ExceptionsMiddlewareOptions = {
relation: "after",
toMiddleware: "deserializerMiddleware",
tags: ["THROW_200_EXCEPTIONS", "S3"],
name: "throw200ExceptionsMiddleware",
override: true
};
getThrow200ExceptionsPlugin = /* @__PURE__ */ __name((config) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.addRelativeTo(throw200ExceptionsMiddleware(config), throw200ExceptionsMiddlewareOptions);
}, "applyToStack")
}), "getThrow200ExceptionsPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-arn-parser@3.693.0/node_modules/@aws-sdk/util-arn-parser/dist-es/index.js
var validate2;
var init_dist_es30 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-arn-parser@3.693.0/node_modules/@aws-sdk/util-arn-parser/dist-es/index.js"() {
init_import_meta_url();
validate2 = /* @__PURE__ */ __name((str) => typeof str === "string" && str.indexOf("arn:") === 0 && str.split(":").length >= 6, "validate");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/bucket-endpoint-middleware.js
function bucketEndpointMiddleware(options) {
return (next, context2) => async (args) => {
if (options.bucketEndpoint) {
const endpoint = context2.endpointV2;
if (endpoint) {
const bucket = args.input.Bucket;
if (typeof bucket === "string") {
try {
const bucketEndpointUrl = new URL(bucket);
context2.endpointV2 = {
...endpoint,
url: bucketEndpointUrl
};
} catch (e7) {
const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`;
if (context2.logger?.constructor?.name === "NoOpLogger") {
console.warn(warning);
} else {
context2.logger?.warn?.(warning);
}
throw e7;
}
}
}
}
return next(args);
};
}
var bucketEndpointMiddlewareOptions;
var init_bucket_endpoint_middleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/bucket-endpoint-middleware.js"() {
init_import_meta_url();
__name(bucketEndpointMiddleware, "bucketEndpointMiddleware");
bucketEndpointMiddlewareOptions = {
name: "bucketEndpointMiddleware",
override: true,
relation: "after",
toMiddleware: "endpointV2Middleware"
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/validate-bucket-name.js
function validateBucketNameMiddleware({ bucketEndpoint }) {
return (next) => async (args) => {
const { input: { Bucket } } = args;
if (!bucketEndpoint && typeof Bucket === "string" && !validate2(Bucket) && Bucket.indexOf("/") >= 0) {
const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`);
err.name = "InvalidBucketName";
throw err;
}
return next({ ...args });
};
}
var validateBucketNameMiddlewareOptions, getValidateBucketNamePlugin;
var init_validate_bucket_name = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/validate-bucket-name.js"() {
init_import_meta_url();
init_dist_es30();
init_bucket_endpoint_middleware();
__name(validateBucketNameMiddleware, "validateBucketNameMiddleware");
validateBucketNameMiddlewareOptions = {
step: "initialize",
tags: ["VALIDATE_BUCKET_NAME"],
name: "validateBucketNameMiddleware",
override: true
};
getValidateBucketNamePlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions);
clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions);
}, "applyToStack")
}), "getValidateBucketNamePlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/index.js
var init_dist_es31 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.716.0/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/index.js"() {
init_import_meta_url();
init_check_content_length_header();
init_region_redirect_endpoint_middleware();
init_region_redirect_middleware();
init_s3_expires_middleware();
init_s3_express();
init_s3Configuration();
init_throw_200_exceptions();
init_validate_bucket_name();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js
function isValidUserAgentAppId(appId) {
if (appId === void 0) {
return true;
}
return typeof appId === "string" && appId.length <= 50;
}
function resolveUserAgentConfig(input) {
const normalizedAppIdProvider = normalizeProvider2(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
return {
...input,
customUserAgent: typeof input.customUserAgent === "string" ? [[input.customUserAgent]] : input.customUserAgent,
userAgentAppId: /* @__PURE__ */ __name(async () => {
const appId = await normalizedAppIdProvider();
if (!isValidUserAgentAppId(appId)) {
const logger4 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
if (typeof appId !== "string") {
logger4?.warn("userAgentAppId must be a string or undefined.");
} else if (appId.length > 50) {
logger4?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
}
}
return appId;
}, "userAgentAppId")
};
}
var DEFAULT_UA_APP_ID;
var init_configurations = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js"() {
init_import_meta_url();
init_dist_es16();
DEFAULT_UA_APP_ID = void 0;
__name(isValidUserAgentAppId, "isValidUserAgentAppId");
__name(resolveUserAgentConfig, "resolveUserAgentConfig");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js
var EndpointCache;
var init_EndpointCache = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"() {
init_import_meta_url();
EndpointCache = class {
static {
__name(this, "EndpointCache");
}
constructor({ size, params }) {
this.data = /* @__PURE__ */ new Map();
this.parameters = [];
this.capacity = size ?? 50;
if (params) {
this.parameters = params;
}
}
get(endpointParams, resolver) {
const key = this.hash(endpointParams);
if (key === false) {
return resolver();
}
if (!this.data.has(key)) {
if (this.data.size > this.capacity + 10) {
const keys = this.data.keys();
let i5 = 0;
while (true) {
const { value, done } = keys.next();
this.data.delete(value);
if (done || ++i5 > 10) {
break;
}
}
}
this.data.set(key, resolver());
}
return this.data.get(key);
}
size() {
return this.data.size;
}
hash(endpointParams) {
let buffer = "";
const { parameters } = this;
if (parameters.length === 0) {
return false;
}
for (const param of parameters) {
const val2 = String(endpointParams[param] ?? "");
if (val2.includes("|;")) {
return false;
}
buffer += val2 + "|;";
}
return buffer;
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js
var IP_V4_REGEX, isIpAddress;
var init_isIpAddress = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"() {
init_import_meta_url();
IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
isIpAddress = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js
var VALID_HOST_LABEL_REGEX, isValidHostLabel;
var init_isValidHostLabel = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"() {
init_import_meta_url();
VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
if (!allowSubDomains) {
return VALID_HOST_LABEL_REGEX.test(value);
}
const labels = value.split(".");
for (const label of labels) {
if (!isValidHostLabel(label)) {
return false;
}
}
return true;
}, "isValidHostLabel");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js
var customEndpointFunctions;
var init_customEndpointFunctions = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"() {
init_import_meta_url();
customEndpointFunctions = {};
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js
var debugId;
var init_debugId = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js"() {
init_import_meta_url();
debugId = "endpoints";
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js
function toDebugString(input) {
if (typeof input !== "object" || input == null) {
return input;
}
if ("ref" in input) {
return `$${toDebugString(input.ref)}`;
}
if ("fn" in input) {
return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
}
return JSON.stringify(input, null, 2);
}
var init_toDebugString = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js"() {
init_import_meta_url();
__name(toDebugString, "toDebugString");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/debug/index.js
var init_debug = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/debug/index.js"() {
init_import_meta_url();
init_debugId();
init_toDebugString();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js
var EndpointError;
var init_EndpointError = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js"() {
init_import_meta_url();
EndpointError = class extends Error {
static {
__name(this, "EndpointError");
}
constructor(message) {
super(message);
this.name = "EndpointError";
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js
var init_EndpointFunctions = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js
var init_EndpointRuleObject2 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js
var init_ErrorRuleObject2 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js
var init_RuleSetObject2 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js
var init_TreeRuleObject2 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/shared.js
var init_shared3 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/shared.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/index.js
var init_types7 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/types/index.js"() {
init_import_meta_url();
init_EndpointError();
init_EndpointFunctions();
init_EndpointRuleObject2();
init_ErrorRuleObject2();
init_RuleSetObject2();
init_TreeRuleObject2();
init_shared3();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js
var booleanEquals;
var init_booleanEquals = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js"() {
init_import_meta_url();
booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js
var getAttrPathList;
var init_getAttrPathList = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() {
init_import_meta_url();
init_types7();
getAttrPathList = /* @__PURE__ */ __name((path72) => {
const parts = path72.split(".");
const pathList = [];
for (const part of parts) {
const squareBracketIndex = part.indexOf("[");
if (squareBracketIndex !== -1) {
if (part.indexOf("]") !== part.length - 1) {
throw new EndpointError(`Path: '${path72}' does not end with ']'`);
}
const arrayIndex = part.slice(squareBracketIndex + 1, -1);
if (Number.isNaN(parseInt(arrayIndex))) {
throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path72}'`);
}
if (squareBracketIndex !== 0) {
pathList.push(part.slice(0, squareBracketIndex));
}
pathList.push(arrayIndex);
} else {
pathList.push(part);
}
}
return pathList;
}, "getAttrPathList");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js
var getAttr;
var init_getAttr = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js"() {
init_import_meta_url();
init_types7();
init_getAttrPathList();
getAttr = /* @__PURE__ */ __name((value, path72) => getAttrPathList(path72).reduce((acc, index) => {
if (typeof acc !== "object") {
throw new EndpointError(`Index '${index}' in '${path72}' not found in '${JSON.stringify(value)}'`);
} else if (Array.isArray(acc)) {
return acc[parseInt(index)];
}
return acc[index];
}, value), "getAttr");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js
var isSet;
var init_isSet = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js"() {
init_import_meta_url();
isSet = /* @__PURE__ */ __name((value) => value != null, "isSet");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/not.js
var not;
var init_not = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/not.js"() {
init_import_meta_url();
not = /* @__PURE__ */ __name((value) => !value, "not");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js
var DEFAULT_PORTS, parseURL;
var init_parseURL = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js"() {
init_import_meta_url();
init_dist_es();
init_isIpAddress();
DEFAULT_PORTS = {
[EndpointURLScheme.HTTP]: 80,
[EndpointURLScheme.HTTPS]: 443
};
parseURL = /* @__PURE__ */ __name((value) => {
const whatwgURL = (() => {
try {
if (value instanceof URL) {
return value;
}
if (typeof value === "object" && "hostname" in value) {
const { hostname: hostname3, port, protocol: protocol2 = "", path: path72 = "", query = {} } = value;
const url4 = new URL(`${protocol2}//${hostname3}${port ? `:${port}` : ""}${path72}`);
url4.search = Object.entries(query).map(([k6, v7]) => `${k6}=${v7}`).join("&");
return url4;
}
return new URL(value);
} catch (error2) {
return null;
}
})();
if (!whatwgURL) {
console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
return null;
}
const urlString = whatwgURL.href;
const { host, hostname: hostname2, pathname, protocol, search } = whatwgURL;
if (search) {
return null;
}
const scheme = protocol.slice(0, -1);
if (!Object.values(EndpointURLScheme).includes(scheme)) {
return null;
}
const isIp = isIpAddress(hostname2);
const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);
const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;
return {
scheme,
authority,
path: pathname,
normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
isIp
};
}, "parseURL");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js
var stringEquals;
var init_stringEquals = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js"() {
init_import_meta_url();
stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js
var substring;
var init_substring = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js"() {
init_import_meta_url();
substring = /* @__PURE__ */ __name((input, start, stop, reverse) => {
if (start >= stop || input.length < stop) {
return null;
}
if (!reverse) {
return input.substring(start, stop);
}
return input.substring(input.length - stop, input.length - start);
}, "substring");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js
var uriEncode;
var init_uriEncode = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js"() {
init_import_meta_url();
uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c6) => `%${c6.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/index.js
var init_lib5 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/lib/index.js"() {
init_import_meta_url();
init_booleanEquals();
init_getAttr();
init_isSet();
init_isValidHostLabel();
init_not();
init_parseURL();
init_stringEquals();
init_substring();
init_uriEncode();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js
var endpointFunctions;
var init_endpointFunctions = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js"() {
init_import_meta_url();
init_lib5();
endpointFunctions = {
booleanEquals,
getAttr,
isSet,
isValidHostLabel,
not,
parseURL,
stringEquals,
substring,
uriEncode
};
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js
var evaluateTemplate;
var init_evaluateTemplate = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js"() {
init_import_meta_url();
init_lib5();
evaluateTemplate = /* @__PURE__ */ __name((template, options) => {
const evaluatedTemplateArr = [];
const templateContext = {
...options.endpointParams,
...options.referenceRecord
};
let currentIndex = 0;
while (currentIndex < template.length) {
const openingBraceIndex = template.indexOf("{", currentIndex);
if (openingBraceIndex === -1) {
evaluatedTemplateArr.push(template.slice(currentIndex));
break;
}
evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
const closingBraceIndex = template.indexOf("}", openingBraceIndex);
if (closingBraceIndex === -1) {
evaluatedTemplateArr.push(template.slice(openingBraceIndex));
break;
}
if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
currentIndex = closingBraceIndex + 2;
}
const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
if (parameterName.includes("#")) {
const [refName, attrName] = parameterName.split("#");
evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
} else {
evaluatedTemplateArr.push(templateContext[parameterName]);
}
currentIndex = closingBraceIndex + 1;
}
return evaluatedTemplateArr.join("");
}, "evaluateTemplate");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js
var getReferenceValue;
var init_getReferenceValue = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js"() {
init_import_meta_url();
getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => {
const referenceRecord = {
...options.endpointParams,
...options.referenceRecord
};
return referenceRecord[ref];
}, "getReferenceValue");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js
var evaluateExpression;
var init_evaluateExpression = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js"() {
init_import_meta_url();
init_types7();
init_callFunction();
init_evaluateTemplate();
init_getReferenceValue();
evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => {
if (typeof obj === "string") {
return evaluateTemplate(obj, options);
} else if (obj["fn"]) {
return callFunction(obj, options);
} else if (obj["ref"]) {
return getReferenceValue(obj, options);
}
throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
}, "evaluateExpression");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js
var callFunction;
var init_callFunction = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js"() {
init_import_meta_url();
init_customEndpointFunctions();
init_endpointFunctions();
init_evaluateExpression();
callFunction = /* @__PURE__ */ __name(({ fn: fn2, argv }, options) => {
const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options));
const fnSegments = fn2.split(".");
if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {
return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
}
return endpointFunctions[fn2](...evaluatedArgs);
}, "callFunction");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js
var evaluateCondition;
var init_evaluateCondition = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js"() {
init_import_meta_url();
init_debug();
init_types7();
init_callFunction();
evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => {
if (assign && assign in options.referenceRecord) {
throw new EndpointError(`'${assign}' is already defined in Reference Record.`);
}
const value = callFunction(fnArgs, options);
options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
return {
result: value === "" ? true : !!value,
...assign != null && { toAssign: { name: assign, value } }
};
}, "evaluateCondition");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js
var evaluateConditions;
var init_evaluateConditions = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js"() {
init_import_meta_url();
init_debug();
init_evaluateCondition();
evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => {
const conditionsReferenceRecord = {};
for (const condition of conditions) {
const { result, toAssign } = evaluateCondition(condition, {
...options,
referenceRecord: {
...options.referenceRecord,
...conditionsReferenceRecord
}
});
if (!result) {
return { result };
}
if (toAssign) {
conditionsReferenceRecord[toAssign.name] = toAssign.value;
options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
}
}
return { result: true, referenceRecord: conditionsReferenceRecord };
}, "evaluateConditions");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js
var getEndpointHeaders;
var init_getEndpointHeaders = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js"() {
init_import_meta_url();
init_types7();
init_evaluateExpression();
getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({
...acc,
[headerKey]: headerVal.map((headerValEntry) => {
const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
if (typeof processedExpr !== "string") {
throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);
}
return processedExpr;
})
}), {}), "getEndpointHeaders");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js
var getEndpointProperty;
var init_getEndpointProperty = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js"() {
init_import_meta_url();
init_types7();
init_evaluateTemplate();
init_getEndpointProperties();
getEndpointProperty = /* @__PURE__ */ __name((property, options) => {
if (Array.isArray(property)) {
return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
}
switch (typeof property) {
case "string":
return evaluateTemplate(property, options);
case "object":
if (property === null) {
throw new EndpointError(`Unexpected endpoint property: ${property}`);
}
return getEndpointProperties(property, options);
case "boolean":
return property;
default:
throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);
}
}, "getEndpointProperty");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js
var getEndpointProperties;
var init_getEndpointProperties = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js"() {
init_import_meta_url();
init_getEndpointProperty();
getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
...acc,
[propertyKey]: getEndpointProperty(propertyVal, options)
}), {}), "getEndpointProperties");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js
var getEndpointUrl;
var init_getEndpointUrl = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js"() {
init_import_meta_url();
init_types7();
init_evaluateExpression();
getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => {
const expression = evaluateExpression(endpointUrl, "Endpoint URL", options);
if (typeof expression === "string") {
try {
return new URL(expression);
} catch (error2) {
console.error(`Failed to construct URL with ${expression}`, error2);
throw error2;
}
}
throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
}, "getEndpointUrl");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js
var evaluateEndpointRule;
var init_evaluateEndpointRule = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js"() {
init_import_meta_url();
init_debug();
init_evaluateConditions();
init_getEndpointHeaders();
init_getEndpointProperties();
init_getEndpointUrl();
evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => {
const { conditions, endpoint } = endpointRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) {
return;
}
const endpointRuleOptions = {
...options,
referenceRecord: { ...options.referenceRecord, ...referenceRecord }
};
const { url: url4, properties, headers } = endpoint;
options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
return {
...headers != void 0 && {
headers: getEndpointHeaders(headers, endpointRuleOptions)
},
...properties != void 0 && {
properties: getEndpointProperties(properties, endpointRuleOptions)
},
url: getEndpointUrl(url4, endpointRuleOptions)
};
}, "evaluateEndpointRule");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js
var evaluateErrorRule;
var init_evaluateErrorRule = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js"() {
init_import_meta_url();
init_types7();
init_evaluateConditions();
init_evaluateExpression();
evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => {
const { conditions, error: error2 } = errorRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) {
return;
}
throw new EndpointError(evaluateExpression(error2, "Error", {
...options,
referenceRecord: { ...options.referenceRecord, ...referenceRecord }
}));
}, "evaluateErrorRule");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js
var evaluateTreeRule;
var init_evaluateTreeRule = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js"() {
init_import_meta_url();
init_evaluateConditions();
init_evaluateRules();
evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => {
const { conditions, rules } = treeRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) {
return;
}
return evaluateRules(rules, {
...options,
referenceRecord: { ...options.referenceRecord, ...referenceRecord }
});
}, "evaluateTreeRule");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js
var evaluateRules;
var init_evaluateRules = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js"() {
init_import_meta_url();
init_types7();
init_evaluateEndpointRule();
init_evaluateErrorRule();
init_evaluateTreeRule();
evaluateRules = /* @__PURE__ */ __name((rules, options) => {
for (const rule of rules) {
if (rule.type === "endpoint") {
const endpointOrUndefined = evaluateEndpointRule(rule, options);
if (endpointOrUndefined) {
return endpointOrUndefined;
}
} else if (rule.type === "error") {
evaluateErrorRule(rule, options);
} else if (rule.type === "tree") {
const endpointOrUndefined = evaluateTreeRule(rule, options);
if (endpointOrUndefined) {
return endpointOrUndefined;
}
} else {
throw new EndpointError(`Unknown endpoint rule: ${rule}`);
}
}
throw new EndpointError(`Rules evaluation failed`);
}, "evaluateRules");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/index.js
var init_utils8 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/utils/index.js"() {
init_import_meta_url();
init_customEndpointFunctions();
init_evaluateRules();
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js
var resolveEndpoint;
var init_resolveEndpoint = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"() {
init_import_meta_url();
init_debug();
init_types7();
init_utils8();
resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => {
const { endpointParams, logger: logger4 } = options;
const { parameters, rules } = ruleSetObject;
options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
const paramsWithDefault = Object.entries(parameters).filter(([, v7]) => v7.default != null).map(([k6, v7]) => [k6, v7.default]);
if (paramsWithDefault.length > 0) {
for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
}
}
const requiredParams = Object.entries(parameters).filter(([, v7]) => v7.required).map(([k6]) => k6);
for (const requiredParam of requiredParams) {
if (endpointParams[requiredParam] == null) {
throw new EndpointError(`Missing required parameter: '${requiredParam}'`);
}
}
const endpoint = evaluateRules(rules, { endpointParams, logger: logger4, referenceRecord: {} });
options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
return endpoint;
}, "resolveEndpoint");
}
});
// ../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/index.js
var init_dist_es32 = __esm({
"../../node_modules/.pnpm/@smithy+util-endpoints@2.1.7/node_modules/@smithy/util-endpoints/dist-es/index.js"() {
init_import_meta_url();
init_EndpointCache();
init_isIpAddress();
init_isValidHostLabel();
init_customEndpointFunctions();
init_resolveEndpoint();
init_types7();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js
var init_isIpAddress2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() {
init_import_meta_url();
init_dist_es32();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js
var isVirtualHostableS3Bucket;
var init_isVirtualHostableS3Bucket = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() {
init_import_meta_url();
init_dist_es32();
init_isIpAddress2();
isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
if (allowSubDomains) {
for (const label of value.split(".")) {
if (!isVirtualHostableS3Bucket(label)) {
return false;
}
}
return true;
}
if (!isValidHostLabel(value)) {
return false;
}
if (value.length < 3 || value.length > 63) {
return false;
}
if (value !== value.toLowerCase()) {
return false;
}
if (isIpAddress(value)) {
return false;
}
return true;
}, "isVirtualHostableS3Bucket");
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js
var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn;
var init_parseArn = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() {
init_import_meta_url();
ARN_DELIMITER = ":";
RESOURCE_DELIMITER = "/";
parseArn = /* @__PURE__ */ __name((value) => {
const segments = value.split(ARN_DELIMITER);
if (segments.length < 6)
return null;
const [arn, partition2, service, region, accountId, ...resourcePath] = segments;
if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "")
return null;
const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
return {
partition: partition2,
service,
region,
accountId,
resourceId
};
}, "parseArn");
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json
var partitions_default;
var init_partitions = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() {
partitions_default = {
partitions: [{
id: "aws",
outputs: {
dnsSuffix: "amazonaws.com",
dualStackDnsSuffix: "api.aws",
implicitGlobalRegion: "us-east-1",
name: "aws",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
regions: {
"af-south-1": {
description: "Africa (Cape Town)"
},
"ap-east-1": {
description: "Asia Pacific (Hong Kong)"
},
"ap-northeast-1": {
description: "Asia Pacific (Tokyo)"
},
"ap-northeast-2": {
description: "Asia Pacific (Seoul)"
},
"ap-northeast-3": {
description: "Asia Pacific (Osaka)"
},
"ap-south-1": {
description: "Asia Pacific (Mumbai)"
},
"ap-south-2": {
description: "Asia Pacific (Hyderabad)"
},
"ap-southeast-1": {
description: "Asia Pacific (Singapore)"
},
"ap-southeast-2": {
description: "Asia Pacific (Sydney)"
},
"ap-southeast-3": {
description: "Asia Pacific (Jakarta)"
},
"ap-southeast-4": {
description: "Asia Pacific (Melbourne)"
},
"ap-southeast-5": {
description: "Asia Pacific (Malaysia)"
},
"aws-global": {
description: "AWS Standard global region"
},
"ca-central-1": {
description: "Canada (Central)"
},
"ca-west-1": {
description: "Canada West (Calgary)"
},
"eu-central-1": {
description: "Europe (Frankfurt)"
},
"eu-central-2": {
description: "Europe (Zurich)"
},
"eu-north-1": {
description: "Europe (Stockholm)"
},
"eu-south-1": {
description: "Europe (Milan)"
},
"eu-south-2": {
description: "Europe (Spain)"
},
"eu-west-1": {
description: "Europe (Ireland)"
},
"eu-west-2": {
description: "Europe (London)"
},
"eu-west-3": {
description: "Europe (Paris)"
},
"il-central-1": {
description: "Israel (Tel Aviv)"
},
"me-central-1": {
description: "Middle East (UAE)"
},
"me-south-1": {
description: "Middle East (Bahrain)"
},
"sa-east-1": {
description: "South America (Sao Paulo)"
},
"us-east-1": {
description: "US East (N. Virginia)"
},
"us-east-2": {
description: "US East (Ohio)"
},
"us-west-1": {
description: "US West (N. California)"
},
"us-west-2": {
description: "US West (Oregon)"
}
}
}, {
id: "aws-cn",
outputs: {
dnsSuffix: "amazonaws.com.cn",
dualStackDnsSuffix: "api.amazonwebservices.com.cn",
implicitGlobalRegion: "cn-northwest-1",
name: "aws-cn",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^cn\\-\\w+\\-\\d+$",
regions: {
"aws-cn-global": {
description: "AWS China global region"
},
"cn-north-1": {
description: "China (Beijing)"
},
"cn-northwest-1": {
description: "China (Ningxia)"
}
}
}, {
id: "aws-us-gov",
outputs: {
dnsSuffix: "amazonaws.com",
dualStackDnsSuffix: "api.aws",
implicitGlobalRegion: "us-gov-west-1",
name: "aws-us-gov",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
regions: {
"aws-us-gov-global": {
description: "AWS GovCloud (US) global region"
},
"us-gov-east-1": {
description: "AWS GovCloud (US-East)"
},
"us-gov-west-1": {
description: "AWS GovCloud (US-West)"
}
}
}, {
id: "aws-iso",
outputs: {
dnsSuffix: "c2s.ic.gov",
dualStackDnsSuffix: "c2s.ic.gov",
implicitGlobalRegion: "us-iso-east-1",
name: "aws-iso",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
regions: {
"aws-iso-global": {
description: "AWS ISO (US) global region"
},
"us-iso-east-1": {
description: "US ISO East"
},
"us-iso-west-1": {
description: "US ISO WEST"
}
}
}, {
id: "aws-iso-b",
outputs: {
dnsSuffix: "sc2s.sgov.gov",
dualStackDnsSuffix: "sc2s.sgov.gov",
implicitGlobalRegion: "us-isob-east-1",
name: "aws-iso-b",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
regions: {
"aws-iso-b-global": {
description: "AWS ISOB (US) global region"
},
"us-isob-east-1": {
description: "US ISOB East (Ohio)"
}
}
}, {
id: "aws-iso-e",
outputs: {
dnsSuffix: "cloud.adc-e.uk",
dualStackDnsSuffix: "cloud.adc-e.uk",
implicitGlobalRegion: "eu-isoe-west-1",
name: "aws-iso-e",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
regions: {
"eu-isoe-west-1": {
description: "EU ISOE West"
}
}
}, {
id: "aws-iso-f",
outputs: {
dnsSuffix: "csp.hci.ic.gov",
dualStackDnsSuffix: "csp.hci.ic.gov",
implicitGlobalRegion: "us-isof-south-1",
name: "aws-iso-f",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
regions: {}
}],
version: "1.1"
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js
var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix;
var init_partition = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() {
init_import_meta_url();
init_partitions();
selectedPartitionsInfo = partitions_default;
selectedUserAgentPrefix = "";
partition = /* @__PURE__ */ __name((value) => {
const { partitions } = selectedPartitionsInfo;
for (const partition2 of partitions) {
const { regions, outputs } = partition2;
for (const [region, regionData] of Object.entries(regions)) {
if (region === value) {
return {
...outputs,
...regionData
};
}
}
}
for (const partition2 of partitions) {
const { regionRegex, outputs } = partition2;
if (new RegExp(regionRegex).test(value)) {
return {
...outputs
};
}
}
const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws");
if (!DEFAULT_PARTITION) {
throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
}
return {
...DEFAULT_PARTITION.outputs
};
}, "partition");
getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix");
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js
var awsEndpointFunctions;
var init_aws = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() {
init_import_meta_url();
init_dist_es32();
init_isVirtualHostableS3Bucket();
init_parseArn();
init_partition();
awsEndpointFunctions = {
isVirtualHostableS3Bucket,
parseArn,
partition
};
customEndpointFunctions.aws = awsEndpointFunctions;
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js
var init_resolveEndpoint2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() {
init_import_meta_url();
init_dist_es32();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js
var init_EndpointError2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() {
init_import_meta_url();
init_dist_es32();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js
var init_EndpointRuleObject3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js
var init_ErrorRuleObject3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js
var init_RuleSetObject3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js
var init_TreeRuleObject3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js
var init_shared4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js
var init_types8 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() {
init_import_meta_url();
init_EndpointError2();
init_EndpointRuleObject3();
init_ErrorRuleObject3();
init_RuleSetObject3();
init_TreeRuleObject3();
init_shared4();
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js
var init_dist_es33 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-endpoints@3.714.0/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() {
init_import_meta_url();
init_aws();
init_partition();
init_isIpAddress2();
init_resolveEndpoint2();
init_types8();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js
async function checkFeatures(context2, config, args) {
const request4 = args.request;
if (request4?.headers?.["smithy-protocol"] === "rpc-v2-cbor") {
setFeature(context2, "PROTOCOL_RPC_V2_CBOR", "M");
}
if (typeof config.retryStrategy === "function") {
const retryStrategy = await config.retryStrategy();
if (typeof retryStrategy.acquireInitialRetryToken === "function") {
if (retryStrategy.constructor?.name?.includes("Adaptive")) {
setFeature(context2, "RETRY_MODE_ADAPTIVE", "F");
} else {
setFeature(context2, "RETRY_MODE_STANDARD", "E");
}
} else {
setFeature(context2, "RETRY_MODE_LEGACY", "D");
}
}
if (typeof config.accountIdEndpointMode === "function") {
const endpointV2 = context2.endpointV2;
if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
setFeature(context2, "ACCOUNT_ID_ENDPOINT", "O");
}
switch (await config.accountIdEndpointMode?.()) {
case "disabled":
setFeature(context2, "ACCOUNT_ID_MODE_DISABLED", "Q");
break;
case "preferred":
setFeature(context2, "ACCOUNT_ID_MODE_PREFERRED", "P");
break;
case "required":
setFeature(context2, "ACCOUNT_ID_MODE_REQUIRED", "R");
break;
}
}
const identity = context2.__smithy_context?.selectedHttpAuthScheme?.identity;
if (identity?.$source) {
const credentials = identity;
if (credentials.accountId) {
setFeature(context2, "RESOLVED_ACCOUNT_ID", "T");
}
for (const [key, value] of Object.entries(credentials.$source ?? {})) {
setFeature(context2, key, value);
}
}
}
var ACCOUNT_ID_ENDPOINT_REGEX;
var init_check_features = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js"() {
init_import_meta_url();
init_dist_es21();
ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
__name(checkFeatures, "checkFeatures");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js
var USER_AGENT, X_AMZ_USER_AGENT, SPACE, UA_NAME_SEPARATOR, UA_NAME_ESCAPE_REGEX, UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR;
var init_constants11 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js"() {
init_import_meta_url();
USER_AGENT = "user-agent";
X_AMZ_USER_AGENT = "x-amz-user-agent";
SPACE = " ";
UA_NAME_SEPARATOR = "/";
UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
UA_ESCAPE_CHAR = "-";
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js
function encodeFeatures(features) {
let buffer = "";
for (const key in features) {
const val2 = features[key];
if (buffer.length + val2.length + 1 <= BYTE_LIMIT) {
if (buffer.length) {
buffer += "," + val2;
} else {
buffer += val2;
}
continue;
}
break;
}
return buffer;
}
var BYTE_LIMIT;
var init_encode_features = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js"() {
init_import_meta_url();
BYTE_LIMIT = 1024;
__name(encodeFeatures, "encodeFeatures");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js
var userAgentMiddleware, escapeUserAgent, getUserAgentMiddlewareOptions, getUserAgentPlugin;
var init_user_agent_middleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js"() {
init_import_meta_url();
init_dist_es33();
init_dist_es2();
init_check_features();
init_constants11();
init_encode_features();
userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context2) => async (args) => {
const { request: request4 } = args;
if (!HttpRequest.isInstance(request4)) {
return next(args);
}
const { headers } = request4;
const userAgent = context2?.userAgent?.map(escapeUserAgent) || [];
const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
await checkFeatures(context2, options, args);
const awsContext = context2;
defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context2.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`);
const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
const appId = await options.userAgentAppId();
if (appId) {
defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
}
const prefix = getUserAgentPrefix();
const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE);
const normalUAValue = [
...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
...customUserAgent
].join(SPACE);
if (options.runtime !== "browser") {
if (normalUAValue) {
headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
}
headers[USER_AGENT] = sdkUserAgentValue;
} else {
headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
}
return next({
...args,
request: request4
});
}, "userAgentMiddleware");
escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => {
const name2 = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
const version5 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
const prefixSeparatorIndex = name2.indexOf(UA_NAME_SEPARATOR);
const prefix = name2.substring(0, prefixSeparatorIndex);
let uaName = name2.substring(prefixSeparatorIndex + 1);
if (prefix === "api") {
uaName = uaName.toLowerCase();
}
return [prefix, uaName, version5].filter((item) => item && item.length > 0).reduce((acc, item, index) => {
switch (index) {
case 0:
return item;
case 1:
return `${acc}/${item}`;
default:
return `${acc}#${item}`;
}
}, "");
}, "escapeUserAgent");
getUserAgentMiddlewareOptions = {
name: "getUserAgentMiddleware",
step: "build",
priority: "low",
tags: ["SET_USER_AGENT", "USER_AGENT"],
override: true
};
getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
}, "applyToStack")
}), "getUserAgentPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js
var init_dist_es34 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.721.0/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js"() {
init_import_meta_url();
init_configurations();
init_user_agent_middleware();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js
var ENV_USE_DUALSTACK_ENDPOINT, CONFIG_USE_DUALSTACK_ENDPOINT, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS;
var init_NodeUseDualstackEndpointConfigOptions = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js"() {
init_import_meta_url();
init_dist_es29();
ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => booleanSelector(env6, ENV_USE_DUALSTACK_ENDPOINT, SelectorType2.ENV), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType2.CONFIG), "configFileSelector"),
default: false
};
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js
var ENV_USE_FIPS_ENDPOINT, CONFIG_USE_FIPS_ENDPOINT, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS;
var init_NodeUseFipsEndpointConfigOptions = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js"() {
init_import_meta_url();
init_dist_es29();
ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => booleanSelector(env6, ENV_USE_FIPS_ENDPOINT, SelectorType2.ENV), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType2.CONFIG), "configFileSelector"),
default: false
};
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js
var init_resolveCustomEndpointsConfig = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js"() {
init_import_meta_url();
init_dist_es4();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js
var init_getEndpointFromRegion = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js
var init_resolveEndpointsConfig = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js"() {
init_import_meta_url();
init_dist_es4();
init_getEndpointFromRegion();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js
var init_endpointsConfig = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js"() {
init_import_meta_url();
init_NodeUseDualstackEndpointConfigOptions();
init_NodeUseFipsEndpointConfigOptions();
init_resolveCustomEndpointsConfig();
init_resolveEndpointsConfig();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js
var REGION_ENV_NAME, REGION_INI_NAME, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS;
var init_config5 = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"() {
init_import_meta_url();
REGION_ENV_NAME = "AWS_REGION";
REGION_INI_NAME = "region";
NODE_REGION_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => env6[REGION_ENV_NAME], "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"),
default: /* @__PURE__ */ __name(() => {
throw new Error("Region is missing");
}, "default")
};
NODE_REGION_CONFIG_FILE_OPTIONS = {
preferredFile: "credentials"
};
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js
var isFipsRegion;
var init_isFipsRegion = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
init_import_meta_url();
isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js
var getRealRegion;
var init_getRealRegion = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js"() {
init_import_meta_url();
init_isFipsRegion();
getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js
var resolveRegionConfig;
var init_resolveRegionConfig = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
init_import_meta_url();
init_getRealRegion();
init_isFipsRegion();
resolveRegionConfig = /* @__PURE__ */ __name((input) => {
const { region, useFipsEndpoint } = input;
if (!region) {
throw new Error("Region is missing");
}
return {
...input,
region: /* @__PURE__ */ __name(async () => {
if (typeof region === "string") {
return getRealRegion(region);
}
const providedRegion = await region();
return getRealRegion(providedRegion);
}, "region"),
useFipsEndpoint: /* @__PURE__ */ __name(async () => {
const providedRegion = typeof region === "string" ? region : await region();
if (isFipsRegion(providedRegion)) {
return true;
}
return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
}, "useFipsEndpoint")
};
}, "resolveRegionConfig");
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js
var init_regionConfig = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js"() {
init_import_meta_url();
init_config5();
init_resolveRegionConfig();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js
var init_PartitionHash = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js
var init_RegionHash = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js
var init_getHostnameFromVariants = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js
var init_getResolvedHostname = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js
var init_getResolvedPartition = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js
var init_getResolvedSigningRegion = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js
var init_getRegionInfo = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js"() {
init_import_meta_url();
init_getHostnameFromVariants();
init_getResolvedHostname();
init_getResolvedPartition();
init_getResolvedSigningRegion();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js
var init_regionInfo = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js"() {
init_import_meta_url();
init_PartitionHash();
init_RegionHash();
init_getRegionInfo();
}
});
// ../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/index.js
var init_dist_es35 = __esm({
"../../node_modules/.pnpm/@smithy+config-resolver@3.0.13/node_modules/@smithy/config-resolver/dist-es/index.js"() {
init_import_meta_url();
init_endpointsConfig();
init_regionConfig();
init_regionInfo();
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@3.0.11/node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js
var resolveEventStreamSerdeConfig;
var init_EventStreamSerdeConfig = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@3.0.11/node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js"() {
init_import_meta_url();
resolveEventStreamSerdeConfig = /* @__PURE__ */ __name((input) => ({
...input,
eventStreamMarshaller: input.eventStreamSerdeProvider(input)
}), "resolveEventStreamSerdeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@3.0.11/node_modules/@smithy/eventstream-serde-config-resolver/dist-es/index.js
var init_dist_es36 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@3.0.11/node_modules/@smithy/eventstream-serde-config-resolver/dist-es/index.js"() {
init_import_meta_url();
init_EventStreamSerdeConfig();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-content-length@3.0.13/node_modules/@smithy/middleware-content-length/dist-es/index.js
function contentLengthMiddleware(bodyLengthChecker) {
return (next) => async (args) => {
const request4 = args.request;
if (HttpRequest.isInstance(request4)) {
const { body, headers } = request4;
if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER2) === -1) {
try {
const length = bodyLengthChecker(body);
request4.headers = {
...request4.headers,
[CONTENT_LENGTH_HEADER2]: String(length)
};
} catch (error2) {
}
}
}
return next({
...args,
request: request4
});
};
}
var CONTENT_LENGTH_HEADER2, contentLengthMiddlewareOptions, getContentLengthPlugin;
var init_dist_es37 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-content-length@3.0.13/node_modules/@smithy/middleware-content-length/dist-es/index.js"() {
init_import_meta_url();
init_dist_es2();
CONTENT_LENGTH_HEADER2 = "content-length";
__name(contentLengthMiddleware, "contentLengthMiddleware");
contentLengthMiddlewareOptions = {
step: "build",
tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
name: "contentLengthMiddleware",
override: true
};
getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
}, "applyToStack")
}), "getContentLengthPlugin");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js
var resolveParamsForS3, DOMAIN_PATTERN, IP_ADDRESS_PATTERN, DOTS_PATTERN, isDnsCompatibleBucketName, isArnBucketName;
var init_s3 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js"() {
init_import_meta_url();
resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => {
const bucket = endpointParams?.Bucket || "";
if (typeof endpointParams.Bucket === "string") {
endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
}
if (isArnBucketName(bucket)) {
if (endpointParams.ForcePathStyle === true) {
throw new Error("Path-style addressing cannot be used with ARN buckets");
}
} else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
endpointParams.ForcePathStyle = true;
}
if (endpointParams.DisableMultiRegionAccessPoints) {
endpointParams.disableMultiRegionAccessPoints = true;
endpointParams.DisableMRAP = true;
}
return endpointParams;
}, "resolveParamsForS3");
DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
DOTS_PATTERN = /\.\./;
isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName");
isArnBucketName = /* @__PURE__ */ __name((bucketName) => {
const [arn, partition2, service, , , bucket] = bucketName.split(":");
const isArn = arn === "arn" && bucketName.split(":").length >= 6;
const isValidArn = Boolean(isArn && partition2 && service && bucket);
if (isArn && !isValidArn) {
throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
}
return isValidArn;
}, "isArnBucketName");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js
var init_service_customizations = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js"() {
init_import_meta_url();
init_s3();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js
var createConfigValueProvider;
var init_createConfigValueProvider = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js"() {
init_import_meta_url();
createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => {
const configProvider = /* @__PURE__ */ __name(async () => {
const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
if (typeof configValue === "function") {
return configValue();
}
return configValue;
}, "configProvider");
if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
return async () => {
const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
const configValue = credentials?.credentialScope ?? credentials?.CredentialScope;
return configValue;
};
}
if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
return async () => {
const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
const configValue = credentials?.accountId ?? credentials?.AccountId;
return configValue;
};
}
if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
return async () => {
const endpoint = await configProvider();
if (endpoint && typeof endpoint === "object") {
if ("url" in endpoint) {
return endpoint.url.href;
}
if ("hostname" in endpoint) {
const { protocol, hostname: hostname2, port, path: path72 } = endpoint;
return `${protocol}//${hostname2}${port ? ":" + port : ""}${path72}`;
}
}
return endpoint;
};
}
return configProvider;
}, "createConfigValueProvider");
}
});
// ../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js
function getSelectorName(functionString) {
try {
const constants4 = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));
constants4.delete("CONFIG");
constants4.delete("CONFIG_PREFIX_SEPARATOR");
constants4.delete("ENV");
return [...constants4].join(", ");
} catch (e7) {
return functionString;
}
}
var init_getSelectorName = __esm({
"../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js"() {
init_import_meta_url();
__name(getSelectorName, "getSelectorName");
}
});
// ../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js
var fromEnv;
var init_fromEnv = __esm({
"../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/fromEnv.js"() {
init_import_meta_url();
init_dist_es17();
init_getSelectorName();
fromEnv = /* @__PURE__ */ __name((envVarSelector, logger4) => async () => {
try {
const config = envVarSelector(process.env);
if (config === void 0) {
throw new Error();
}
return config;
} catch (e7) {
throw new CredentialsProviderError(e7.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: logger4 });
}
}, "fromEnv");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js
var import_os5, import_path18, homeDirCache, getHomeDirCacheKey, getHomeDir;
var init_getHomeDir = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js"() {
init_import_meta_url();
import_os5 = require("os");
import_path18 = require("path");
homeDirCache = {};
getHomeDirCacheKey = /* @__PURE__ */ __name(() => {
if (process && process.geteuid) {
return `${process.geteuid()}`;
}
return "DEFAULT";
}, "getHomeDirCacheKey");
getHomeDir = /* @__PURE__ */ __name(() => {
const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${import_path18.sep}` } = process.env;
if (HOME)
return HOME;
if (USERPROFILE)
return USERPROFILE;
if (HOMEPATH)
return `${HOMEDRIVE}${HOMEPATH}`;
const homeDirCacheKey = getHomeDirCacheKey();
if (!homeDirCache[homeDirCacheKey])
homeDirCache[homeDirCacheKey] = (0, import_os5.homedir)();
return homeDirCache[homeDirCacheKey];
}, "getHomeDir");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js
var ENV_PROFILE, DEFAULT_PROFILE, getProfileName;
var init_getProfileName = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js"() {
init_import_meta_url();
ENV_PROFILE = "AWS_PROFILE";
DEFAULT_PROFILE = "default";
getProfileName = /* @__PURE__ */ __name((init3) => init3.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js
var import_crypto3, import_path19, getSSOTokenFilepath;
var init_getSSOTokenFilepath = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js"() {
init_import_meta_url();
import_crypto3 = require("crypto");
import_path19 = require("path");
init_getHomeDir();
getSSOTokenFilepath = /* @__PURE__ */ __name((id) => {
const hasher = (0, import_crypto3.createHash)("sha1");
const cacheName = hasher.update(id).digest("hex");
return (0, import_path19.join)(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`);
}, "getSSOTokenFilepath");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js
var import_fs18, readFile9, getSSOTokenFromFile;
var init_getSSOTokenFromFile = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js"() {
init_import_meta_url();
import_fs18 = require("fs");
init_getSSOTokenFilepath();
({ readFile: readFile9 } = import_fs18.promises);
getSSOTokenFromFile = /* @__PURE__ */ __name(async (id) => {
const ssoTokenFilepath = getSSOTokenFilepath(id);
const ssoTokenText = await readFile9(ssoTokenFilepath, "utf8");
return JSON.parse(ssoTokenText);
}, "getSSOTokenFromFile");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js
var getConfigData;
var init_getConfigData = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js"() {
init_import_meta_url();
init_dist_es();
init_loadSharedConfigFiles();
getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => {
const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
if (indexOfSeparator === -1) {
return false;
}
return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator));
}).reduce((acc, [key, value]) => {
const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
acc[updatedKey] = value;
return acc;
}, {
...data.default && { default: data.default }
}), "getConfigData");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js
var import_path20, ENV_CONFIG_PATH, getConfigFilepath;
var init_getConfigFilepath = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js"() {
init_import_meta_url();
import_path20 = require("path");
init_getHomeDir();
ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path20.join)(getHomeDir(), ".aws", "config"), "getConfigFilepath");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js
var import_path21, ENV_CREDENTIALS_PATH, getCredentialsFilepath;
var init_getCredentialsFilepath = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js"() {
init_import_meta_url();
import_path21 = require("path");
init_getHomeDir();
ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path21.join)(getHomeDir(), ".aws", "credentials"), "getCredentialsFilepath");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js
var prefixKeyRegex, profileNameBlockList, parseIni;
var init_parseIni = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js"() {
init_import_meta_url();
init_dist_es();
init_loadSharedConfigFiles();
prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
profileNameBlockList = ["__proto__", "profile __proto__"];
parseIni = /* @__PURE__ */ __name((iniData) => {
const map2 = {};
let currentSection;
let currentSubSection;
for (const iniLine of iniData.split(/\r?\n/)) {
const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
if (isSection) {
currentSection = void 0;
currentSubSection = void 0;
const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
const matches = prefixKeyRegex.exec(sectionName);
if (matches) {
const [, prefix, , name2] = matches;
if (Object.values(IniSectionType).includes(prefix)) {
currentSection = [prefix, name2].join(CONFIG_PREFIX_SEPARATOR);
}
} else {
currentSection = sectionName;
}
if (profileNameBlockList.includes(sectionName)) {
throw new Error(`Found invalid profile name "${sectionName}"`);
}
} else if (currentSection) {
const indexOfEqualsSign = trimmedLine.indexOf("=");
if (![0, -1].includes(indexOfEqualsSign)) {
const [name2, value] = [
trimmedLine.substring(0, indexOfEqualsSign).trim(),
trimmedLine.substring(indexOfEqualsSign + 1).trim()
];
if (value === "") {
currentSubSection = name2;
} else {
if (currentSubSection && iniLine.trimStart() === iniLine) {
currentSubSection = void 0;
}
map2[currentSection] = map2[currentSection] || {};
const key = currentSubSection ? [currentSubSection, name2].join(CONFIG_PREFIX_SEPARATOR) : name2;
map2[currentSection][key] = value;
}
}
}
}
return map2;
}, "parseIni");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js
var import_fs19, readFile10, filePromisesHash, slurpFile;
var init_slurpFile = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/slurpFile.js"() {
init_import_meta_url();
import_fs19 = require("fs");
({ readFile: readFile10 } = import_fs19.promises);
filePromisesHash = {};
slurpFile = /* @__PURE__ */ __name((path72, options) => {
if (!filePromisesHash[path72] || options?.ignoreCache) {
filePromisesHash[path72] = readFile10(path72, "utf8");
}
return filePromisesHash[path72];
}, "slurpFile");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js
var import_path22, swallowError, CONFIG_PREFIX_SEPARATOR, loadSharedConfigFiles;
var init_loadSharedConfigFiles = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js"() {
init_import_meta_url();
import_path22 = require("path");
init_getConfigData();
init_getConfigFilepath();
init_getCredentialsFilepath();
init_getHomeDir();
init_parseIni();
init_slurpFile();
swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError");
CONFIG_PREFIX_SEPARATOR = ".";
loadSharedConfigFiles = /* @__PURE__ */ __name(async (init3 = {}) => {
const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init3;
const homeDir = getHomeDir();
const relativeHomeDirPrefix = "~/";
let resolvedFilepath = filepath;
if (filepath.startsWith(relativeHomeDirPrefix)) {
resolvedFilepath = (0, import_path22.join)(homeDir, filepath.slice(2));
}
let resolvedConfigFilepath = configFilepath;
if (configFilepath.startsWith(relativeHomeDirPrefix)) {
resolvedConfigFilepath = (0, import_path22.join)(homeDir, configFilepath.slice(2));
}
const parsedFiles = await Promise.all([
slurpFile(resolvedConfigFilepath, {
ignoreCache: init3.ignoreCache
}).then(parseIni).then(getConfigData).catch(swallowError),
slurpFile(resolvedFilepath, {
ignoreCache: init3.ignoreCache
}).then(parseIni).catch(swallowError)
]);
return {
configFile: parsedFiles[0],
credentialsFile: parsedFiles[1]
};
}, "loadSharedConfigFiles");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js
var getSsoSessionData;
var init_getSsoSessionData = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js"() {
init_import_meta_url();
init_dist_es();
init_loadSharedConfigFiles();
getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js
var swallowError2, loadSsoSessionData;
var init_loadSsoSessionData = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js"() {
init_import_meta_url();
init_getConfigFilepath();
init_getSsoSessionData();
init_parseIni();
init_slurpFile();
swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError");
loadSsoSessionData = /* @__PURE__ */ __name(async (init3 = {}) => slurpFile(init3.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js
var mergeConfigFiles;
var init_mergeConfigFiles = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js"() {
init_import_meta_url();
mergeConfigFiles = /* @__PURE__ */ __name((...files) => {
const merged = {};
for (const file of files) {
for (const [key, values] of Object.entries(file)) {
if (merged[key] !== void 0) {
Object.assign(merged[key], values);
} else {
merged[key] = values;
}
}
}
return merged;
}, "mergeConfigFiles");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js
var parseKnownFiles;
var init_parseKnownFiles = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js"() {
init_import_meta_url();
init_loadSharedConfigFiles();
init_mergeConfigFiles();
parseKnownFiles = /* @__PURE__ */ __name(async (init3) => {
const parsedFiles = await loadSharedConfigFiles(init3);
return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
}, "parseKnownFiles");
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js
var init_types9 = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js
var init_dist_es38 = __esm({
"../../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.1.12/node_modules/@smithy/shared-ini-file-loader/dist-es/index.js"() {
init_import_meta_url();
init_getHomeDir();
init_getProfileName();
init_getSSOTokenFilepath();
init_getSSOTokenFromFile();
init_loadSharedConfigFiles();
init_loadSsoSessionData();
init_parseKnownFiles();
init_types9();
}
});
// ../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js
var fromSharedConfigFiles;
var init_fromSharedConfigFiles = __esm({
"../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js"() {
init_import_meta_url();
init_dist_es17();
init_dist_es38();
init_getSelectorName();
fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init3 } = {}) => async () => {
const profile = getProfileName(init3);
const { configFile, credentialsFile } = await loadSharedConfigFiles(init3);
const profileFromCredentials = credentialsFile[profile] || {};
const profileFromConfig = configFile[profile] || {};
const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials };
try {
const cfgFile = preferredFile === "config" ? configFile : credentialsFile;
const configValue = configSelector(mergedProfile, cfgFile);
if (configValue === void 0) {
throw new Error();
}
return configValue;
} catch (e7) {
throw new CredentialsProviderError(e7.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init3.logger });
}
}, "fromSharedConfigFiles");
}
});
// ../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js
var isFunction2, fromStatic2;
var init_fromStatic2 = __esm({
"../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/fromStatic.js"() {
init_import_meta_url();
init_dist_es17();
isFunction2 = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction");
fromStatic2 = /* @__PURE__ */ __name((defaultValue) => isFunction2(defaultValue) ? async () => await defaultValue() : fromStatic(defaultValue), "fromStatic");
}
});
// ../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/configLoader.js
var loadConfig;
var init_configLoader = __esm({
"../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/configLoader.js"() {
init_import_meta_url();
init_dist_es17();
init_fromEnv();
init_fromSharedConfigFiles();
init_fromStatic2();
loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => memoize(chain(fromEnv(environmentVariableSelector), fromSharedConfigFiles(configFileSelector, configuration), fromStatic2(defaultValue))), "loadConfig");
}
});
// ../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/index.js
var init_dist_es39 = __esm({
"../../node_modules/.pnpm/@smithy+node-config-provider@3.1.12/node_modules/@smithy/node-config-provider/dist-es/index.js"() {
init_import_meta_url();
init_configLoader();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js
var ENV_ENDPOINT_URL, CONFIG_ENDPOINT_URL, getEndpointUrlConfig;
var init_getEndpointUrlConfig = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js"() {
init_import_meta_url();
init_dist_es38();
ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
CONFIG_ENDPOINT_URL = "endpoint_url";
getEndpointUrlConfig = /* @__PURE__ */ __name((serviceId) => ({
environmentVariableSelector: /* @__PURE__ */ __name((env6) => {
const serviceSuffixParts = serviceId.split(" ").map((w6) => w6.toUpperCase());
const serviceEndpointUrl = env6[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
if (serviceEndpointUrl)
return serviceEndpointUrl;
const endpointUrl = env6[ENV_ENDPOINT_URL];
if (endpointUrl)
return endpointUrl;
return void 0;
}, "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile, config) => {
if (config && profile.services) {
const servicesSection = config[["services", profile.services].join(CONFIG_PREFIX_SEPARATOR)];
if (servicesSection) {
const servicePrefixParts = serviceId.split(" ").map((w6) => w6.toLowerCase());
const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)];
if (endpointUrl2)
return endpointUrl2;
}
}
const endpointUrl = profile[CONFIG_ENDPOINT_URL];
if (endpointUrl)
return endpointUrl;
return void 0;
}, "configFileSelector"),
default: void 0
}), "getEndpointUrlConfig");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js
var getEndpointFromConfig;
var init_getEndpointFromConfig = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js"() {
init_import_meta_url();
init_dist_es39();
init_getEndpointUrlConfig();
getEndpointFromConfig = /* @__PURE__ */ __name(async (serviceId) => loadConfig(getEndpointUrlConfig(serviceId ?? ""))(), "getEndpointFromConfig");
}
});
// ../../node_modules/.pnpm/@smithy+querystring-parser@3.0.11/node_modules/@smithy/querystring-parser/dist-es/index.js
function parseQueryString(querystring) {
const query = {};
querystring = querystring.replace(/^\?/, "");
if (querystring) {
for (const pair of querystring.split("&")) {
let [key, value = null] = pair.split("=");
key = decodeURIComponent(key);
if (value) {
value = decodeURIComponent(value);
}
if (!(key in query)) {
query[key] = value;
} else if (Array.isArray(query[key])) {
query[key].push(value);
} else {
query[key] = [query[key], value];
}
}
}
return query;
}
var init_dist_es40 = __esm({
"../../node_modules/.pnpm/@smithy+querystring-parser@3.0.11/node_modules/@smithy/querystring-parser/dist-es/index.js"() {
init_import_meta_url();
__name(parseQueryString, "parseQueryString");
}
});
// ../../node_modules/.pnpm/@smithy+url-parser@3.0.11/node_modules/@smithy/url-parser/dist-es/index.js
var parseUrl;
var init_dist_es41 = __esm({
"../../node_modules/.pnpm/@smithy+url-parser@3.0.11/node_modules/@smithy/url-parser/dist-es/index.js"() {
init_import_meta_url();
init_dist_es40();
parseUrl = /* @__PURE__ */ __name((url4) => {
if (typeof url4 === "string") {
return parseUrl(new URL(url4));
}
const { hostname: hostname2, pathname, port, protocol, search } = url4;
let query;
if (search) {
query = parseQueryString(search);
}
return {
hostname: hostname2,
port: port ? parseInt(port) : void 0,
protocol,
path: pathname,
query
};
}, "parseUrl");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js
var toEndpointV1;
var init_toEndpointV1 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js"() {
init_import_meta_url();
init_dist_es41();
toEndpointV1 = /* @__PURE__ */ __name((endpoint) => {
if (typeof endpoint === "object") {
if ("url" in endpoint) {
return parseUrl(endpoint.url);
}
return endpoint;
}
return parseUrl(endpoint);
}, "toEndpointV1");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js
var getEndpointFromInstructions, resolveParams;
var init_getEndpointFromInstructions = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js"() {
init_import_meta_url();
init_service_customizations();
init_createConfigValueProvider();
init_getEndpointFromConfig();
init_toEndpointV1();
getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context2) => {
if (!clientConfig.endpoint) {
let endpointFromConfig;
if (clientConfig.serviceConfiguredEndpoint) {
endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
} else {
endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId);
}
if (endpointFromConfig) {
clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
}
}
const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
if (typeof clientConfig.endpointProvider !== "function") {
throw new Error("config.endpointProvider is not set.");
}
const endpoint = clientConfig.endpointProvider(endpointParams, context2);
return endpoint;
}, "getEndpointFromInstructions");
resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => {
const endpointParams = {};
const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};
for (const [name2, instruction] of Object.entries(instructions)) {
switch (instruction.type) {
case "staticContextParams":
endpointParams[name2] = instruction.value;
break;
case "contextParams":
endpointParams[name2] = commandInput[instruction.name];
break;
case "clientContextParams":
case "builtInParams":
endpointParams[name2] = await createConfigValueProvider(instruction.name, name2, clientConfig)();
break;
case "operationContextParams":
endpointParams[name2] = instruction.get(commandInput);
break;
default:
throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
}
}
if (Object.keys(instructions).length === 0) {
Object.assign(endpointParams, clientConfig);
}
if (String(clientConfig.serviceId).toLowerCase() === "s3") {
await resolveParamsForS3(endpointParams);
}
return endpointParams;
}, "resolveParams");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js
var init_adaptors = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js"() {
init_import_meta_url();
init_getEndpointFromInstructions();
init_toEndpointV1();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js
var endpointMiddleware;
var init_endpointMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js"() {
init_import_meta_url();
init_dist_es16();
init_dist_es4();
init_getEndpointFromInstructions();
endpointMiddleware = /* @__PURE__ */ __name(({ config, instructions }) => {
return (next, context2) => async (args) => {
if (config.endpoint) {
setFeature2(context2, "ENDPOINT_OVERRIDE", "N");
}
const endpoint = await getEndpointFromInstructions(args.input, {
getEndpointParameterInstructions() {
return instructions;
}
}, { ...config }, context2);
context2.endpointV2 = endpoint;
context2.authSchemes = endpoint.properties?.authSchemes;
const authScheme = context2.authSchemes?.[0];
if (authScheme) {
context2["signing_region"] = authScheme.signingRegion;
context2["signing_service"] = authScheme.signingName;
const smithyContext = getSmithyContext(context2);
const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;
if (httpAuthOption) {
httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {
signing_region: authScheme.signingRegion,
signingRegion: authScheme.signingRegion,
signing_service: authScheme.signingName,
signingName: authScheme.signingName,
signingRegionSet: authScheme.signingRegionSet
}, authScheme.properties);
}
}
return next({
...args
});
};
}, "endpointMiddleware");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js
var endpointMiddlewareOptions, getEndpointPlugin;
var init_getEndpointPlugin = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js"() {
init_import_meta_url();
init_dist_es5();
init_endpointMiddleware();
endpointMiddlewareOptions = {
step: "serialize",
tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
name: "endpointV2Middleware",
override: true,
relation: "before",
toMiddleware: serializerMiddlewareOption.name
};
getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.addRelativeTo(endpointMiddleware({
config,
instructions
}), endpointMiddlewareOptions);
}, "applyToStack")
}), "getEndpointPlugin");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js
var resolveEndpointConfig;
var init_resolveEndpointConfig = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js"() {
init_import_meta_url();
init_dist_es4();
init_getEndpointFromConfig();
init_toEndpointV1();
resolveEndpointConfig = /* @__PURE__ */ __name((input) => {
const tls = input.tls ?? true;
const { endpoint } = input;
const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0;
const isCustomEndpoint = !!endpoint;
const resolvedConfig = {
...input,
endpoint: customEndpointProvider,
tls,
isCustomEndpoint,
useDualstackEndpoint: normalizeProvider(input.useDualstackEndpoint ?? false),
useFipsEndpoint: normalizeProvider(input.useFipsEndpoint ?? false)
};
let configuredEndpointPromise = void 0;
resolvedConfig.serviceConfiguredEndpoint = async () => {
if (input.serviceId && !configuredEndpointPromise) {
configuredEndpointPromise = getEndpointFromConfig(input.serviceId);
}
return configuredEndpointPromise;
};
return resolvedConfig;
}, "resolveEndpointConfig");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/types.js
var init_types10 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/index.js
var init_dist_es42 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-endpoint@3.2.8/node_modules/@smithy/middleware-endpoint/dist-es/index.js"() {
init_import_meta_url();
init_adaptors();
init_endpointMiddleware();
init_getEndpointPlugin();
init_resolveEndpointConfig();
init_types10();
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/config.js
var RETRY_MODES, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE;
var init_config6 = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/config.js"() {
init_import_meta_url();
(function(RETRY_MODES2) {
RETRY_MODES2["STANDARD"] = "standard";
RETRY_MODES2["ADAPTIVE"] = "adaptive";
})(RETRY_MODES || (RETRY_MODES = {}));
DEFAULT_MAX_ATTEMPTS = 3;
DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD;
}
});
// ../../node_modules/.pnpm/@smithy+service-error-classification@3.0.11/node_modules/@smithy/service-error-classification/dist-es/constants.js
var THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, NODEJS_TIMEOUT_ERROR_CODES2;
var init_constants12 = __esm({
"../../node_modules/.pnpm/@smithy+service-error-classification@3.0.11/node_modules/@smithy/service-error-classification/dist-es/constants.js"() {
init_import_meta_url();
THROTTLING_ERROR_CODES = [
"BandwidthLimitExceeded",
"EC2ThrottledException",
"LimitExceededException",
"PriorRequestNotComplete",
"ProvisionedThroughputExceededException",
"RequestLimitExceeded",
"RequestThrottled",
"RequestThrottledException",
"SlowDown",
"ThrottledException",
"Throttling",
"ThrottlingException",
"TooManyRequestsException",
"TransactionInProgressException"
];
TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
NODEJS_TIMEOUT_ERROR_CODES2 = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
}
});
// ../../node_modules/.pnpm/@smithy+service-error-classification@3.0.11/node_modules/@smithy/service-error-classification/dist-es/index.js
var isClockSkewCorrectedError, isThrottlingError, isTransientError, isServerError;
var init_dist_es43 = __esm({
"../../node_modules/.pnpm/@smithy+service-error-classification@3.0.11/node_modules/@smithy/service-error-classification/dist-es/index.js"() {
init_import_meta_url();
init_constants12();
isClockSkewCorrectedError = /* @__PURE__ */ __name((error2) => error2.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError");
isThrottlingError = /* @__PURE__ */ __name((error2) => error2.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || error2.$retryable?.throttling == true, "isThrottlingError");
isTransientError = /* @__PURE__ */ __name((error2, depth = 0) => isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES2.includes(error2?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error2.$metadata?.httpStatusCode || 0) || error2.cause !== void 0 && depth <= 10 && isTransientError(error2.cause, depth + 1), "isTransientError");
isServerError = /* @__PURE__ */ __name((error2) => {
if (error2.$metadata?.httpStatusCode !== void 0) {
const statusCode = error2.$metadata.httpStatusCode;
if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) {
return true;
}
return false;
}
return false;
}, "isServerError");
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js
var DefaultRateLimiter;
var init_DefaultRateLimiter = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js"() {
init_import_meta_url();
init_dist_es43();
DefaultRateLimiter = class _DefaultRateLimiter {
static {
__name(this, "DefaultRateLimiter");
}
constructor(options) {
this.currentCapacity = 0;
this.enabled = false;
this.lastMaxRate = 0;
this.measuredTxRate = 0;
this.requestCount = 0;
this.lastTimestamp = 0;
this.timeWindow = 0;
this.beta = options?.beta ?? 0.7;
this.minCapacity = options?.minCapacity ?? 1;
this.minFillRate = options?.minFillRate ?? 0.5;
this.scaleConstant = options?.scaleConstant ?? 0.4;
this.smooth = options?.smooth ?? 0.8;
const currentTimeInSeconds = this.getCurrentTimeInSeconds();
this.lastThrottleTime = currentTimeInSeconds;
this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
this.fillRate = this.minFillRate;
this.maxCapacity = this.minCapacity;
}
getCurrentTimeInSeconds() {
return Date.now() / 1e3;
}
async getSendToken() {
return this.acquireTokenBucket(1);
}
async acquireTokenBucket(amount) {
if (!this.enabled) {
return;
}
this.refillTokenBucket();
if (amount > this.currentCapacity) {
const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
await new Promise((resolve25) => _DefaultRateLimiter.setTimeoutFn(resolve25, delay));
}
this.currentCapacity = this.currentCapacity - amount;
}
refillTokenBucket() {
const timestamp = this.getCurrentTimeInSeconds();
if (!this.lastTimestamp) {
this.lastTimestamp = timestamp;
return;
}
const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
this.lastTimestamp = timestamp;
}
updateClientSendingRate(response) {
let calculatedRate;
this.updateMeasuredRate();
if (isThrottlingError(response)) {
const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
this.lastMaxRate = rateToUse;
this.calculateTimeWindow();
this.lastThrottleTime = this.getCurrentTimeInSeconds();
calculatedRate = this.cubicThrottle(rateToUse);
this.enableTokenBucket();
} else {
this.calculateTimeWindow();
calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
}
const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
this.updateTokenBucketRate(newRate);
}
calculateTimeWindow() {
this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
}
cubicThrottle(rateToUse) {
return this.getPrecise(rateToUse * this.beta);
}
cubicSuccess(timestamp) {
return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
}
enableTokenBucket() {
this.enabled = true;
}
updateTokenBucketRate(newRate) {
this.refillTokenBucket();
this.fillRate = Math.max(newRate, this.minFillRate);
this.maxCapacity = Math.max(newRate, this.minCapacity);
this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
}
updateMeasuredRate() {
const t7 = this.getCurrentTimeInSeconds();
const timeBucket = Math.floor(t7 * 2) / 2;
this.requestCount++;
if (timeBucket > this.lastTxRateBucket) {
const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
this.requestCount = 0;
this.lastTxRateBucket = timeBucket;
}
}
getPrecise(num) {
return parseFloat(num.toFixed(8));
}
};
DefaultRateLimiter.setTimeoutFn = setTimeout;
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/constants.js
var DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY, THROTTLING_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, RETRY_COST, TIMEOUT_RETRY_COST, NO_RETRY_INCREMENT, INVOCATION_ID_HEADER, REQUEST_HEADER;
var init_constants13 = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/constants.js"() {
init_import_meta_url();
DEFAULT_RETRY_DELAY_BASE = 100;
MAXIMUM_RETRY_DELAY = 20 * 1e3;
THROTTLING_RETRY_DELAY_BASE = 500;
INITIAL_RETRY_TOKENS = 500;
RETRY_COST = 5;
TIMEOUT_RETRY_COST = 10;
NO_RETRY_INCREMENT = 1;
INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
REQUEST_HEADER = "amz-sdk-request";
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js
var getDefaultRetryBackoffStrategy;
var init_defaultRetryBackoffStrategy = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js"() {
init_import_meta_url();
init_constants13();
getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => {
let delayBase = DEFAULT_RETRY_DELAY_BASE;
const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => {
return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
}, "computeNextBackoffDelay");
const setDelayBase = /* @__PURE__ */ __name((delay) => {
delayBase = delay;
}, "setDelayBase");
return {
computeNextBackoffDelay,
setDelayBase
};
}, "getDefaultRetryBackoffStrategy");
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js
var createDefaultRetryToken;
var init_defaultRetryToken = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js"() {
init_import_meta_url();
init_constants13();
createDefaultRetryToken = /* @__PURE__ */ __name(({ retryDelay, retryCount, retryCost }) => {
const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount");
const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay");
const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost");
return {
getRetryCount,
getRetryDelay,
getRetryCost
};
}, "createDefaultRetryToken");
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js
var StandardRetryStrategy;
var init_StandardRetryStrategy = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js"() {
init_import_meta_url();
init_config6();
init_constants13();
init_defaultRetryBackoffStrategy();
init_defaultRetryToken();
StandardRetryStrategy = class {
static {
__name(this, "StandardRetryStrategy");
}
constructor(maxAttempts) {
this.maxAttempts = maxAttempts;
this.mode = RETRY_MODES.STANDARD;
this.capacity = INITIAL_RETRY_TOKENS;
this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
}
async acquireInitialRetryToken(retryTokenScope) {
return createDefaultRetryToken({
retryDelay: DEFAULT_RETRY_DELAY_BASE,
retryCount: 0
});
}
async refreshRetryTokenForRetry(token, errorInfo) {
const maxAttempts = await this.getMaxAttempts();
if (this.shouldRetry(token, errorInfo, maxAttempts)) {
const errorType = errorInfo.errorType;
this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
const capacityCost = this.getCapacityCost(errorType);
this.capacity -= capacityCost;
return createDefaultRetryToken({
retryDelay,
retryCount: token.getRetryCount() + 1,
retryCost: capacityCost
});
}
throw new Error("No retry token available");
}
recordSuccess(token) {
this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
}
getCapacity() {
return this.capacity;
}
async getMaxAttempts() {
try {
return await this.maxAttemptsProvider();
} catch (error2) {
console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
return DEFAULT_MAX_ATTEMPTS;
}
}
shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
const attempts = tokenToRenew.getRetryCount() + 1;
return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
}
getCapacityCost(errorType) {
return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
}
isRetryableError(errorType) {
return errorType === "THROTTLING" || errorType === "TRANSIENT";
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js
var AdaptiveRetryStrategy;
var init_AdaptiveRetryStrategy = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js"() {
init_import_meta_url();
init_config6();
init_DefaultRateLimiter();
init_StandardRetryStrategy();
AdaptiveRetryStrategy = class {
static {
__name(this, "AdaptiveRetryStrategy");
}
constructor(maxAttemptsProvider, options) {
this.maxAttemptsProvider = maxAttemptsProvider;
this.mode = RETRY_MODES.ADAPTIVE;
const { rateLimiter } = options ?? {};
this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
}
async acquireInitialRetryToken(retryTokenScope) {
await this.rateLimiter.getSendToken();
return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
}
async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
this.rateLimiter.updateClientSendingRate(errorInfo);
return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
}
recordSuccess(token) {
this.rateLimiter.updateClientSendingRate({});
this.standardRetryStrategy.recordSuccess(token);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js
var init_ConfiguredRetryStrategy = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js"() {
init_import_meta_url();
init_constants13();
init_StandardRetryStrategy();
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/types.js
var init_types11 = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/index.js
var init_dist_es44 = __esm({
"../../node_modules/.pnpm/@smithy+util-retry@3.0.11/node_modules/@smithy/util-retry/dist-es/index.js"() {
init_import_meta_url();
init_AdaptiveRetryStrategy();
init_ConfiguredRetryStrategy();
init_DefaultRateLimiter();
init_StandardRetryStrategy();
init_config6();
init_constants13();
init_types11();
}
});
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
import_crypto4.default.randomFillSync(rnds8Pool);
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
var import_crypto4, rnds8Pool, poolPtr;
var init_rng = __esm({
"../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js"() {
init_import_meta_url();
import_crypto4 = __toESM(require("crypto"));
rnds8Pool = new Uint8Array(256);
poolPtr = rnds8Pool.length;
__name(rng, "rng");
}
});
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
function unsafeStringify(arr, offset = 0) {
return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
var byteToHex;
var init_stringify = __esm({
"../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() {
init_import_meta_url();
byteToHex = [];
for (let i5 = 0; i5 < 256; ++i5) {
byteToHex.push((i5 + 256).toString(16).slice(1));
}
__name(unsafeStringify, "unsafeStringify");
}
});
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
var import_crypto5, native_default;
var init_native = __esm({
"../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() {
init_import_meta_url();
import_crypto5 = __toESM(require("crypto"));
native_default = {
randomUUID: import_crypto5.default.randomUUID
};
}
});
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js
function v4(options, buf, offset) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i5 = 0; i5 < 16; ++i5) {
buf[offset + i5] = rnds[i5];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default;
var init_v4 = __esm({
"../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js"() {
init_import_meta_url();
init_native();
init_rng();
init_stringify();
__name(v4, "v4");
v4_default = v4;
}
});
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js
var init_esm_node = __esm({
"../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() {
init_import_meta_url();
init_v4();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js
var init_defaultRetryQuota = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js"() {
init_import_meta_url();
init_dist_es44();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js
var init_delayDecider = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/delayDecider.js"() {
init_import_meta_url();
init_dist_es44();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js
var init_retryDecider = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/retryDecider.js"() {
init_import_meta_url();
init_dist_es43();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/util.js
var asSdkError;
var init_util3 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/util.js"() {
init_import_meta_url();
asSdkError = /* @__PURE__ */ __name((error2) => {
if (error2 instanceof Error)
return error2;
if (error2 instanceof Object)
return Object.assign(new Error(), error2);
if (typeof error2 === "string")
return new Error(error2);
return new Error(`AWS SDK error wrapper for ${error2}`);
}, "asSdkError");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js
var init_StandardRetryStrategy2 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es43();
init_dist_es44();
init_defaultRetryQuota();
init_delayDecider();
init_retryDecider();
init_util3();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js
var init_AdaptiveRetryStrategy2 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js"() {
init_import_meta_url();
init_dist_es44();
init_StandardRetryStrategy2();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/configurations.js
var ENV_MAX_ATTEMPTS, CONFIG_MAX_ATTEMPTS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, ENV_RETRY_MODE, CONFIG_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS;
var init_configurations2 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/configurations.js"() {
init_import_meta_url();
init_dist_es4();
init_dist_es44();
ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
CONFIG_MAX_ATTEMPTS = "max_attempts";
NODE_MAX_ATTEMPT_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => {
const value = env6[ENV_MAX_ATTEMPTS];
if (!value)
return void 0;
const maxAttempt = parseInt(value);
if (Number.isNaN(maxAttempt)) {
throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`);
}
return maxAttempt;
}, "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => {
const value = profile[CONFIG_MAX_ATTEMPTS];
if (!value)
return void 0;
const maxAttempt = parseInt(value);
if (Number.isNaN(maxAttempt)) {
throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`);
}
return maxAttempt;
}, "configFileSelector"),
default: DEFAULT_MAX_ATTEMPTS
};
resolveRetryConfig = /* @__PURE__ */ __name((input) => {
const { retryStrategy } = input;
const maxAttempts = normalizeProvider(input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
return {
...input,
maxAttempts,
retryStrategy: /* @__PURE__ */ __name(async () => {
if (retryStrategy) {
return retryStrategy;
}
const retryMode = await normalizeProvider(input.retryMode)();
if (retryMode === RETRY_MODES.ADAPTIVE) {
return new AdaptiveRetryStrategy(maxAttempts);
}
return new StandardRetryStrategy(maxAttempts);
}, "retryStrategy")
};
}, "resolveRetryConfig");
ENV_RETRY_MODE = "AWS_RETRY_MODE";
CONFIG_RETRY_MODE = "retry_mode";
NODE_RETRY_MODE_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => env6[ENV_RETRY_MODE], "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => profile[CONFIG_RETRY_MODE], "configFileSelector"),
default: DEFAULT_RETRY_MODE
};
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js
var init_omitRetryHeadersMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es44();
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js
var import_stream12, isStreamingPayload;
var init_isStreamingPayload = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js"() {
init_import_meta_url();
import_stream12 = require("stream");
isStreamingPayload = /* @__PURE__ */ __name((request4) => request4?.body instanceof import_stream12.Readable || typeof ReadableStream !== "undefined" && request4?.body instanceof ReadableStream, "isStreamingPayload");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js
var retryMiddleware, isRetryStrategyV2, getRetryErrorInfo, getRetryErrorType, retryMiddlewareOptions, getRetryPlugin, getRetryAfterHint;
var init_retryMiddleware = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js"() {
init_import_meta_url();
init_dist_es2();
init_dist_es43();
init_dist_es20();
init_dist_es44();
init_esm_node();
init_isStreamingPayload();
init_util3();
retryMiddleware = /* @__PURE__ */ __name((options) => (next, context2) => async (args) => {
let retryStrategy = await options.retryStrategy();
const maxAttempts = await options.maxAttempts();
if (isRetryStrategyV2(retryStrategy)) {
retryStrategy = retryStrategy;
let retryToken = await retryStrategy.acquireInitialRetryToken(context2["partition_id"]);
let lastError = new Error();
let attempts = 0;
let totalRetryDelay = 0;
const { request: request4 } = args;
const isRequest = HttpRequest.isInstance(request4);
if (isRequest) {
request4.headers[INVOCATION_ID_HEADER] = v4_default();
}
while (true) {
try {
if (isRequest) {
request4.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
}
const { response, output } = await next(args);
retryStrategy.recordSuccess(retryToken);
output.$metadata.attempts = attempts + 1;
output.$metadata.totalRetryDelay = totalRetryDelay;
return { response, output };
} catch (e7) {
const retryErrorInfo = getRetryErrorInfo(e7);
lastError = asSdkError(e7);
if (isRequest && isStreamingPayload(request4)) {
(context2.logger instanceof NoOpLogger ? console : context2.logger)?.warn("An error was encountered in a non-retryable streaming request.");
throw lastError;
}
try {
retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
} catch (refreshError) {
if (!lastError.$metadata) {
lastError.$metadata = {};
}
lastError.$metadata.attempts = attempts + 1;
lastError.$metadata.totalRetryDelay = totalRetryDelay;
throw lastError;
}
attempts = retryToken.getRetryCount();
const delay = retryToken.getRetryDelay();
totalRetryDelay += delay;
await new Promise((resolve25) => setTimeout(resolve25, delay));
}
}
} else {
retryStrategy = retryStrategy;
if (retryStrategy?.mode)
context2.userAgent = [...context2.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
return retryStrategy.retry(next, args);
}
}, "retryMiddleware");
isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2");
getRetryErrorInfo = /* @__PURE__ */ __name((error2) => {
const errorInfo = {
error: error2,
errorType: getRetryErrorType(error2)
};
const retryAfterHint = getRetryAfterHint(error2.$response);
if (retryAfterHint) {
errorInfo.retryAfterHint = retryAfterHint;
}
return errorInfo;
}, "getRetryErrorInfo");
getRetryErrorType = /* @__PURE__ */ __name((error2) => {
if (isThrottlingError(error2))
return "THROTTLING";
if (isTransientError(error2))
return "TRANSIENT";
if (isServerError(error2))
return "SERVER_ERROR";
return "CLIENT_ERROR";
}, "getRetryErrorType");
retryMiddlewareOptions = {
name: "retryMiddleware",
tags: ["RETRY"],
step: "finalizeRequest",
priority: "high",
override: true
};
getRetryPlugin = /* @__PURE__ */ __name((options) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
}, "applyToStack")
}), "getRetryPlugin");
getRetryAfterHint = /* @__PURE__ */ __name((response) => {
if (!HttpResponse.isInstance(response))
return;
const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
if (!retryAfterHeaderName)
return;
const retryAfter = response.headers[retryAfterHeaderName];
const retryAfterSeconds = Number(retryAfter);
if (!Number.isNaN(retryAfterSeconds))
return new Date(retryAfterSeconds * 1e3);
const retryAfterDate = new Date(retryAfter);
return retryAfterDate;
}, "getRetryAfterHint");
}
});
// ../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/index.js
var init_dist_es45 = __esm({
"../../node_modules/.pnpm/@smithy+middleware-retry@3.0.34/node_modules/@smithy/middleware-retry/dist-es/index.js"() {
init_import_meta_url();
init_AdaptiveRetryStrategy2();
init_StandardRetryStrategy2();
init_configurations2();
init_delayDecider();
init_omitRetryHeadersMiddleware();
init_retryDecider();
init_retryMiddleware();
}
});
// ../../node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.716.0/node_modules/@aws-sdk/signature-v4-multi-region/dist-es/signature-v4-crt-container.js
var signatureV4CrtContainer;
var init_signature_v4_crt_container = __esm({
"../../node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.716.0/node_modules/@aws-sdk/signature-v4-multi-region/dist-es/signature-v4-crt-container.js"() {
init_import_meta_url();
signatureV4CrtContainer = {
CrtSignerV4: null
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.716.0/node_modules/@aws-sdk/signature-v4-multi-region/dist-es/SignatureV4MultiRegion.js
var SignatureV4MultiRegion;
var init_SignatureV4MultiRegion = __esm({
"../../node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.716.0/node_modules/@aws-sdk/signature-v4-multi-region/dist-es/SignatureV4MultiRegion.js"() {
init_import_meta_url();
init_dist_es31();
init_signature_v4_crt_container();
SignatureV4MultiRegion = class {
static {
__name(this, "SignatureV4MultiRegion");
}
constructor(options) {
this.sigv4Signer = new SignatureV4S3Express(options);
this.signerOptions = options;
}
async sign(requestToSign, options = {}) {
if (options.signingRegion === "*") {
if (this.signerOptions.runtime !== "node")
throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");
return this.getSigv4aSigner().sign(requestToSign, options);
}
return this.sigv4Signer.sign(requestToSign, options);
}
async signWithCredentials(requestToSign, credentials, options = {}) {
if (options.signingRegion === "*") {
if (this.signerOptions.runtime !== "node")
throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");
return this.getSigv4aSigner().signWithCredentials(requestToSign, credentials, options);
}
return this.sigv4Signer.signWithCredentials(requestToSign, credentials, options);
}
async presign(originalRequest, options = {}) {
if (options.signingRegion === "*") {
if (this.signerOptions.runtime !== "node")
throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");
return this.getSigv4aSigner().presign(originalRequest, options);
}
return this.sigv4Signer.presign(originalRequest, options);
}
async presignWithCredentials(originalRequest, credentials, options = {}) {
if (options.signingRegion === "*") {
throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");
}
return this.sigv4Signer.presignWithCredentials(originalRequest, credentials, options);
}
getSigv4aSigner() {
if (!this.sigv4aSigner) {
let CrtSignerV4 = null;
try {
CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4;
if (typeof CrtSignerV4 !== "function")
throw new Error();
} catch (e7) {
e7.message = `${e7.message}
Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly.
You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";].
For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`;
throw e7;
}
this.sigv4aSigner = new CrtSignerV4({
...this.signerOptions,
signingAlgorithm: 1
});
}
return this.sigv4aSigner;
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.716.0/node_modules/@aws-sdk/signature-v4-multi-region/dist-es/index.js
var init_dist_es46 = __esm({
"../../node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.716.0/node_modules/@aws-sdk/signature-v4-multi-region/dist-es/index.js"() {
init_import_meta_url();
init_SignatureV4MultiRegion();
init_signature_v4_crt_container();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/endpoint/ruleset.js
var ci, cj, ck, cl, cm, cn, co, cp2, cq, cr, cs, ct, cu, cv, cw, cx, a, b2, c2, d2, e2, f2, g2, h2, i, j2, k2, l2, m2, n, o, p2, q2, r2, s, t2, u, v2, w2, x2, y2, z3, A, B, C, D, E, F, G2, H2, I2, J2, K2, L2, M2, N2, O2, P2, Q2, R2, S2, T2, U2, V2, W2, X2, Y2, Z2, aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az, aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM, aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ, ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm, bn, bo, bp, bq, br, bs, bt, bu, bv, bw, bx, by, bz, bA, bB, bC, bD, bE, bF, bG, bH, bI, bJ, bK, bL, bM, bN, bO, bP, bQ, bR, bS, bT, bU, bV, bW, bX, bY, bZ, ca, cb, cc, cd, ce, cf, cg, ch, _data, ruleSet;
var init_ruleset = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/endpoint/ruleset.js"() {
init_import_meta_url();
ci = "required";
cj = "type";
ck = "conditions";
cl = "fn";
cm = "argv";
cn = "ref";
co = "assign";
cp2 = "url";
cq = "properties";
cr = "backend";
cs = "authSchemes";
ct = "disableDoubleEncoding";
cu = "signingName";
cv = "signingRegion";
cw = "headers";
cx = "signingRegionSet";
a = 6;
b2 = false;
c2 = true;
d2 = "isSet";
e2 = "booleanEquals";
f2 = "error";
g2 = "aws.partition";
h2 = "stringEquals";
i = "getAttr";
j2 = "name";
k2 = "substring";
l2 = "bucketSuffix";
m2 = "parseURL";
n = "{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}";
o = "endpoint";
p2 = "tree";
q2 = "aws.isVirtualHostableS3Bucket";
r2 = "{url#scheme}://{Bucket}.{url#authority}{url#path}";
s = "not";
t2 = "{url#scheme}://{url#authority}{url#path}";
u = "hardwareType";
v2 = "regionPrefix";
w2 = "bucketAliasSuffix";
x2 = "outpostId";
y2 = "isValidHostLabel";
z3 = "sigv4a";
A = "s3-outposts";
B = "s3";
C = "{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}";
D = "https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}";
E = "https://{Bucket}.s3.{partitionResult#dnsSuffix}";
F = "aws.parseArn";
G2 = "bucketArn";
H2 = "arnType";
I2 = "";
J2 = "s3-object-lambda";
K2 = "accesspoint";
L2 = "accessPointName";
M2 = "{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}";
N2 = "mrapPartition";
O2 = "outpostType";
P2 = "arnPrefix";
Q2 = "{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}";
R2 = "https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}";
S2 = "https://s3.{partitionResult#dnsSuffix}";
T2 = { [ci]: false, [cj]: "String" };
U2 = { [ci]: true, "default": false, [cj]: "Boolean" };
V2 = { [ci]: false, [cj]: "Boolean" };
W2 = { [cl]: e2, [cm]: [{ [cn]: "Accelerate" }, true] };
X2 = { [cl]: e2, [cm]: [{ [cn]: "UseFIPS" }, true] };
Y2 = { [cl]: e2, [cm]: [{ [cn]: "UseDualStack" }, true] };
Z2 = { [cl]: d2, [cm]: [{ [cn]: "Endpoint" }] };
aa = { [cl]: g2, [cm]: [{ [cn]: "Region" }], [co]: "partitionResult" };
ab = { [cl]: h2, [cm]: [{ [cl]: i, [cm]: [{ [cn]: "partitionResult" }, j2] }, "aws-cn"] };
ac = { [cl]: d2, [cm]: [{ [cn]: "Bucket" }] };
ad = { [cn]: "Bucket" };
ae = { [cl]: m2, [cm]: [{ [cn]: "Endpoint" }], [co]: "url" };
af = { [cl]: e2, [cm]: [{ [cl]: i, [cm]: [{ [cn]: "url" }, "isIp"] }, true] };
ag = { [cn]: "url" };
ah = { [cl]: "uriEncode", [cm]: [ad], [co]: "uri_encoded_bucket" };
ai = { [cr]: "S3Express", [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: "s3express", [cv]: "{Region}" }] };
aj = {};
ak = { [cl]: q2, [cm]: [ad, false] };
al = { [f2]: "S3Express bucket name is not a valid virtual hostable name.", [cj]: f2 };
am = { [cr]: "S3Express", [cs]: [{ [ct]: true, [j2]: "sigv4-s3express", [cu]: "s3express", [cv]: "{Region}" }] };
an = { [cl]: d2, [cm]: [{ [cn]: "UseS3ExpressControlEndpoint" }] };
ao = { [cl]: e2, [cm]: [{ [cn]: "UseS3ExpressControlEndpoint" }, true] };
ap = { [cl]: s, [cm]: [Z2] };
aq = { [f2]: "Unrecognized S3Express bucket name format.", [cj]: f2 };
ar = { [cl]: s, [cm]: [ac] };
as = { [cn]: u };
at = { [ck]: [ap], [f2]: "Expected a endpoint to be specified but no endpoint was found", [cj]: f2 };
au = { [cs]: [{ [ct]: true, [j2]: z3, [cu]: A, [cx]: ["*"] }, { [ct]: true, [j2]: "sigv4", [cu]: A, [cv]: "{Region}" }] };
av = { [cl]: e2, [cm]: [{ [cn]: "ForcePathStyle" }, false] };
aw = { [cn]: "ForcePathStyle" };
ax = { [cl]: e2, [cm]: [{ [cn]: "Accelerate" }, false] };
ay = { [cl]: h2, [cm]: [{ [cn]: "Region" }, "aws-global"] };
az = { [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: B, [cv]: "us-east-1" }] };
aA = { [cl]: s, [cm]: [ay] };
aB = { [cl]: e2, [cm]: [{ [cn]: "UseGlobalEndpoint" }, true] };
aC = { [cp2]: "https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cq]: { [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: B, [cv]: "{Region}" }] }, [cw]: {} };
aD = { [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: B, [cv]: "{Region}" }] };
aE = { [cl]: e2, [cm]: [{ [cn]: "UseGlobalEndpoint" }, false] };
aF = { [cl]: e2, [cm]: [{ [cn]: "UseDualStack" }, false] };
aG = { [cp2]: "https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
aH = { [cl]: e2, [cm]: [{ [cn]: "UseFIPS" }, false] };
aI = { [cp2]: "https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
aJ = { [cp2]: "https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
aK = { [cl]: e2, [cm]: [{ [cl]: i, [cm]: [ag, "isIp"] }, false] };
aL = { [cp2]: C, [cq]: aD, [cw]: {} };
aM = { [cp2]: r2, [cq]: aD, [cw]: {} };
aN = { [o]: aM, [cj]: o };
aO = { [cp2]: D, [cq]: aD, [cw]: {} };
aP = { [cp2]: "https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
aQ = { [f2]: "Invalid region: region was not a valid DNS name.", [cj]: f2 };
aR = { [cn]: G2 };
aS = { [cn]: H2 };
aT = { [cl]: i, [cm]: [aR, "service"] };
aU = { [cn]: L2 };
aV = { [ck]: [Y2], [f2]: "S3 Object Lambda does not support Dual-stack", [cj]: f2 };
aW = { [ck]: [W2], [f2]: "S3 Object Lambda does not support S3 Accelerate", [cj]: f2 };
aX = { [ck]: [{ [cl]: d2, [cm]: [{ [cn]: "DisableAccessPoints" }] }, { [cl]: e2, [cm]: [{ [cn]: "DisableAccessPoints" }, true] }], [f2]: "Access points are not supported for this operation", [cj]: f2 };
aY = { [ck]: [{ [cl]: d2, [cm]: [{ [cn]: "UseArnRegion" }] }, { [cl]: e2, [cm]: [{ [cn]: "UseArnRegion" }, false] }, { [cl]: s, [cm]: [{ [cl]: h2, [cm]: [{ [cl]: i, [cm]: [aR, "region"] }, "{Region}"] }] }], [f2]: "Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`", [cj]: f2 };
aZ = { [cl]: i, [cm]: [{ [cn]: "bucketPartition" }, j2] };
ba = { [cl]: i, [cm]: [aR, "accountId"] };
bb = { [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: J2, [cv]: "{bucketArn#region}" }] };
bc = { [f2]: "Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`", [cj]: f2 };
bd = { [f2]: "Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`", [cj]: f2 };
be = { [f2]: "Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)", [cj]: f2 };
bf = { [f2]: "Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`", [cj]: f2 };
bg = { [f2]: "Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.", [cj]: f2 };
bh = { [f2]: "Invalid ARN: Expected a resource of the format `accesspoint:<accesspoint name>` but no name was provided", [cj]: f2 };
bi = { [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: B, [cv]: "{bucketArn#region}" }] };
bj = { [cs]: [{ [ct]: true, [j2]: z3, [cu]: A, [cx]: ["*"] }, { [ct]: true, [j2]: "sigv4", [cu]: A, [cv]: "{bucketArn#region}" }] };
bk = { [cl]: F, [cm]: [ad] };
bl = { [cp2]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: aD, [cw]: {} };
bm = { [cp2]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: aD, [cw]: {} };
bn = { [cp2]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: aD, [cw]: {} };
bo = { [cp2]: Q2, [cq]: aD, [cw]: {} };
bp = { [cp2]: "https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: aD, [cw]: {} };
bq = { [cn]: "UseObjectLambdaEndpoint" };
br = { [cs]: [{ [ct]: true, [j2]: "sigv4", [cu]: J2, [cv]: "{Region}" }] };
bs = { [cp2]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
bt = { [cp2]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
bu = { [cp2]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
bv = { [cp2]: t2, [cq]: aD, [cw]: {} };
bw = { [cp2]: "https://s3.{Region}.{partitionResult#dnsSuffix}", [cq]: aD, [cw]: {} };
bx = [{ [cn]: "Region" }];
by = [{ [cn]: "Endpoint" }];
bz = [ad];
bA = [Y2];
bB = [W2];
bC = [Z2, ae];
bD = [{ [cl]: d2, [cm]: [{ [cn]: "DisableS3ExpressSessionAuth" }] }, { [cl]: e2, [cm]: [{ [cn]: "DisableS3ExpressSessionAuth" }, true] }];
bE = [af];
bF = [ah];
bG = [ak];
bH = [X2];
bI = [{ [cl]: k2, [cm]: [ad, 6, 14, true], [co]: "s3expressAvailabilityZoneId" }, { [cl]: k2, [cm]: [ad, 14, 16, true], [co]: "s3expressAvailabilityZoneDelim" }, { [cl]: h2, [cm]: [{ [cn]: "s3expressAvailabilityZoneDelim" }, "--"] }];
bJ = [{ [ck]: [X2], [o]: { [cp2]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com", [cq]: ai, [cw]: {} }, [cj]: o }, { [o]: { [cp2]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com", [cq]: ai, [cw]: {} }, [cj]: o }];
bK = [{ [cl]: k2, [cm]: [ad, 6, 15, true], [co]: "s3expressAvailabilityZoneId" }, { [cl]: k2, [cm]: [ad, 15, 17, true], [co]: "s3expressAvailabilityZoneDelim" }, { [cl]: h2, [cm]: [{ [cn]: "s3expressAvailabilityZoneDelim" }, "--"] }];
bL = [{ [cl]: k2, [cm]: [ad, 6, 19, true], [co]: "s3expressAvailabilityZoneId" }, { [cl]: k2, [cm]: [ad, 19, 21, true], [co]: "s3expressAvailabilityZoneDelim" }, { [cl]: h2, [cm]: [{ [cn]: "s3expressAvailabilityZoneDelim" }, "--"] }];
bM = [{ [cl]: k2, [cm]: [ad, 6, 20, true], [co]: "s3expressAvailabilityZoneId" }, { [cl]: k2, [cm]: [ad, 20, 22, true], [co]: "s3expressAvailabilityZoneDelim" }, { [cl]: h2, [cm]: [{ [cn]: "s3expressAvailabilityZoneDelim" }, "--"] }];
bN = [{ [cl]: k2, [cm]: [ad, 6, 26, true], [co]: "s3expressAvailabilityZoneId" }, { [cl]: k2, [cm]: [ad, 26, 28, true], [co]: "s3expressAvailabilityZoneDelim" }, { [cl]: h2, [cm]: [{ [cn]: "s3expressAvailabilityZoneDelim" }, "--"] }];
bO = [{ [ck]: [X2], [o]: { [cp2]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com", [cq]: am, [cw]: {} }, [cj]: o }, { [o]: { [cp2]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com", [cq]: am, [cw]: {} }, [cj]: o }];
bP = [ac];
bQ = [{ [cl]: y2, [cm]: [{ [cn]: x2 }, false] }];
bR = [{ [cl]: h2, [cm]: [{ [cn]: v2 }, "beta"] }];
bS = ["*"];
bT = [aa];
bU = [{ [cl]: y2, [cm]: [{ [cn]: "Region" }, false] }];
bV = [{ [cl]: h2, [cm]: [{ [cn]: "Region" }, "us-east-1"] }];
bW = [{ [cl]: h2, [cm]: [aS, K2] }];
bX = [{ [cl]: i, [cm]: [aR, "resourceId[1]"], [co]: L2 }, { [cl]: s, [cm]: [{ [cl]: h2, [cm]: [aU, I2] }] }];
bY = [aR, "resourceId[1]"];
bZ = [{ [cl]: s, [cm]: [{ [cl]: h2, [cm]: [{ [cl]: i, [cm]: [aR, "region"] }, I2] }] }];
ca = [{ [cl]: s, [cm]: [{ [cl]: d2, [cm]: [{ [cl]: i, [cm]: [aR, "resourceId[2]"] }] }] }];
cb = [aR, "resourceId[2]"];
cc = [{ [cl]: g2, [cm]: [{ [cl]: i, [cm]: [aR, "region"] }], [co]: "bucketPartition" }];
cd = [{ [cl]: h2, [cm]: [aZ, { [cl]: i, [cm]: [{ [cn]: "partitionResult" }, j2] }] }];
ce = [{ [cl]: y2, [cm]: [{ [cl]: i, [cm]: [aR, "region"] }, true] }];
cf = [{ [cl]: y2, [cm]: [ba, false] }];
cg = [{ [cl]: y2, [cm]: [aU, false] }];
ch = [{ [cl]: y2, [cm]: [{ [cn]: "Region" }, true] }];
_data = { version: "1.0", parameters: { Bucket: T2, Region: T2, UseFIPS: U2, UseDualStack: U2, Endpoint: T2, ForcePathStyle: U2, Accelerate: U2, UseGlobalEndpoint: U2, UseObjectLambdaEndpoint: V2, Key: T2, Prefix: T2, CopySource: T2, DisableAccessPoints: V2, DisableMultiRegionAccessPoints: U2, UseArnRegion: V2, UseS3ExpressControlEndpoint: V2, DisableS3ExpressSessionAuth: V2 }, rules: [{ [ck]: [{ [cl]: d2, [cm]: bx }], rules: [{ [ck]: [W2, X2], error: "Accelerate cannot be used with FIPS", [cj]: f2 }, { [ck]: [Y2, Z2], error: "Cannot set dual-stack in combination with a custom endpoint.", [cj]: f2 }, { [ck]: [Z2, X2], error: "A custom endpoint cannot be combined with FIPS", [cj]: f2 }, { [ck]: [Z2, W2], error: "A custom endpoint cannot be combined with S3 Accelerate", [cj]: f2 }, { [ck]: [X2, aa, ab], error: "Partition does not support FIPS", [cj]: f2 }, { [ck]: [ac, { [cl]: k2, [cm]: [ad, 0, a, c2], [co]: l2 }, { [cl]: h2, [cm]: [{ [cn]: l2 }, "--x-s3"] }], rules: [{ [ck]: bA, error: "S3Express does not support Dual-stack.", [cj]: f2 }, { [ck]: bB, error: "S3Express does not support S3 Accelerate.", [cj]: f2 }, { [ck]: bC, rules: [{ [ck]: bD, rules: [{ [ck]: bE, rules: [{ [ck]: bF, rules: [{ endpoint: { [cp2]: n, [cq]: ai, [cw]: aj }, [cj]: o }], [cj]: p2 }], [cj]: p2 }, { [ck]: bG, rules: [{ endpoint: { [cp2]: r2, [cq]: ai, [cw]: aj }, [cj]: o }], [cj]: p2 }, al], [cj]: p2 }, { [ck]: bE, rules: [{ [ck]: bF, rules: [{ endpoint: { [cp2]: n, [cq]: am, [cw]: aj }, [cj]: o }], [cj]: p2 }], [cj]: p2 }, { [ck]: bG, rules: [{ endpoint: { [cp2]: r2, [cq]: am, [cw]: aj }, [cj]: o }], [cj]: p2 }, al], [cj]: p2 }, { [ck]: [an, ao], rules: [{ [ck]: [ah, ap], rules: [{ [ck]: bH, endpoint: { [cp2]: "https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}", [cq]: ai, [cw]: aj }, [cj]: o }, { endpoint: { [cp2]: "https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}", [cq]: ai, [cw]: aj }, [cj]: o }], [cj]: p2 }], [cj]: p2 }, { [ck]: bG, rules: [{ [ck]: bD, rules: [{ [ck]: bI, rules: bJ, [cj]: p2 }, { [ck]: bK, rules: bJ, [cj]: p2 }, { [ck]: bL, rules: bJ, [cj]: p2 }, { [ck]: bM, rules: bJ, [cj]: p2 }, { [ck]: bN, rules: bJ, [cj]: p2 }, aq], [cj]: p2 }, { [ck]: bI, rules: bO, [cj]: p2 }, { [ck]: bK, rules: bO, [cj]: p2 }, { [ck]: bL, rules: bO, [cj]: p2 }, { [ck]: bM, rules: bO, [cj]: p2 }, { [ck]: bN, rules: bO, [cj]: p2 }, aq], [cj]: p2 }, al], [cj]: p2 }, { [ck]: [ar, an, ao], rules: [{ [ck]: bC, endpoint: { [cp2]: t2, [cq]: ai, [cw]: aj }, [cj]: o }, { [ck]: bH, endpoint: { [cp2]: "https://s3express-control-fips.{Region}.amazonaws.com", [cq]: ai, [cw]: aj }, [cj]: o }, { endpoint: { [cp2]: "https://s3express-control.{Region}.amazonaws.com", [cq]: ai, [cw]: aj }, [cj]: o }], [cj]: p2 }, { [ck]: [ac, { [cl]: k2, [cm]: [ad, 49, 50, c2], [co]: u }, { [cl]: k2, [cm]: [ad, 8, 12, c2], [co]: v2 }, { [cl]: k2, [cm]: [ad, 0, 7, c2], [co]: w2 }, { [cl]: k2, [cm]: [ad, 32, 49, c2], [co]: x2 }, { [cl]: g2, [cm]: bx, [co]: "regionPartition" }, { [cl]: h2, [cm]: [{ [cn]: w2 }, "--op-s3"] }], rules: [{ [ck]: bQ, rules: [{ [ck]: [{ [cl]: h2, [cm]: [as, "e"] }], rules: [{ [ck]: bR, rules: [at, { [ck]: bC, endpoint: { [cp2]: "https://{Bucket}.ec2.{url#authority}", [cq]: au, [cw]: aj }, [cj]: o }], [cj]: p2 }, { endpoint: { [cp2]: "https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}", [cq]: au, [cw]: aj }, [cj]: o }], [cj]: p2 }, { [ck]: [{ [cl]: h2, [cm]: [as, "o"] }], rules: [{ [ck]: bR, rules: [at, { [ck]: bC, endpoint: { [cp2]: "https://{Bucket}.op-{outpostId}.{url#authority}", [cq]: au, [cw]: aj }, [cj]: o }], [cj]: p2 }, { endpoint: { [cp2]: "https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}", [cq]: au, [cw]: aj }, [cj]: o }], [cj]: p2 }, { error: 'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"', [cj]: f2 }], [cj]: p2 }, { error: "Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.", [cj]: f2 }], [cj]: p2 }, { [ck]: bP, rules: [{ [ck]: [Z2, { [cl]: s, [cm]: [{ [cl]: d2, [cm]: [{ [cl]: m2, [cm]: by }] }] }], error: "Custom endpoint `{Endpoint}` was not a valid URI", [cj]: f2 }, { [ck]: [av, ak], rules: [{ [ck]: bT, rules: [{ [ck]: bU, rules: [{ [ck]: [W2, ab], error: "S3 Accelerate cannot be used in this region", [cj]: f2 }, { [ck]: [Y2, X2, ax, ap, ay], endpoint: { [cp2]: "https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [Y2, X2, ax, ap, aA, aB], rules: [{ endpoint: aC, [cj]: o }], [cj]: p2 }, { [ck]: [Y2, X2, ax, ap, aA, aE], endpoint: aC, [cj]: o }, { [ck]: [aF, X2, ax, ap, ay], endpoint: { [cp2]: "https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, X2, ax, ap, aA, aB], rules: [{ endpoint: aG, [cj]: o }], [cj]: p2 }, { [ck]: [aF, X2, ax, ap, aA, aE], endpoint: aG, [cj]: o }, { [ck]: [Y2, aH, W2, ap, ay], endpoint: { [cp2]: "https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [Y2, aH, W2, ap, aA, aB], rules: [{ endpoint: aI, [cj]: o }], [cj]: p2 }, { [ck]: [Y2, aH, W2, ap, aA, aE], endpoint: aI, [cj]: o }, { [ck]: [Y2, aH, ax, ap, ay], endpoint: { [cp2]: "https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [Y2, aH, ax, ap, aA, aB], rules: [{ endpoint: aJ, [cj]: o }], [cj]: p2 }, { [ck]: [Y2, aH, ax, ap, aA, aE], endpoint: aJ, [cj]: o }, { [ck]: [aF, aH, ax, Z2, ae, af, ay], endpoint: { [cp2]: C, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, aH, ax, Z2, ae, aK, ay], endpoint: { [cp2]: r2, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, aH, ax, Z2, ae, af, aA, aB], rules: [{ [ck]: bV, endpoint: aL, [cj]: o }, { endpoint: aL, [cj]: o }], [cj]: p2 }, { [ck]: [aF, aH, ax, Z2, ae, aK, aA, aB], rules: [{ [ck]: bV, endpoint: aM, [cj]: o }, aN], [cj]: p2 }, { [ck]: [aF, aH, ax, Z2, ae, af, aA, aE], endpoint: aL, [cj]: o }, { [ck]: [aF, aH, ax, Z2, ae, aK, aA, aE], endpoint: aM, [cj]: o }, { [ck]: [aF, aH, W2, ap, ay], endpoint: { [cp2]: D, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, aH, W2, ap, aA, aB], rules: [{ [ck]: bV, endpoint: aO, [cj]: o }, { endpoint: aO, [cj]: o }], [cj]: p2 }, { [ck]: [aF, aH, W2, ap, aA, aE], endpoint: aO, [cj]: o }, { [ck]: [aF, aH, ax, ap, ay], endpoint: { [cp2]: E, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, aH, ax, ap, aA, aB], rules: [{ [ck]: bV, endpoint: { [cp2]: E, [cq]: aD, [cw]: aj }, [cj]: o }, { endpoint: aP, [cj]: o }], [cj]: p2 }, { [ck]: [aF, aH, ax, ap, aA, aE], endpoint: aP, [cj]: o }], [cj]: p2 }, aQ], [cj]: p2 }], [cj]: p2 }, { [ck]: [Z2, ae, { [cl]: h2, [cm]: [{ [cl]: i, [cm]: [ag, "scheme"] }, "http"] }, { [cl]: q2, [cm]: [ad, c2] }, av, aH, aF, ax], rules: [{ [ck]: bT, rules: [{ [ck]: bU, rules: [aN], [cj]: p2 }, aQ], [cj]: p2 }], [cj]: p2 }, { [ck]: [av, { [cl]: F, [cm]: bz, [co]: G2 }], rules: [{ [ck]: [{ [cl]: i, [cm]: [aR, "resourceId[0]"], [co]: H2 }, { [cl]: s, [cm]: [{ [cl]: h2, [cm]: [aS, I2] }] }], rules: [{ [ck]: [{ [cl]: h2, [cm]: [aT, J2] }], rules: [{ [ck]: bW, rules: [{ [ck]: bX, rules: [aV, aW, { [ck]: bZ, rules: [aX, { [ck]: ca, rules: [aY, { [ck]: cc, rules: [{ [ck]: bT, rules: [{ [ck]: cd, rules: [{ [ck]: ce, rules: [{ [ck]: [{ [cl]: h2, [cm]: [ba, I2] }], error: "Invalid ARN: Missing account id", [cj]: f2 }, { [ck]: cf, rules: [{ [ck]: cg, rules: [{ [ck]: bC, endpoint: { [cp2]: M2, [cq]: bb, [cw]: aj }, [cj]: o }, { [ck]: bH, endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bb, [cw]: aj }, [cj]: o }, { endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bb, [cw]: aj }, [cj]: o }], [cj]: p2 }, bc], [cj]: p2 }, bd], [cj]: p2 }, be], [cj]: p2 }, bf], [cj]: p2 }], [cj]: p2 }], [cj]: p2 }, bg], [cj]: p2 }, { error: "Invalid ARN: bucket ARN is missing a region", [cj]: f2 }], [cj]: p2 }, bh], [cj]: p2 }, { error: "Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`", [cj]: f2 }], [cj]: p2 }, { [ck]: bW, rules: [{ [ck]: bX, rules: [{ [ck]: bZ, rules: [{ [ck]: bW, rules: [{ [ck]: bZ, rules: [aX, { [ck]: ca, rules: [aY, { [ck]: cc, rules: [{ [ck]: bT, rules: [{ [ck]: [{ [cl]: h2, [cm]: [aZ, "{partitionResult#name}"] }], rules: [{ [ck]: ce, rules: [{ [ck]: [{ [cl]: h2, [cm]: [aT, B] }], rules: [{ [ck]: cf, rules: [{ [ck]: cg, rules: [{ [ck]: bB, error: "Access Points do not support S3 Accelerate", [cj]: f2 }, { [ck]: [X2, Y2], endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bi, [cw]: aj }, [cj]: o }, { [ck]: [X2, aF], endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bi, [cw]: aj }, [cj]: o }, { [ck]: [aH, Y2], endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bi, [cw]: aj }, [cj]: o }, { [ck]: [aH, aF, Z2, ae], endpoint: { [cp2]: M2, [cq]: bi, [cw]: aj }, [cj]: o }, { [ck]: [aH, aF], endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bi, [cw]: aj }, [cj]: o }], [cj]: p2 }, bc], [cj]: p2 }, bd], [cj]: p2 }, { error: "Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}", [cj]: f2 }], [cj]: p2 }, be], [cj]: p2 }, bf], [cj]: p2 }], [cj]: p2 }], [cj]: p2 }, bg], [cj]: p2 }], [cj]: p2 }], [cj]: p2 }, { [ck]: [{ [cl]: y2, [cm]: [aU, c2] }], rules: [{ [ck]: bA, error: "S3 MRAP does not support dual-stack", [cj]: f2 }, { [ck]: bH, error: "S3 MRAP does not support FIPS", [cj]: f2 }, { [ck]: bB, error: "S3 MRAP does not support S3 Accelerate", [cj]: f2 }, { [ck]: [{ [cl]: e2, [cm]: [{ [cn]: "DisableMultiRegionAccessPoints" }, c2] }], error: "Invalid configuration: Multi-Region Access Point ARNs are disabled.", [cj]: f2 }, { [ck]: [{ [cl]: g2, [cm]: bx, [co]: N2 }], rules: [{ [ck]: [{ [cl]: h2, [cm]: [{ [cl]: i, [cm]: [{ [cn]: N2 }, j2] }, { [cl]: i, [cm]: [aR, "partition"] }] }], rules: [{ endpoint: { [cp2]: "https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}", [cq]: { [cs]: [{ [ct]: c2, name: z3, [cu]: B, [cx]: bS }] }, [cw]: aj }, [cj]: o }], [cj]: p2 }, { error: "Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`", [cj]: f2 }], [cj]: p2 }], [cj]: p2 }, { error: "Invalid Access Point Name", [cj]: f2 }], [cj]: p2 }, bh], [cj]: p2 }, { [ck]: [{ [cl]: h2, [cm]: [aT, A] }], rules: [{ [ck]: bA, error: "S3 Outposts does not support Dual-stack", [cj]: f2 }, { [ck]: bH, error: "S3 Outposts does not support FIPS", [cj]: f2 }, { [ck]: bB, error: "S3 Outposts does not support S3 Accelerate", [cj]: f2 }, { [ck]: [{ [cl]: d2, [cm]: [{ [cl]: i, [cm]: [aR, "resourceId[4]"] }] }], error: "Invalid Arn: Outpost Access Point ARN contains sub resources", [cj]: f2 }, { [ck]: [{ [cl]: i, [cm]: bY, [co]: x2 }], rules: [{ [ck]: bQ, rules: [aY, { [ck]: cc, rules: [{ [ck]: bT, rules: [{ [ck]: cd, rules: [{ [ck]: ce, rules: [{ [ck]: cf, rules: [{ [ck]: [{ [cl]: i, [cm]: cb, [co]: O2 }], rules: [{ [ck]: [{ [cl]: i, [cm]: [aR, "resourceId[3]"], [co]: L2 }], rules: [{ [ck]: [{ [cl]: h2, [cm]: [{ [cn]: O2 }, K2] }], rules: [{ [ck]: bC, endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}", [cq]: bj, [cw]: aj }, [cj]: o }, { endpoint: { [cp2]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cq]: bj, [cw]: aj }, [cj]: o }], [cj]: p2 }, { error: "Expected an outpost type `accesspoint`, found {outpostType}", [cj]: f2 }], [cj]: p2 }, { error: "Invalid ARN: expected an access point name", [cj]: f2 }], [cj]: p2 }, { error: "Invalid ARN: Expected a 4-component resource", [cj]: f2 }], [cj]: p2 }, bd], [cj]: p2 }, be], [cj]: p2 }, bf], [cj]: p2 }], [cj]: p2 }], [cj]: p2 }, { error: "Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`", [cj]: f2 }], [cj]: p2 }, { error: "Invalid ARN: The Outpost Id was not set", [cj]: f2 }], [cj]: p2 }, { error: "Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})", [cj]: f2 }], [cj]: p2 }, { error: "Invalid ARN: No ARN type specified", [cj]: f2 }], [cj]: p2 }, { [ck]: [{ [cl]: k2, [cm]: [ad, 0, 4, b2], [co]: P2 }, { [cl]: h2, [cm]: [{ [cn]: P2 }, "arn:"] }, { [cl]: s, [cm]: [{ [cl]: d2, [cm]: [bk] }] }], error: "Invalid ARN: `{Bucket}` was not a valid ARN", [cj]: f2 }, { [ck]: [{ [cl]: e2, [cm]: [aw, c2] }, bk], error: "Path-style addressing cannot be used with ARN buckets", [cj]: f2 }, { [ck]: bF, rules: [{ [ck]: bT, rules: [{ [ck]: [ax], rules: [{ [ck]: [Y2, ap, X2, ay], endpoint: { [cp2]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [Y2, ap, X2, aA, aB], rules: [{ endpoint: bl, [cj]: o }], [cj]: p2 }, { [ck]: [Y2, ap, X2, aA, aE], endpoint: bl, [cj]: o }, { [ck]: [aF, ap, X2, ay], endpoint: { [cp2]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, ap, X2, aA, aB], rules: [{ endpoint: bm, [cj]: o }], [cj]: p2 }, { [ck]: [aF, ap, X2, aA, aE], endpoint: bm, [cj]: o }, { [ck]: [Y2, ap, aH, ay], endpoint: { [cp2]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [Y2, ap, aH, aA, aB], rules: [{ endpoint: bn, [cj]: o }], [cj]: p2 }, { [ck]: [Y2, ap, aH, aA, aE], endpoint: bn, [cj]: o }, { [ck]: [aF, Z2, ae, aH, ay], endpoint: { [cp2]: Q2, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, Z2, ae, aH, aA, aB], rules: [{ [ck]: bV, endpoint: bo, [cj]: o }, { endpoint: bo, [cj]: o }], [cj]: p2 }, { [ck]: [aF, Z2, ae, aH, aA, aE], endpoint: bo, [cj]: o }, { [ck]: [aF, ap, aH, ay], endpoint: { [cp2]: R2, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aF, ap, aH, aA, aB], rules: [{ [ck]: bV, endpoint: { [cp2]: R2, [cq]: aD, [cw]: aj }, [cj]: o }, { endpoint: bp, [cj]: o }], [cj]: p2 }, { [ck]: [aF, ap, aH, aA, aE], endpoint: bp, [cj]: o }], [cj]: p2 }, { error: "Path-style addressing cannot be used with S3 Accelerate", [cj]: f2 }], [cj]: p2 }], [cj]: p2 }], [cj]: p2 }, { [ck]: [{ [cl]: d2, [cm]: [bq] }, { [cl]: e2, [cm]: [bq, c2] }], rules: [{ [ck]: bT, rules: [{ [ck]: ch, rules: [aV, aW, { [ck]: bC, endpoint: { [cp2]: t2, [cq]: br, [cw]: aj }, [cj]: o }, { [ck]: bH, endpoint: { [cp2]: "https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}", [cq]: br, [cw]: aj }, [cj]: o }, { endpoint: { [cp2]: "https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}", [cq]: br, [cw]: aj }, [cj]: o }], [cj]: p2 }, aQ], [cj]: p2 }], [cj]: p2 }, { [ck]: [ar], rules: [{ [ck]: bT, rules: [{ [ck]: ch, rules: [{ [ck]: [X2, Y2, ap, ay], endpoint: { [cp2]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [X2, Y2, ap, aA, aB], rules: [{ endpoint: bs, [cj]: o }], [cj]: p2 }, { [ck]: [X2, Y2, ap, aA, aE], endpoint: bs, [cj]: o }, { [ck]: [X2, aF, ap, ay], endpoint: { [cp2]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [X2, aF, ap, aA, aB], rules: [{ endpoint: bt, [cj]: o }], [cj]: p2 }, { [ck]: [X2, aF, ap, aA, aE], endpoint: bt, [cj]: o }, { [ck]: [aH, Y2, ap, ay], endpoint: { [cp2]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aH, Y2, ap, aA, aB], rules: [{ endpoint: bu, [cj]: o }], [cj]: p2 }, { [ck]: [aH, Y2, ap, aA, aE], endpoint: bu, [cj]: o }, { [ck]: [aH, aF, Z2, ae, ay], endpoint: { [cp2]: t2, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aH, aF, Z2, ae, aA, aB], rules: [{ [ck]: bV, endpoint: bv, [cj]: o }, { endpoint: bv, [cj]: o }], [cj]: p2 }, { [ck]: [aH, aF, Z2, ae, aA, aE], endpoint: bv, [cj]: o }, { [ck]: [aH, aF, ap, ay], endpoint: { [cp2]: S2, [cq]: az, [cw]: aj }, [cj]: o }, { [ck]: [aH, aF, ap, aA, aB], rules: [{ [ck]: bV, endpoint: { [cp2]: S2, [cq]: aD, [cw]: aj }, [cj]: o }, { endpoint: bw, [cj]: o }], [cj]: p2 }, { [ck]: [aH, aF, ap, aA, aE], endpoint: bw, [cj]: o }], [cj]: p2 }, aQ], [cj]: p2 }], [cj]: p2 }], [cj]: p2 }, { error: "A region must be set when sending requests to S3.", [cj]: f2 }] };
ruleSet = _data;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/endpoint/endpointResolver.js
var cache2, defaultEndpointResolver;
var init_endpointResolver = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/endpoint/endpointResolver.js"() {
init_import_meta_url();
init_dist_es33();
init_dist_es32();
init_ruleset();
cache2 = new EndpointCache({
size: 50,
params: [
"Accelerate",
"Bucket",
"DisableAccessPoints",
"DisableMultiRegionAccessPoints",
"DisableS3ExpressSessionAuth",
"Endpoint",
"ForcePathStyle",
"Region",
"UseArnRegion",
"UseDualStack",
"UseFIPS",
"UseGlobalEndpoint",
"UseObjectLambdaEndpoint",
"UseS3ExpressControlEndpoint"
]
});
defaultEndpointResolver = /* @__PURE__ */ __name((endpointParams, context2 = {}) => {
return cache2.get(endpointParams, () => resolveEndpoint(ruleSet, {
endpointParams,
logger: context2.logger
}));
}, "defaultEndpointResolver");
customEndpointFunctions.aws = awsEndpointFunctions;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption(authParameters) {
return {
schemeId: "aws.auth#sigv4",
signingProperties: {
name: "s3",
region: authParameters.region
},
propertiesExtractor: /* @__PURE__ */ __name((config, context2) => ({
signingProperties: {
config,
context: context2
}
}), "propertiesExtractor")
};
}
function createAwsAuthSigv4aHttpAuthOption(authParameters) {
return {
schemeId: "aws.auth#sigv4a",
signingProperties: {
name: "s3",
region: authParameters.region
},
propertiesExtractor: /* @__PURE__ */ __name((config, context2) => ({
signingProperties: {
config,
context: context2
}
}), "propertiesExtractor")
};
}
var createEndpointRuleSetHttpAuthSchemeParametersProvider, _defaultS3HttpAuthSchemeParametersProvider, defaultS3HttpAuthSchemeParametersProvider, createEndpointRuleSetHttpAuthSchemeProvider, _defaultS3HttpAuthSchemeProvider, defaultS3HttpAuthSchemeProvider, resolveHttpAuthSchemeConfig;
var init_httpAuthSchemeProvider = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthSchemeProvider.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es46();
init_dist_es42();
init_dist_es4();
init_endpointResolver();
createEndpointRuleSetHttpAuthSchemeParametersProvider = /* @__PURE__ */ __name((defaultHttpAuthSchemeParametersProvider) => async (config, context2, input) => {
if (!input) {
throw new Error(`Could not find \`input\` for \`defaultEndpointRuleSetHttpAuthSchemeParametersProvider\``);
}
const defaultParameters = await defaultHttpAuthSchemeParametersProvider(config, context2, input);
const instructionsFn = getSmithyContext(context2)?.commandInstance?.constructor?.getEndpointParameterInstructions;
if (!instructionsFn) {
throw new Error(`getEndpointParameterInstructions() is not defined on \`${context2.commandName}\``);
}
const endpointParameters = await resolveParams(input, { getEndpointParameterInstructions: instructionsFn }, config);
return Object.assign(defaultParameters, endpointParameters);
}, "createEndpointRuleSetHttpAuthSchemeParametersProvider");
_defaultS3HttpAuthSchemeParametersProvider = /* @__PURE__ */ __name(async (config, context2, input) => {
return {
operation: getSmithyContext(context2).operation,
region: await normalizeProvider(config.region)() || (() => {
throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
})()
};
}, "_defaultS3HttpAuthSchemeParametersProvider");
defaultS3HttpAuthSchemeParametersProvider = createEndpointRuleSetHttpAuthSchemeParametersProvider(_defaultS3HttpAuthSchemeParametersProvider);
__name(createAwsAuthSigv4HttpAuthOption, "createAwsAuthSigv4HttpAuthOption");
__name(createAwsAuthSigv4aHttpAuthOption, "createAwsAuthSigv4aHttpAuthOption");
createEndpointRuleSetHttpAuthSchemeProvider = /* @__PURE__ */ __name((defaultEndpointResolver5, defaultHttpAuthSchemeResolver, createHttpAuthOptionFunctions) => {
const endpointRuleSetHttpAuthSchemeProvider = /* @__PURE__ */ __name((authParameters) => {
const endpoint = defaultEndpointResolver5(authParameters);
const authSchemes = endpoint.properties?.authSchemes;
if (!authSchemes) {
return defaultHttpAuthSchemeResolver(authParameters);
}
const options = [];
for (const scheme of authSchemes) {
const { name: resolvedName, properties = {}, ...rest } = scheme;
const name2 = resolvedName.toLowerCase();
if (resolvedName !== name2) {
console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${resolvedName}\` to \`${name2}\``);
}
let schemeId;
if (name2 === "sigv4a") {
schemeId = "aws.auth#sigv4a";
const sigv4Present = authSchemes.find((s5) => {
const name3 = s5.name.toLowerCase();
return name3 !== "sigv4a" && name3.startsWith("sigv4");
});
if (!signatureV4CrtContainer.CrtSignerV4 && sigv4Present) {
continue;
}
} else if (name2.startsWith("sigv4")) {
schemeId = "aws.auth#sigv4";
} else {
throw new Error(`Unknown HttpAuthScheme found in \`@smithy.rules#endpointRuleSet\`: \`${name2}\``);
}
const createOption = createHttpAuthOptionFunctions[schemeId];
if (!createOption) {
throw new Error(`Could not find HttpAuthOption create function for \`${schemeId}\``);
}
const option = createOption(authParameters);
option.schemeId = schemeId;
option.signingProperties = { ...option.signingProperties || {}, ...rest, ...properties };
options.push(option);
}
return options;
}, "endpointRuleSetHttpAuthSchemeProvider");
return endpointRuleSetHttpAuthSchemeProvider;
}, "createEndpointRuleSetHttpAuthSchemeProvider");
_defaultS3HttpAuthSchemeProvider = /* @__PURE__ */ __name((authParameters) => {
const options = [];
switch (authParameters.operation) {
default: {
options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
options.push(createAwsAuthSigv4aHttpAuthOption(authParameters));
}
}
return options;
}, "_defaultS3HttpAuthSchemeProvider");
defaultS3HttpAuthSchemeProvider = createEndpointRuleSetHttpAuthSchemeProvider(defaultEndpointResolver, _defaultS3HttpAuthSchemeProvider, {
"aws.auth#sigv4": createAwsAuthSigv4HttpAuthOption,
"aws.auth#sigv4a": createAwsAuthSigv4aHttpAuthOption
});
resolveHttpAuthSchemeConfig = /* @__PURE__ */ __name((config) => {
const config_0 = resolveAwsSdkSigV4Config(config);
const config_1 = resolveAwsSdkSigV4AConfig(config_0);
return {
...config_1
};
}, "resolveHttpAuthSchemeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters, commonParams;
var init_EndpointParameters = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/endpoint/EndpointParameters.js"() {
init_import_meta_url();
resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => {
return {
...options,
useFipsEndpoint: options.useFipsEndpoint ?? false,
useDualstackEndpoint: options.useDualstackEndpoint ?? false,
forcePathStyle: options.forcePathStyle ?? false,
useAccelerateEndpoint: options.useAccelerateEndpoint ?? false,
useGlobalEndpoint: options.useGlobalEndpoint ?? false,
disableMultiregionAccessPoints: options.disableMultiregionAccessPoints ?? false,
defaultSigningName: "s3"
};
}, "resolveClientEndpointParameters");
commonParams = {
ForcePathStyle: { type: "clientContextParams", name: "forcePathStyle" },
UseArnRegion: { type: "clientContextParams", name: "useArnRegion" },
DisableMultiRegionAccessPoints: { type: "clientContextParams", name: "disableMultiregionAccessPoints" },
Accelerate: { type: "clientContextParams", name: "useAccelerateEndpoint" },
DisableS3ExpressSessionAuth: { type: "clientContextParams", name: "disableS3ExpressSessionAuth" },
UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
Endpoint: { type: "builtInParams", name: "endpoint" },
Region: { type: "builtInParams", name: "region" },
UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/S3ServiceException.js
var S3ServiceException;
var init_S3ServiceException = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/S3ServiceException.js"() {
init_import_meta_url();
init_dist_es20();
S3ServiceException = class _S3ServiceException extends ServiceException {
static {
__name(this, "S3ServiceException");
}
constructor(options) {
super(options);
Object.setPrototypeOf(this, _S3ServiceException.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/models_0.js
var NoSuchUpload, ObjectNotInActiveTierError, BucketAlreadyExists, BucketAlreadyOwnedByYou, NoSuchBucket, AnalyticsFilter, MetricsFilter, InvalidObjectState, NoSuchKey, NotFound, CompleteMultipartUploadOutputFilterSensitiveLog, CompleteMultipartUploadRequestFilterSensitiveLog, CopyObjectOutputFilterSensitiveLog, CopyObjectRequestFilterSensitiveLog, CreateMultipartUploadOutputFilterSensitiveLog, CreateMultipartUploadRequestFilterSensitiveLog, SessionCredentialsFilterSensitiveLog, CreateSessionOutputFilterSensitiveLog, CreateSessionRequestFilterSensitiveLog, ServerSideEncryptionByDefaultFilterSensitiveLog, ServerSideEncryptionRuleFilterSensitiveLog, ServerSideEncryptionConfigurationFilterSensitiveLog, GetBucketEncryptionOutputFilterSensitiveLog, SSEKMSFilterSensitiveLog, InventoryEncryptionFilterSensitiveLog, InventoryS3BucketDestinationFilterSensitiveLog, InventoryDestinationFilterSensitiveLog, InventoryConfigurationFilterSensitiveLog, GetBucketInventoryConfigurationOutputFilterSensitiveLog, GetObjectOutputFilterSensitiveLog, GetObjectRequestFilterSensitiveLog, GetObjectAttributesRequestFilterSensitiveLog, GetObjectTorrentOutputFilterSensitiveLog, HeadObjectOutputFilterSensitiveLog, HeadObjectRequestFilterSensitiveLog, ListBucketInventoryConfigurationsOutputFilterSensitiveLog, ListPartsRequestFilterSensitiveLog;
var init_models_0 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/models_0.js"() {
init_import_meta_url();
init_dist_es20();
init_S3ServiceException();
NoSuchUpload = class _NoSuchUpload extends S3ServiceException {
static {
__name(this, "NoSuchUpload");
}
constructor(opts) {
super({
name: "NoSuchUpload",
$fault: "client",
...opts
});
this.name = "NoSuchUpload";
this.$fault = "client";
Object.setPrototypeOf(this, _NoSuchUpload.prototype);
}
};
ObjectNotInActiveTierError = class _ObjectNotInActiveTierError extends S3ServiceException {
static {
__name(this, "ObjectNotInActiveTierError");
}
constructor(opts) {
super({
name: "ObjectNotInActiveTierError",
$fault: "client",
...opts
});
this.name = "ObjectNotInActiveTierError";
this.$fault = "client";
Object.setPrototypeOf(this, _ObjectNotInActiveTierError.prototype);
}
};
BucketAlreadyExists = class _BucketAlreadyExists extends S3ServiceException {
static {
__name(this, "BucketAlreadyExists");
}
constructor(opts) {
super({
name: "BucketAlreadyExists",
$fault: "client",
...opts
});
this.name = "BucketAlreadyExists";
this.$fault = "client";
Object.setPrototypeOf(this, _BucketAlreadyExists.prototype);
}
};
BucketAlreadyOwnedByYou = class _BucketAlreadyOwnedByYou extends S3ServiceException {
static {
__name(this, "BucketAlreadyOwnedByYou");
}
constructor(opts) {
super({
name: "BucketAlreadyOwnedByYou",
$fault: "client",
...opts
});
this.name = "BucketAlreadyOwnedByYou";
this.$fault = "client";
Object.setPrototypeOf(this, _BucketAlreadyOwnedByYou.prototype);
}
};
NoSuchBucket = class _NoSuchBucket extends S3ServiceException {
static {
__name(this, "NoSuchBucket");
}
constructor(opts) {
super({
name: "NoSuchBucket",
$fault: "client",
...opts
});
this.name = "NoSuchBucket";
this.$fault = "client";
Object.setPrototypeOf(this, _NoSuchBucket.prototype);
}
};
(function(AnalyticsFilter2) {
AnalyticsFilter2.visit = (value, visitor) => {
if (value.Prefix !== void 0)
return visitor.Prefix(value.Prefix);
if (value.Tag !== void 0)
return visitor.Tag(value.Tag);
if (value.And !== void 0)
return visitor.And(value.And);
return visitor._(value.$unknown[0], value.$unknown[1]);
};
})(AnalyticsFilter || (AnalyticsFilter = {}));
(function(MetricsFilter2) {
MetricsFilter2.visit = (value, visitor) => {
if (value.Prefix !== void 0)
return visitor.Prefix(value.Prefix);
if (value.Tag !== void 0)
return visitor.Tag(value.Tag);
if (value.AccessPointArn !== void 0)
return visitor.AccessPointArn(value.AccessPointArn);
if (value.And !== void 0)
return visitor.And(value.And);
return visitor._(value.$unknown[0], value.$unknown[1]);
};
})(MetricsFilter || (MetricsFilter = {}));
InvalidObjectState = class _InvalidObjectState extends S3ServiceException {
static {
__name(this, "InvalidObjectState");
}
constructor(opts) {
super({
name: "InvalidObjectState",
$fault: "client",
...opts
});
this.name = "InvalidObjectState";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidObjectState.prototype);
this.StorageClass = opts.StorageClass;
this.AccessTier = opts.AccessTier;
}
};
NoSuchKey = class _NoSuchKey extends S3ServiceException {
static {
__name(this, "NoSuchKey");
}
constructor(opts) {
super({
name: "NoSuchKey",
$fault: "client",
...opts
});
this.name = "NoSuchKey";
this.$fault = "client";
Object.setPrototypeOf(this, _NoSuchKey.prototype);
}
};
NotFound = class _NotFound extends S3ServiceException {
static {
__name(this, "NotFound");
}
constructor(opts) {
super({
name: "NotFound",
$fault: "client",
...opts
});
this.name = "NotFound";
this.$fault = "client";
Object.setPrototypeOf(this, _NotFound.prototype);
}
};
CompleteMultipartUploadOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING }
}), "CompleteMultipartUploadOutputFilterSensitiveLog");
CompleteMultipartUploadRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "CompleteMultipartUploadRequestFilterSensitiveLog");
CopyObjectOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING }
}), "CopyObjectOutputFilterSensitiveLog");
CopyObjectRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING },
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING },
...obj.CopySourceSSECustomerKey && { CopySourceSSECustomerKey: SENSITIVE_STRING }
}), "CopyObjectRequestFilterSensitiveLog");
CreateMultipartUploadOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING }
}), "CreateMultipartUploadOutputFilterSensitiveLog");
CreateMultipartUploadRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING },
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING }
}), "CreateMultipartUploadRequestFilterSensitiveLog");
SessionCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SecretAccessKey && { SecretAccessKey: SENSITIVE_STRING },
...obj.SessionToken && { SessionToken: SENSITIVE_STRING }
}), "SessionCredentialsFilterSensitiveLog");
CreateSessionOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING },
...obj.Credentials && { Credentials: SessionCredentialsFilterSensitiveLog(obj.Credentials) }
}), "CreateSessionOutputFilterSensitiveLog");
CreateSessionRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING }
}), "CreateSessionRequestFilterSensitiveLog");
ServerSideEncryptionByDefaultFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.KMSMasterKeyID && { KMSMasterKeyID: SENSITIVE_STRING }
}), "ServerSideEncryptionByDefaultFilterSensitiveLog");
ServerSideEncryptionRuleFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.ApplyServerSideEncryptionByDefault && {
ApplyServerSideEncryptionByDefault: ServerSideEncryptionByDefaultFilterSensitiveLog(obj.ApplyServerSideEncryptionByDefault)
}
}), "ServerSideEncryptionRuleFilterSensitiveLog");
ServerSideEncryptionConfigurationFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Rules && { Rules: obj.Rules.map((item) => ServerSideEncryptionRuleFilterSensitiveLog(item)) }
}), "ServerSideEncryptionConfigurationFilterSensitiveLog");
GetBucketEncryptionOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.ServerSideEncryptionConfiguration && {
ServerSideEncryptionConfiguration: ServerSideEncryptionConfigurationFilterSensitiveLog(obj.ServerSideEncryptionConfiguration)
}
}), "GetBucketEncryptionOutputFilterSensitiveLog");
SSEKMSFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.KeyId && { KeyId: SENSITIVE_STRING }
}), "SSEKMSFilterSensitiveLog");
InventoryEncryptionFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMS && { SSEKMS: SSEKMSFilterSensitiveLog(obj.SSEKMS) }
}), "InventoryEncryptionFilterSensitiveLog");
InventoryS3BucketDestinationFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Encryption && { Encryption: InventoryEncryptionFilterSensitiveLog(obj.Encryption) }
}), "InventoryS3BucketDestinationFilterSensitiveLog");
InventoryDestinationFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.S3BucketDestination && {
S3BucketDestination: InventoryS3BucketDestinationFilterSensitiveLog(obj.S3BucketDestination)
}
}), "InventoryDestinationFilterSensitiveLog");
InventoryConfigurationFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Destination && { Destination: InventoryDestinationFilterSensitiveLog(obj.Destination) }
}), "InventoryConfigurationFilterSensitiveLog");
GetBucketInventoryConfigurationOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.InventoryConfiguration && {
InventoryConfiguration: InventoryConfigurationFilterSensitiveLog(obj.InventoryConfiguration)
}
}), "GetBucketInventoryConfigurationOutputFilterSensitiveLog");
GetObjectOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING }
}), "GetObjectOutputFilterSensitiveLog");
GetObjectRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "GetObjectRequestFilterSensitiveLog");
GetObjectAttributesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "GetObjectAttributesRequestFilterSensitiveLog");
GetObjectTorrentOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj
}), "GetObjectTorrentOutputFilterSensitiveLog");
HeadObjectOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING }
}), "HeadObjectOutputFilterSensitiveLog");
HeadObjectRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "HeadObjectRequestFilterSensitiveLog");
ListBucketInventoryConfigurationsOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.InventoryConfigurationList && {
InventoryConfigurationList: obj.InventoryConfigurationList.map((item) => InventoryConfigurationFilterSensitiveLog(item))
}
}), "ListBucketInventoryConfigurationsOutputFilterSensitiveLog");
ListPartsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "ListPartsRequestFilterSensitiveLog");
}
});
// ../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/escape-attribute.js
function escapeAttribute(value) {
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
var init_escape_attribute = __esm({
"../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/escape-attribute.js"() {
init_import_meta_url();
__name(escapeAttribute, "escapeAttribute");
}
});
// ../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/escape-element.js
function escapeElement(value) {
return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/\r/g, "
").replace(/\n/g, "
").replace(/\u0085/g, "…").replace(/\u2028/, "
");
}
var init_escape_element = __esm({
"../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/escape-element.js"() {
init_import_meta_url();
__name(escapeElement, "escapeElement");
}
});
// ../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/XmlText.js
var XmlText;
var init_XmlText = __esm({
"../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/XmlText.js"() {
init_import_meta_url();
init_escape_element();
XmlText = class {
static {
__name(this, "XmlText");
}
constructor(value) {
this.value = value;
}
toString() {
return escapeElement("" + this.value);
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/XmlNode.js
var XmlNode;
var init_XmlNode = __esm({
"../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/XmlNode.js"() {
init_import_meta_url();
init_escape_attribute();
init_XmlText();
XmlNode = class _XmlNode {
static {
__name(this, "XmlNode");
}
static of(name2, childText, withName) {
const node2 = new _XmlNode(name2);
if (childText !== void 0) {
node2.addChildNode(new XmlText(childText));
}
if (withName !== void 0) {
node2.withName(withName);
}
return node2;
}
constructor(name2, children = []) {
this.name = name2;
this.children = children;
this.attributes = {};
}
withName(name2) {
this.name = name2;
return this;
}
addAttribute(name2, value) {
this.attributes[name2] = value;
return this;
}
addChildNode(child) {
this.children.push(child);
return this;
}
removeAttribute(name2) {
delete this.attributes[name2];
return this;
}
n(name2) {
this.name = name2;
return this;
}
c(child) {
this.children.push(child);
return this;
}
a(name2, value) {
if (value != null) {
this.attributes[name2] = value;
}
return this;
}
cc(input, field, withName = field) {
if (input[field] != null) {
const node2 = _XmlNode.of(field, input[field]).withName(withName);
this.c(node2);
}
}
l(input, listName, memberName, valueProvider) {
if (input[listName] != null) {
const nodes = valueProvider();
nodes.map((node2) => {
node2.withName(memberName);
this.c(node2);
});
}
}
lc(input, listName, memberName, valueProvider) {
if (input[listName] != null) {
const nodes = valueProvider();
const containerNode = new _XmlNode(memberName);
nodes.map((node2) => {
containerNode.c(node2);
});
this.c(containerNode);
}
}
toString() {
const hasChildren = Boolean(this.children.length);
let xmlText = `<${this.name}`;
const attributes = this.attributes;
for (const attributeName of Object.keys(attributes)) {
const attribute = attributes[attributeName];
if (attribute != null) {
xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`;
}
}
return xmlText += !hasChildren ? "/>" : `>${this.children.map((c6) => c6.toString()).join("")}</${this.name}>`;
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/index.js
var init_dist_es47 = __esm({
"../../node_modules/.pnpm/@aws-sdk+xml-builder@3.709.0/node_modules/@aws-sdk/xml-builder/dist-es/index.js"() {
init_import_meta_url();
init_XmlNode();
init_XmlText();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/models_1.js
var EncryptionTypeMismatch, InvalidRequest, InvalidWriteOffset, TooManyParts, ObjectAlreadyInActiveTierError, SelectObjectContentEventStream, PutBucketEncryptionRequestFilterSensitiveLog, PutBucketInventoryConfigurationRequestFilterSensitiveLog, PutObjectOutputFilterSensitiveLog, PutObjectRequestFilterSensitiveLog, EncryptionFilterSensitiveLog, S3LocationFilterSensitiveLog, OutputLocationFilterSensitiveLog, RestoreRequestFilterSensitiveLog, RestoreObjectRequestFilterSensitiveLog, SelectObjectContentOutputFilterSensitiveLog, SelectObjectContentRequestFilterSensitiveLog, UploadPartOutputFilterSensitiveLog, UploadPartRequestFilterSensitiveLog, UploadPartCopyOutputFilterSensitiveLog, UploadPartCopyRequestFilterSensitiveLog, WriteGetObjectResponseRequestFilterSensitiveLog;
var init_models_1 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/models_1.js"() {
init_import_meta_url();
init_dist_es20();
init_models_0();
init_S3ServiceException();
EncryptionTypeMismatch = class _EncryptionTypeMismatch extends S3ServiceException {
static {
__name(this, "EncryptionTypeMismatch");
}
constructor(opts) {
super({
name: "EncryptionTypeMismatch",
$fault: "client",
...opts
});
this.name = "EncryptionTypeMismatch";
this.$fault = "client";
Object.setPrototypeOf(this, _EncryptionTypeMismatch.prototype);
}
};
InvalidRequest = class _InvalidRequest extends S3ServiceException {
static {
__name(this, "InvalidRequest");
}
constructor(opts) {
super({
name: "InvalidRequest",
$fault: "client",
...opts
});
this.name = "InvalidRequest";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidRequest.prototype);
}
};
InvalidWriteOffset = class _InvalidWriteOffset extends S3ServiceException {
static {
__name(this, "InvalidWriteOffset");
}
constructor(opts) {
super({
name: "InvalidWriteOffset",
$fault: "client",
...opts
});
this.name = "InvalidWriteOffset";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidWriteOffset.prototype);
}
};
TooManyParts = class _TooManyParts extends S3ServiceException {
static {
__name(this, "TooManyParts");
}
constructor(opts) {
super({
name: "TooManyParts",
$fault: "client",
...opts
});
this.name = "TooManyParts";
this.$fault = "client";
Object.setPrototypeOf(this, _TooManyParts.prototype);
}
};
ObjectAlreadyInActiveTierError = class _ObjectAlreadyInActiveTierError extends S3ServiceException {
static {
__name(this, "ObjectAlreadyInActiveTierError");
}
constructor(opts) {
super({
name: "ObjectAlreadyInActiveTierError",
$fault: "client",
...opts
});
this.name = "ObjectAlreadyInActiveTierError";
this.$fault = "client";
Object.setPrototypeOf(this, _ObjectAlreadyInActiveTierError.prototype);
}
};
(function(SelectObjectContentEventStream2) {
SelectObjectContentEventStream2.visit = (value, visitor) => {
if (value.Records !== void 0)
return visitor.Records(value.Records);
if (value.Stats !== void 0)
return visitor.Stats(value.Stats);
if (value.Progress !== void 0)
return visitor.Progress(value.Progress);
if (value.Cont !== void 0)
return visitor.Cont(value.Cont);
if (value.End !== void 0)
return visitor.End(value.End);
return visitor._(value.$unknown[0], value.$unknown[1]);
};
})(SelectObjectContentEventStream || (SelectObjectContentEventStream = {}));
PutBucketEncryptionRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.ServerSideEncryptionConfiguration && {
ServerSideEncryptionConfiguration: ServerSideEncryptionConfigurationFilterSensitiveLog(obj.ServerSideEncryptionConfiguration)
}
}), "PutBucketEncryptionRequestFilterSensitiveLog");
PutBucketInventoryConfigurationRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.InventoryConfiguration && {
InventoryConfiguration: InventoryConfigurationFilterSensitiveLog(obj.InventoryConfiguration)
}
}), "PutBucketInventoryConfigurationRequestFilterSensitiveLog");
PutObjectOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING }
}), "PutObjectOutputFilterSensitiveLog");
PutObjectRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING },
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING },
...obj.SSEKMSEncryptionContext && { SSEKMSEncryptionContext: SENSITIVE_STRING }
}), "PutObjectRequestFilterSensitiveLog");
EncryptionFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.KMSKeyId && { KMSKeyId: SENSITIVE_STRING }
}), "EncryptionFilterSensitiveLog");
S3LocationFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Encryption && { Encryption: EncryptionFilterSensitiveLog(obj.Encryption) }
}), "S3LocationFilterSensitiveLog");
OutputLocationFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.S3 && { S3: S3LocationFilterSensitiveLog(obj.S3) }
}), "OutputLocationFilterSensitiveLog");
RestoreRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.OutputLocation && { OutputLocation: OutputLocationFilterSensitiveLog(obj.OutputLocation) }
}), "RestoreRequestFilterSensitiveLog");
RestoreObjectRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.RestoreRequest && { RestoreRequest: RestoreRequestFilterSensitiveLog(obj.RestoreRequest) }
}), "RestoreObjectRequestFilterSensitiveLog");
SelectObjectContentOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Payload && { Payload: "STREAMING_CONTENT" }
}), "SelectObjectContentOutputFilterSensitiveLog");
SelectObjectContentRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "SelectObjectContentRequestFilterSensitiveLog");
UploadPartOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING }
}), "UploadPartOutputFilterSensitiveLog");
UploadPartRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING }
}), "UploadPartRequestFilterSensitiveLog");
UploadPartCopyOutputFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING }
}), "UploadPartCopyOutputFilterSensitiveLog");
UploadPartCopyRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSECustomerKey && { SSECustomerKey: SENSITIVE_STRING },
...obj.CopySourceSSECustomerKey && { CopySourceSSECustomerKey: SENSITIVE_STRING }
}), "UploadPartCopyRequestFilterSensitiveLog");
WriteGetObjectResponseRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SSEKMSKeyId && { SSEKMSKeyId: SENSITIVE_STRING }
}), "WriteGetObjectResponseRequestFilterSensitiveLog");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/protocols/Aws_restXml.js
var se_AbortMultipartUploadCommand, se_CompleteMultipartUploadCommand, se_CopyObjectCommand, se_CreateBucketCommand, se_CreateBucketMetadataTableConfigurationCommand, se_CreateMultipartUploadCommand, se_CreateSessionCommand, se_DeleteBucketCommand, se_DeleteBucketAnalyticsConfigurationCommand, se_DeleteBucketCorsCommand, se_DeleteBucketEncryptionCommand, se_DeleteBucketIntelligentTieringConfigurationCommand, se_DeleteBucketInventoryConfigurationCommand, se_DeleteBucketLifecycleCommand, se_DeleteBucketMetadataTableConfigurationCommand, se_DeleteBucketMetricsConfigurationCommand, se_DeleteBucketOwnershipControlsCommand, se_DeleteBucketPolicyCommand, se_DeleteBucketReplicationCommand, se_DeleteBucketTaggingCommand, se_DeleteBucketWebsiteCommand, se_DeleteObjectCommand, se_DeleteObjectsCommand, se_DeleteObjectTaggingCommand, se_DeletePublicAccessBlockCommand, se_GetBucketAccelerateConfigurationCommand, se_GetBucketAclCommand, se_GetBucketAnalyticsConfigurationCommand, se_GetBucketCorsCommand, se_GetBucketEncryptionCommand, se_GetBucketIntelligentTieringConfigurationCommand, se_GetBucketInventoryConfigurationCommand, se_GetBucketLifecycleConfigurationCommand, se_GetBucketLocationCommand, se_GetBucketLoggingCommand, se_GetBucketMetadataTableConfigurationCommand, se_GetBucketMetricsConfigurationCommand, se_GetBucketNotificationConfigurationCommand, se_GetBucketOwnershipControlsCommand, se_GetBucketPolicyCommand, se_GetBucketPolicyStatusCommand, se_GetBucketReplicationCommand, se_GetBucketRequestPaymentCommand, se_GetBucketTaggingCommand, se_GetBucketVersioningCommand, se_GetBucketWebsiteCommand, se_GetObjectCommand, se_GetObjectAclCommand, se_GetObjectAttributesCommand, se_GetObjectLegalHoldCommand, se_GetObjectLockConfigurationCommand, se_GetObjectRetentionCommand, se_GetObjectTaggingCommand, se_GetObjectTorrentCommand, se_GetPublicAccessBlockCommand, se_HeadBucketCommand, se_HeadObjectCommand, se_ListBucketAnalyticsConfigurationsCommand, se_ListBucketIntelligentTieringConfigurationsCommand, se_ListBucketInventoryConfigurationsCommand, se_ListBucketMetricsConfigurationsCommand, se_ListBucketsCommand, se_ListDirectoryBucketsCommand, se_ListMultipartUploadsCommand, se_ListObjectsCommand, se_ListObjectsV2Command, se_ListObjectVersionsCommand, se_ListPartsCommand, se_PutBucketAccelerateConfigurationCommand, se_PutBucketAclCommand, se_PutBucketAnalyticsConfigurationCommand, se_PutBucketCorsCommand, se_PutBucketEncryptionCommand, se_PutBucketIntelligentTieringConfigurationCommand, se_PutBucketInventoryConfigurationCommand, se_PutBucketLifecycleConfigurationCommand, se_PutBucketLoggingCommand, se_PutBucketMetricsConfigurationCommand, se_PutBucketNotificationConfigurationCommand, se_PutBucketOwnershipControlsCommand, se_PutBucketPolicyCommand, se_PutBucketReplicationCommand, se_PutBucketRequestPaymentCommand, se_PutBucketTaggingCommand, se_PutBucketVersioningCommand, se_PutBucketWebsiteCommand, se_PutObjectCommand, se_PutObjectAclCommand, se_PutObjectLegalHoldCommand, se_PutObjectLockConfigurationCommand, se_PutObjectRetentionCommand, se_PutObjectTaggingCommand, se_PutPublicAccessBlockCommand, se_RestoreObjectCommand, se_SelectObjectContentCommand, se_UploadPartCommand, se_UploadPartCopyCommand, se_WriteGetObjectResponseCommand, de_AbortMultipartUploadCommand, de_CompleteMultipartUploadCommand, de_CopyObjectCommand, de_CreateBucketCommand, de_CreateBucketMetadataTableConfigurationCommand, de_CreateMultipartUploadCommand, de_CreateSessionCommand, de_DeleteBucketCommand, de_DeleteBucketAnalyticsConfigurationCommand, de_DeleteBucketCorsCommand, de_DeleteBucketEncryptionCommand, de_DeleteBucketIntelligentTieringConfigurationCommand, de_DeleteBucketInventoryConfigurationCommand, de_DeleteBucketLifecycleCommand, de_DeleteBucketMetadataTableConfigurationCommand, de_DeleteBucketMetricsConfigurationCommand, de_DeleteBucketOwnershipControlsCommand, de_DeleteBucketPolicyCommand, de_DeleteBucketReplicationCommand, de_DeleteBucketTaggingCommand, de_DeleteBucketWebsiteCommand, de_DeleteObjectCommand, de_DeleteObjectsCommand, de_DeleteObjectTaggingCommand, de_DeletePublicAccessBlockCommand, de_GetBucketAccelerateConfigurationCommand, de_GetBucketAclCommand, de_GetBucketAnalyticsConfigurationCommand, de_GetBucketCorsCommand, de_GetBucketEncryptionCommand, de_GetBucketIntelligentTieringConfigurationCommand, de_GetBucketInventoryConfigurationCommand, de_GetBucketLifecycleConfigurationCommand, de_GetBucketLocationCommand, de_GetBucketLoggingCommand, de_GetBucketMetadataTableConfigurationCommand, de_GetBucketMetricsConfigurationCommand, de_GetBucketNotificationConfigurationCommand, de_GetBucketOwnershipControlsCommand, de_GetBucketPolicyCommand, de_GetBucketPolicyStatusCommand, de_GetBucketReplicationCommand, de_GetBucketRequestPaymentCommand, de_GetBucketTaggingCommand, de_GetBucketVersioningCommand, de_GetBucketWebsiteCommand, de_GetObjectCommand, de_GetObjectAclCommand, de_GetObjectAttributesCommand, de_GetObjectLegalHoldCommand, de_GetObjectLockConfigurationCommand, de_GetObjectRetentionCommand, de_GetObjectTaggingCommand, de_GetObjectTorrentCommand, de_GetPublicAccessBlockCommand, de_HeadBucketCommand, de_HeadObjectCommand, de_ListBucketAnalyticsConfigurationsCommand, de_ListBucketIntelligentTieringConfigurationsCommand, de_ListBucketInventoryConfigurationsCommand, de_ListBucketMetricsConfigurationsCommand, de_ListBucketsCommand, de_ListDirectoryBucketsCommand, de_ListMultipartUploadsCommand, de_ListObjectsCommand, de_ListObjectsV2Command, de_ListObjectVersionsCommand, de_ListPartsCommand, de_PutBucketAccelerateConfigurationCommand, de_PutBucketAclCommand, de_PutBucketAnalyticsConfigurationCommand, de_PutBucketCorsCommand, de_PutBucketEncryptionCommand, de_PutBucketIntelligentTieringConfigurationCommand, de_PutBucketInventoryConfigurationCommand, de_PutBucketLifecycleConfigurationCommand, de_PutBucketLoggingCommand, de_PutBucketMetricsConfigurationCommand, de_PutBucketNotificationConfigurationCommand, de_PutBucketOwnershipControlsCommand, de_PutBucketPolicyCommand, de_PutBucketReplicationCommand, de_PutBucketRequestPaymentCommand, de_PutBucketTaggingCommand, de_PutBucketVersioningCommand, de_PutBucketWebsiteCommand, de_PutObjectCommand, de_PutObjectAclCommand, de_PutObjectLegalHoldCommand, de_PutObjectLockConfigurationCommand, de_PutObjectRetentionCommand, de_PutObjectTaggingCommand, de_PutPublicAccessBlockCommand, de_RestoreObjectCommand, de_SelectObjectContentCommand, de_UploadPartCommand, de_UploadPartCopyCommand, de_WriteGetObjectResponseCommand, de_CommandError, throwDefaultError2, de_BucketAlreadyExistsRes, de_BucketAlreadyOwnedByYouRes, de_EncryptionTypeMismatchRes, de_InvalidObjectStateRes, de_InvalidRequestRes, de_InvalidWriteOffsetRes, de_NoSuchBucketRes, de_NoSuchKeyRes, de_NoSuchUploadRes, de_NotFoundRes, de_ObjectAlreadyInActiveTierErrorRes, de_ObjectNotInActiveTierErrorRes, de_TooManyPartsRes, de_SelectObjectContentEventStream, de_ContinuationEvent_event, de_EndEvent_event, de_ProgressEvent_event, de_RecordsEvent_event, de_StatsEvent_event, se_AbortIncompleteMultipartUpload, se_AccelerateConfiguration, se_AccessControlPolicy, se_AccessControlTranslation, se_AllowedHeaders, se_AllowedMethods, se_AllowedOrigins, se_AnalyticsAndOperator, se_AnalyticsConfiguration, se_AnalyticsExportDestination, se_AnalyticsFilter, se_AnalyticsS3BucketDestination, se_BucketInfo, se_BucketLifecycleConfiguration, se_BucketLoggingStatus, se_CompletedMultipartUpload, se_CompletedPart, se_CompletedPartList, se_Condition, se_CORSConfiguration, se_CORSRule, se_CORSRules, se_CreateBucketConfiguration, se_CSVInput, se_CSVOutput, se_DefaultRetention, se_Delete, se_DeleteMarkerReplication, se_Destination, se_Encryption, se_EncryptionConfiguration, se_ErrorDocument, se_EventBridgeConfiguration, se_EventList, se_ExistingObjectReplication, se_ExposeHeaders, se_FilterRule, se_FilterRuleList, se_GlacierJobParameters, se_Grant, se_Grantee, se_Grants, se_IndexDocument, se_InputSerialization, se_IntelligentTieringAndOperator, se_IntelligentTieringConfiguration, se_IntelligentTieringFilter, se_InventoryConfiguration, se_InventoryDestination, se_InventoryEncryption, se_InventoryFilter, se_InventoryOptionalFields, se_InventoryS3BucketDestination, se_InventorySchedule, se_JSONInput, se_JSONOutput, se_LambdaFunctionConfiguration, se_LambdaFunctionConfigurationList, se_LifecycleExpiration, se_LifecycleRule, se_LifecycleRuleAndOperator, se_LifecycleRuleFilter, se_LifecycleRules, se_LocationInfo, se_LoggingEnabled, se_MetadataEntry, se_MetadataTableConfiguration, se_Metrics, se_MetricsAndOperator, se_MetricsConfiguration, se_MetricsFilter, se_NoncurrentVersionExpiration, se_NoncurrentVersionTransition, se_NoncurrentVersionTransitionList, se_NotificationConfiguration, se_NotificationConfigurationFilter, se_ObjectIdentifier, se_ObjectIdentifierList, se_ObjectLockConfiguration, se_ObjectLockLegalHold, se_ObjectLockRetention, se_ObjectLockRule, se_OutputLocation, se_OutputSerialization, se_Owner, se_OwnershipControls, se_OwnershipControlsRule, se_OwnershipControlsRules, se_ParquetInput, se_PartitionedPrefix, se_PublicAccessBlockConfiguration, se_QueueConfiguration, se_QueueConfigurationList, se_Redirect, se_RedirectAllRequestsTo, se_ReplicaModifications, se_ReplicationConfiguration, se_ReplicationRule, se_ReplicationRuleAndOperator, se_ReplicationRuleFilter, se_ReplicationRules, se_ReplicationTime, se_ReplicationTimeValue, se_RequestPaymentConfiguration, se_RequestProgress, se_RestoreRequest, se_RoutingRule, se_RoutingRules, se_S3KeyFilter, se_S3Location, se_S3TablesDestination, se_ScanRange, se_SelectParameters, se_ServerSideEncryptionByDefault, se_ServerSideEncryptionConfiguration, se_ServerSideEncryptionRule, se_ServerSideEncryptionRules, se_SimplePrefix, se_SourceSelectionCriteria, se_SSEKMS, se_SseKmsEncryptedObjects, se_SSES3, se_StorageClassAnalysis, se_StorageClassAnalysisDataExport, se_Tag, se_Tagging, se_TagSet, se_TargetGrant, se_TargetGrants, se_TargetObjectKeyFormat, se_Tiering, se_TieringList, se_TopicConfiguration, se_TopicConfigurationList, se_Transition, se_TransitionList, se_UserMetadata, se_VersioningConfiguration, se_WebsiteConfiguration, de_AbortIncompleteMultipartUpload, de_AccessControlTranslation, de_AllowedHeaders, de_AllowedMethods, de_AllowedOrigins, de_AnalyticsAndOperator, de_AnalyticsConfiguration, de_AnalyticsConfigurationList, de_AnalyticsExportDestination, de_AnalyticsFilter, de_AnalyticsS3BucketDestination, de_Bucket, de_Buckets, de_Checksum, de_ChecksumAlgorithmList, de_CommonPrefix, de_CommonPrefixList, de_Condition, de_ContinuationEvent, de_CopyObjectResult, de_CopyPartResult, de_CORSRule, de_CORSRules, de_DefaultRetention, de_DeletedObject, de_DeletedObjects, de_DeleteMarkerEntry, de_DeleteMarkerReplication, de_DeleteMarkers, de_Destination, de_EncryptionConfiguration, de_EndEvent, de__Error, de_ErrorDetails, de_ErrorDocument, de_Errors, de_EventBridgeConfiguration, de_EventList, de_ExistingObjectReplication, de_ExposeHeaders, de_FilterRule, de_FilterRuleList, de_GetBucketMetadataTableConfigurationResult, de_GetObjectAttributesParts, de_Grant, de_Grantee, de_Grants, de_IndexDocument, de_Initiator, de_IntelligentTieringAndOperator, de_IntelligentTieringConfiguration, de_IntelligentTieringConfigurationList, de_IntelligentTieringFilter, de_InventoryConfiguration, de_InventoryConfigurationList, de_InventoryDestination, de_InventoryEncryption, de_InventoryFilter, de_InventoryOptionalFields, de_InventoryS3BucketDestination, de_InventorySchedule, de_LambdaFunctionConfiguration, de_LambdaFunctionConfigurationList, de_LifecycleExpiration, de_LifecycleRule, de_LifecycleRuleAndOperator, de_LifecycleRuleFilter, de_LifecycleRules, de_LoggingEnabled, de_MetadataTableConfigurationResult, de_Metrics, de_MetricsAndOperator, de_MetricsConfiguration, de_MetricsConfigurationList, de_MetricsFilter, de_MultipartUpload, de_MultipartUploadList, de_NoncurrentVersionExpiration, de_NoncurrentVersionTransition, de_NoncurrentVersionTransitionList, de_NotificationConfigurationFilter, de__Object, de_ObjectList, de_ObjectLockConfiguration, de_ObjectLockLegalHold, de_ObjectLockRetention, de_ObjectLockRule, de_ObjectPart, de_ObjectVersion, de_ObjectVersionList, de_Owner, de_OwnershipControls, de_OwnershipControlsRule, de_OwnershipControlsRules, de_Part, de_PartitionedPrefix, de_Parts, de_PartsList, de_PolicyStatus, de_Progress, de_PublicAccessBlockConfiguration, de_QueueConfiguration, de_QueueConfigurationList, de_Redirect, de_RedirectAllRequestsTo, de_ReplicaModifications, de_ReplicationConfiguration, de_ReplicationRule, de_ReplicationRuleAndOperator, de_ReplicationRuleFilter, de_ReplicationRules, de_ReplicationTime, de_ReplicationTimeValue, de_RestoreStatus, de_RoutingRule, de_RoutingRules, de_S3KeyFilter, de_S3TablesDestinationResult, de_ServerSideEncryptionByDefault, de_ServerSideEncryptionConfiguration, de_ServerSideEncryptionRule, de_ServerSideEncryptionRules, de_SessionCredentials, de_SimplePrefix, de_SourceSelectionCriteria, de_SSEKMS, de_SseKmsEncryptedObjects, de_SSES3, de_Stats, de_StorageClassAnalysis, de_StorageClassAnalysisDataExport, de_Tag, de_TagSet, de_TargetGrant, de_TargetGrants, de_TargetObjectKeyFormat, de_Tiering, de_TieringList, de_TopicConfiguration, de_TopicConfigurationList, de_Transition, de_TransitionList, deserializeMetadata2, collectBodyString2, _A, _AAO, _AC, _ACL, _ACLc, _ACLn, _ACP, _ACT, _ACc, _AD, _AED, _AF, _AH, _AHl, _AI, _AIMU, _AIc, _AKI, _AM, _AMl, _AO, _AOl, _APA, _APAc, _AQRD, _AR, _ARI, _AS, _ASBD, _ASEFF, _ASSEBD, _AT, _Ac, _B, _BAI, _BAS, _BGR, _BI, _BKE, _BLC, _BLCu, _BLN, _BLP, _BLS, _BLT, _BN, _BP, _BPA, _BPP, _BR, _BRy, _BS, _BT, _BVS, _Bu, _C, _CA, _CACL, _CBC, _CC, _CCRC, _CCRCC, _CD, _CDr, _CE, _CF, _CFC, _CL, _CLo, _CM, _CMD, _CMU, _CORSC, _CORSR, _CORSRu, _CP, _CPo, _CR, _CRSBA, _CS, _CSHA, _CSHAh, _CSIM, _CSIMS, _CSINM, _CSIUS, _CSR, _CSSSECA, _CSSSECK, _CSSSECKMD, _CSV, _CSVI, _CSVIn, _CSVO, _CT, _CTo, _CTom, _Ch, _Co, _Cod, _Com, _Con, _D, _DAI, _DE, _DM, _DMR, _DMRS, _DMVI, _DMe, _DN, _DR, _DRe, _Da, _Dat, _De, _Del, _Des, _Desc, _E, _EA, _EBC, _EBO, _EC, _ECn, _ED, _EH, _EHx, _EM, _EODM, _EOR, _EORS, _ERP, _ES, _ESBO, _ESx, _ET, _ETa, _ETn, _ETv, _ETx, _En, _Ena, _End, _Er, _Err, _Ev, _Eve, _Ex, _Exp, _F, _FD, _FHI, _FO, _FR, _FRN, _FRV, _FRi, _Fi, _Fo, _Fr, _G, _GFC, _GJP, _GR, _GRACP, _GW, _GWACP, _Gr, _Gra, _HECRE, _HN, _HRC, _I, _IC, _ICL, _ID, _ID_, _IDn, _IE, _IEn, _IF, _IFn, _IFnv, _II, _IIOV, _IL, _IM, _IMIT, _IMLMT, _IMS, _IMSf, _INM, _IOF, _IOV, _IP, _IPA, _IRIP, _IS, _ISBD, _ISn, _IT, _ITAO, _ITAT, _ITC, _ITCL, _ITD, _ITF, _ITI, _ITS, _IUS, _In, _Ini, _JSON, _JSONI, _JSONO, _JSONT, _K, _KC, _KI, _KM, _KMSC, _KMSKI, _KMSMKID, _KPE, _L, _LC, _LE, _LEi, _LFA, _LFC, _LFCa, _LI, _LM, _LMT, _LNAS, _LP, _LR, _LRAO, _LRF, _LT, _M, _MAO, _MAS, _MB, _MC, _MCL, _MD, _MDB, _MDf, _ME, _MF, _MFA, _MFAD, _MI, _MK, _MKe, _MM, _MP, _MS, _MTC, _MTCR, _MU, _MV, _Me, _Mes, _Mi, _Mo, _N, _NC, _NCF, _NCT, _ND, _NI, _NKM, _NM, _NNV, _NPNM, _NUIM, _NVE, _NVIM, _NVT, _NVTo, _O, _OA, _OC, _OCACL, _OCR, _OF, _OI, _OK, _OL, _OLC, _OLE, _OLEFB, _OLLH, _OLLHS, _OLM, _OLR, _OLRM, _OLRUD, _OLRb, _OO, _OOA, _OOw, _OP, _OS, _OSGT, _OSGTB, _OSLT, _OSLTB, _OSV, _OSb, _OVI, _Ob, _P, _PABC, _PC, _PDS, _PI, _PN, _PNM, _PP, _Pa, _Par, _Parq, _Part, _Pe, _Pr, _Pri, _Q, _QA, _QC, _QCu, _QCuo, _QEC, _QF, _Qu, _R, _RART, _RC, _RCC, _RCD, _RCE, _RCL, _RCT, _RCe, _RD, _RE, _RED, _RKKID, _RKPW, _RKW, _RM, _RMS, _ROP, _RP, _RPB, _RPC, _RPe, _RR, _RRAO, _RRF, _RRS, _RRT, _RRe, _RRes, _RRo, _RRou, _RS, _RSe, _RT, _RTS, _RTV, _RTe, _RUD, _Re, _Red, _Ro, _Ru, _Rul, _S, _SA, _SAK, _SBD, _SC, _SCA, _SCADE, _SCASV, _SCt, _SDV, _SK, _SKEO, _SKEOS, _SKF, _SKe, _SL, _SM, _SOCR, _SP, _SPi, _SR, _SS, _SSC, _SSE, _SSEA, _SSEBD, _SSEC, _SSECA, _SSECK, _SSECKMD, _SSEKMS, _SSEKMSEC, _SSEKMSKI, _SSER, _SSES, _ST, _STBA, _STD, _STDR, _STN, _S_, _Sc, _Se, _Si, _St, _Su, _T, _TA, _TAa, _TB, _TBA, _TC, _TCo, _TCop, _TD, _TDMOS, _TG, _TGa, _TN, _TNa, _TOKF, _TP, _TPC, _TS, _TSC, _Ta, _Tag, _Ti, _Tie, _Tier, _Tim, _To, _Top, _Tr, _Tra, _Ty, _U, _UI, _UIM, _UM, _URI, _Up, _V, _VC, _VCe, _VI, _VIM, _Va, _Ve, _WC, _WOB, _WRL, _Y, _a2, _ac, _acl, _ar, _at, _br, _c2, _cc, _cd, _ce, _cl, _cl_, _cm, _cr, _ct, _ct_, _d, _de, _e, _en, _et, _eta, _ex, _fo, _i, _im, _ims, _in, _inm, _it, _ius, _km, _l, _lh, _lm, _lo, _log, _lt, _m, _mT, _ma, _mb, _mdb, _me, _mk, _mp, _mu, _n, _oC, _ol, _p, _pAB, _pN, _pS, _pnm, _pr, _r, _rP, _ra, _rcc, _rcd, _rce, _rcl, _rct, _re, _res, _ret, _s, _sa, _se, _st, _t, _to, _u, _uI, _uim, _v, _vI, _ve, _ver, _vim, _w, _x, _xaa, _xaad, _xaapa, _xaari, _xaas, _xabgr, _xabln, _xablt, _xabole, _xabolt, _xabr, _xaca, _xacc, _xacc_, _xacm, _xacrsba, _xacs, _xacs_, _xacs__, _xacsim, _xacsims, _xacsinm, _xacsius, _xacsm, _xacsr, _xacssseca, _xacssseck, _xacssseckm, _xacsvi, _xadm, _xae, _xaebo, _xafec, _xafem, _xafhar, _xafhcc, _xafhcd, _xafhce, _xafhcl, _xafhcr, _xafhct, _xafhe, _xafhe_, _xafhlm, _xafhxacc, _xafhxacc_, _xafhxacs, _xafhxacs_, _xafhxadm, _xafhxae, _xafhxamm, _xafhxampc, _xafhxaollh, _xafhxaolm, _xafhxaolrud, _xafhxar, _xafhxarc, _xafhxars, _xafhxasc, _xafhxasse, _xafhxasseakki, _xafhxassebke, _xafhxasseca, _xafhxasseckm, _xafhxatc, _xafhxavi, _xafs, _xagfc, _xagr, _xagra, _xagw, _xagwa, _xaimit, _xaimlmt, _xaims, _xam, _xamd, _xamm, _xamp, _xampc, _xaoa, _xaollh, _xaolm, _xaolrud, _xaoo, _xaooa, _xaos, _xapnm, _xar, _xarc, _xarop, _xarp, _xarr, _xars, _xart, _xasc, _xasca, _xasdv, _xasebo, _xasse, _xasseakki, _xassebke, _xassec, _xasseca, _xasseck, _xasseckm, _xat, _xatc, _xatd, _xatdmos, _xavi, _xawob, _xawrl, _xi;
var init_Aws_restXml = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/protocols/Aws_restXml.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es47();
init_dist_es16();
init_dist_es2();
init_dist_es20();
init_models_0();
init_models_1();
init_S3ServiceException();
se_AbortMultipartUploadCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xaimit]: [() => isSerializableHeaderValue(input[_IMIT]), () => dateToUtcString(input[_IMIT]).toString()]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "AbortMultipartUpload"],
[_uI]: [, expectNonNull(input[_UI], `UploadId`)]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_AbortMultipartUploadCommand");
se_CompleteMultipartUploadCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xacc]: input[_CCRC],
[_xacc_]: input[_CCRCC],
[_xacs]: input[_CSHA],
[_xacs_]: input[_CSHAh],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_im]: input[_IM],
[_inm]: input[_INM],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_uI]: [, expectNonNull(input[_UI], `UploadId`)]
});
let body;
let contents;
if (input.MultipartUpload !== void 0) {
contents = se_CompletedMultipartUpload(input.MultipartUpload, context2);
contents = contents.n("CompleteMultipartUpload");
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_CompleteMultipartUploadCommand");
se_CopyObjectCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaa]: input[_ACL],
[_cc]: input[_CC],
[_xaca]: input[_CA],
[_cd]: input[_CD],
[_ce]: input[_CE],
[_cl]: input[_CL],
[_ct]: input[_CT],
[_xacs__]: input[_CS],
[_xacsim]: input[_CSIM],
[_xacsims]: [() => isSerializableHeaderValue(input[_CSIMS]), () => dateToUtcString(input[_CSIMS]).toString()],
[_xacsinm]: input[_CSINM],
[_xacsius]: [() => isSerializableHeaderValue(input[_CSIUS]), () => dateToUtcString(input[_CSIUS]).toString()],
[_e]: [() => isSerializableHeaderValue(input[_E]), () => dateToUtcString(input[_E]).toString()],
[_xagfc]: input[_GFC],
[_xagr]: input[_GR],
[_xagra]: input[_GRACP],
[_xagwa]: input[_GWACP],
[_xamd]: input[_MD],
[_xatd]: input[_TD],
[_xasse]: input[_SSE],
[_xasc]: input[_SC],
[_xawrl]: input[_WRL],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xasseakki]: input[_SSEKMSKI],
[_xassec]: input[_SSEKMSEC],
[_xassebke]: [() => isSerializableHeaderValue(input[_BKE]), () => input[_BKE].toString()],
[_xacssseca]: input[_CSSSECA],
[_xacssseck]: input[_CSSSECK],
[_xacssseckm]: input[_CSSSECKMD],
[_xarp]: input[_RP],
[_xat]: input[_T],
[_xaolm]: input[_OLM],
[_xaolrud]: [() => isSerializableHeaderValue(input[_OLRUD]), () => serializeDateTime(input[_OLRUD]).toString()],
[_xaollh]: input[_OLLHS],
[_xaebo]: input[_EBO],
[_xasebo]: input[_ESBO],
...input.Metadata !== void 0 && Object.keys(input.Metadata).reduce((acc, suffix) => {
acc[`x-amz-meta-${suffix.toLowerCase()}`] = input.Metadata[suffix];
return acc;
}, {})
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "CopyObject"]
});
let body;
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_CopyObjectCommand");
se_CreateBucketCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaa]: input[_ACL],
[_xagfc]: input[_GFC],
[_xagr]: input[_GR],
[_xagra]: input[_GRACP],
[_xagw]: input[_GW],
[_xagwa]: input[_GWACP],
[_xabole]: [() => isSerializableHeaderValue(input[_OLEFB]), () => input[_OLEFB].toString()],
[_xaoo]: input[_OO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
let body;
let contents;
if (input.CreateBucketConfiguration !== void 0) {
contents = se_CreateBucketConfiguration(input.CreateBucketConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).b(body);
return b6.build();
}, "se_CreateBucketCommand");
se_CreateBucketMetadataTableConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_mT]: [, ""]
});
let body;
let contents;
if (input.MetadataTableConfiguration !== void 0) {
contents = se_MetadataTableConfiguration(input.MetadataTableConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_CreateBucketMetadataTableConfigurationCommand");
se_CreateMultipartUploadCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaa]: input[_ACL],
[_cc]: input[_CC],
[_cd]: input[_CD],
[_ce]: input[_CE],
[_cl]: input[_CL],
[_ct]: input[_CT],
[_e]: [() => isSerializableHeaderValue(input[_E]), () => dateToUtcString(input[_E]).toString()],
[_xagfc]: input[_GFC],
[_xagr]: input[_GR],
[_xagra]: input[_GRACP],
[_xagwa]: input[_GWACP],
[_xasse]: input[_SSE],
[_xasc]: input[_SC],
[_xawrl]: input[_WRL],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xasseakki]: input[_SSEKMSKI],
[_xassec]: input[_SSEKMSEC],
[_xassebke]: [() => isSerializableHeaderValue(input[_BKE]), () => input[_BKE].toString()],
[_xarp]: input[_RP],
[_xat]: input[_T],
[_xaolm]: input[_OLM],
[_xaolrud]: [() => isSerializableHeaderValue(input[_OLRUD]), () => serializeDateTime(input[_OLRUD]).toString()],
[_xaollh]: input[_OLLHS],
[_xaebo]: input[_EBO],
[_xaca]: input[_CA],
...input.Metadata !== void 0 && Object.keys(input.Metadata).reduce((acc, suffix) => {
acc[`x-amz-meta-${suffix.toLowerCase()}`] = input.Metadata[suffix];
return acc;
}, {})
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_u]: [, ""]
});
let body;
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_CreateMultipartUploadCommand");
se_CreateSessionCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xacsm]: input[_SM],
[_xasse]: input[_SSE],
[_xasseakki]: input[_SSEKMSKI],
[_xassec]: input[_SSEKMSEC],
[_xassebke]: [() => isSerializableHeaderValue(input[_BKE]), () => input[_BKE].toString()]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_s]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_CreateSessionCommand");
se_DeleteBucketCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
let body;
b6.m("DELETE").h(headers).b(body);
return b6.build();
}, "se_DeleteBucketCommand");
se_DeleteBucketAnalyticsConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_a2]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketAnalyticsConfigurationCommand");
se_DeleteBucketCorsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_c2]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketCorsCommand");
se_DeleteBucketEncryptionCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_en]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketEncryptionCommand");
se_DeleteBucketIntelligentTieringConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {};
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_it]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketIntelligentTieringConfigurationCommand");
se_DeleteBucketInventoryConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_in]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketInventoryConfigurationCommand");
se_DeleteBucketLifecycleCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_l]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketLifecycleCommand");
se_DeleteBucketMetadataTableConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_mT]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketMetadataTableConfigurationCommand");
se_DeleteBucketMetricsConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_m]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketMetricsConfigurationCommand");
se_DeleteBucketOwnershipControlsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_oC]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketOwnershipControlsCommand");
se_DeleteBucketPolicyCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_p]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketPolicyCommand");
se_DeleteBucketReplicationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_r]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketReplicationCommand");
se_DeleteBucketTaggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_t]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketTaggingCommand");
se_DeleteBucketWebsiteCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_w]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteBucketWebsiteCommand");
se_DeleteObjectCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xam]: input[_MFA],
[_xarp]: input[_RP],
[_xabgr]: [() => isSerializableHeaderValue(input[_BGR]), () => input[_BGR].toString()],
[_xaebo]: input[_EBO],
[_im]: input[_IM],
[_xaimlmt]: [() => isSerializableHeaderValue(input[_IMLMT]), () => dateToUtcString(input[_IMLMT]).toString()],
[_xaims]: [() => isSerializableHeaderValue(input[_IMS]), () => input[_IMS].toString()]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "DeleteObject"],
[_vI]: [, input[_VI]]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteObjectCommand");
se_DeleteObjectsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xam]: input[_MFA],
[_xarp]: input[_RP],
[_xabgr]: [() => isSerializableHeaderValue(input[_BGR]), () => input[_BGR].toString()],
[_xaebo]: input[_EBO],
[_xasca]: input[_CA]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_d]: [, ""]
});
let body;
let contents;
if (input.Delete !== void 0) {
contents = se_Delete(input.Delete, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteObjectsCommand");
se_DeleteObjectTaggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_t]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeleteObjectTaggingCommand");
se_DeletePublicAccessBlockCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_pAB]: [, ""]
});
let body;
b6.m("DELETE").h(headers).q(query).b(body);
return b6.build();
}, "se_DeletePublicAccessBlockCommand");
se_GetBucketAccelerateConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO],
[_xarp]: input[_RP]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_ac]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketAccelerateConfigurationCommand");
se_GetBucketAclCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_acl]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketAclCommand");
se_GetBucketAnalyticsConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_a2]: [, ""],
[_xi]: [, "GetBucketAnalyticsConfiguration"],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketAnalyticsConfigurationCommand");
se_GetBucketCorsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_c2]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketCorsCommand");
se_GetBucketEncryptionCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_en]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketEncryptionCommand");
se_GetBucketIntelligentTieringConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {};
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_it]: [, ""],
[_xi]: [, "GetBucketIntelligentTieringConfiguration"],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketIntelligentTieringConfigurationCommand");
se_GetBucketInventoryConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_in]: [, ""],
[_xi]: [, "GetBucketInventoryConfiguration"],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketInventoryConfigurationCommand");
se_GetBucketLifecycleConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_l]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketLifecycleConfigurationCommand");
se_GetBucketLocationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_lo]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketLocationCommand");
se_GetBucketLoggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_log]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketLoggingCommand");
se_GetBucketMetadataTableConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_mT]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketMetadataTableConfigurationCommand");
se_GetBucketMetricsConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_m]: [, ""],
[_xi]: [, "GetBucketMetricsConfiguration"],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketMetricsConfigurationCommand");
se_GetBucketNotificationConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_n]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketNotificationConfigurationCommand");
se_GetBucketOwnershipControlsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_oC]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketOwnershipControlsCommand");
se_GetBucketPolicyCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_p]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketPolicyCommand");
se_GetBucketPolicyStatusCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_pS]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketPolicyStatusCommand");
se_GetBucketReplicationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_r]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketReplicationCommand");
se_GetBucketRequestPaymentCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_rP]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketRequestPaymentCommand");
se_GetBucketTaggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_t]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketTaggingCommand");
se_GetBucketVersioningCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_v]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketVersioningCommand");
se_GetBucketWebsiteCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_w]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetBucketWebsiteCommand");
se_GetObjectCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_im]: input[_IM],
[_ims]: [() => isSerializableHeaderValue(input[_IMSf]), () => dateToUtcString(input[_IMSf]).toString()],
[_inm]: input[_INM],
[_ius]: [() => isSerializableHeaderValue(input[_IUS]), () => dateToUtcString(input[_IUS]).toString()],
[_ra]: input[_R],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xacm]: input[_CM]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "GetObject"],
[_rcc]: [, input[_RCC]],
[_rcd]: [, input[_RCD]],
[_rce]: [, input[_RCE]],
[_rcl]: [, input[_RCL]],
[_rct]: [, input[_RCT]],
[_re]: [() => input.ResponseExpires !== void 0, () => dateToUtcString(input[_RE]).toString()],
[_vI]: [, input[_VI]],
[_pN]: [() => input.PartNumber !== void 0, () => input[_PN].toString()]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectCommand");
se_GetObjectAclCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_acl]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectAclCommand");
se_GetObjectAttributesCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xamp]: [() => isSerializableHeaderValue(input[_MP]), () => input[_MP].toString()],
[_xapnm]: input[_PNM],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xaoa]: [() => isSerializableHeaderValue(input[_OA]), () => (input[_OA] || []).map(quoteHeader).join(", ")]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_at]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectAttributesCommand");
se_GetObjectLegalHoldCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_lh]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectLegalHoldCommand");
se_GetObjectLockConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_ol]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectLockConfigurationCommand");
se_GetObjectRetentionCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_ret]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectRetentionCommand");
se_GetObjectTaggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO],
[_xarp]: input[_RP]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_t]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectTaggingCommand");
se_GetObjectTorrentCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_to]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetObjectTorrentCommand");
se_GetPublicAccessBlockCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_pAB]: [, ""]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetPublicAccessBlockCommand");
se_HeadBucketCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
let body;
b6.m("HEAD").h(headers).b(body);
return b6.build();
}, "se_HeadBucketCommand");
se_HeadObjectCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_im]: input[_IM],
[_ims]: [() => isSerializableHeaderValue(input[_IMSf]), () => dateToUtcString(input[_IMSf]).toString()],
[_inm]: input[_INM],
[_ius]: [() => isSerializableHeaderValue(input[_IUS]), () => dateToUtcString(input[_IUS]).toString()],
[_ra]: input[_R],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xacm]: input[_CM]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_rcc]: [, input[_RCC]],
[_rcd]: [, input[_RCD]],
[_rce]: [, input[_RCE]],
[_rcl]: [, input[_RCL]],
[_rct]: [, input[_RCT]],
[_re]: [() => input.ResponseExpires !== void 0, () => dateToUtcString(input[_RE]).toString()],
[_vI]: [, input[_VI]],
[_pN]: [() => input.PartNumber !== void 0, () => input[_PN].toString()]
});
let body;
b6.m("HEAD").h(headers).q(query).b(body);
return b6.build();
}, "se_HeadObjectCommand");
se_ListBucketAnalyticsConfigurationsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_a2]: [, ""],
[_xi]: [, "ListBucketAnalyticsConfigurations"],
[_ct_]: [, input[_CTo]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListBucketAnalyticsConfigurationsCommand");
se_ListBucketIntelligentTieringConfigurationsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {};
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_it]: [, ""],
[_xi]: [, "ListBucketIntelligentTieringConfigurations"],
[_ct_]: [, input[_CTo]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListBucketIntelligentTieringConfigurationsCommand");
se_ListBucketInventoryConfigurationsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_in]: [, ""],
[_xi]: [, "ListBucketInventoryConfigurations"],
[_ct_]: [, input[_CTo]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListBucketInventoryConfigurationsCommand");
se_ListBucketMetricsConfigurationsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_m]: [, ""],
[_xi]: [, "ListBucketMetricsConfigurations"],
[_ct_]: [, input[_CTo]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListBucketMetricsConfigurationsCommand");
se_ListBucketsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {};
b6.bp("/");
const query = map({
[_xi]: [, "ListBuckets"],
[_mb]: [() => input.MaxBuckets !== void 0, () => input[_MB].toString()],
[_ct_]: [, input[_CTo]],
[_pr]: [, input[_P]],
[_br]: [, input[_BR]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListBucketsCommand");
se_ListDirectoryBucketsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {};
b6.bp("/");
const query = map({
[_xi]: [, "ListDirectoryBuckets"],
[_ct_]: [, input[_CTo]],
[_mdb]: [() => input.MaxDirectoryBuckets !== void 0, () => input[_MDB].toString()]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListDirectoryBucketsCommand");
se_ListMultipartUploadsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO],
[_xarp]: input[_RP]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_u]: [, ""],
[_de]: [, input[_D]],
[_et]: [, input[_ET]],
[_km]: [, input[_KM]],
[_mu]: [() => input.MaxUploads !== void 0, () => input[_MU].toString()],
[_pr]: [, input[_P]],
[_uim]: [, input[_UIM]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListMultipartUploadsCommand");
se_ListObjectsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xaooa]: [() => isSerializableHeaderValue(input[_OOA]), () => (input[_OOA] || []).map(quoteHeader).join(", ")]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_de]: [, input[_D]],
[_et]: [, input[_ET]],
[_ma]: [, input[_M]],
[_mk]: [() => input.MaxKeys !== void 0, () => input[_MK].toString()],
[_pr]: [, input[_P]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListObjectsCommand");
se_ListObjectsV2Command = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xaooa]: [() => isSerializableHeaderValue(input[_OOA]), () => (input[_OOA] || []).map(quoteHeader).join(", ")]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_lt]: [, "2"],
[_de]: [, input[_D]],
[_et]: [, input[_ET]],
[_mk]: [() => input.MaxKeys !== void 0, () => input[_MK].toString()],
[_pr]: [, input[_P]],
[_ct_]: [, input[_CTo]],
[_fo]: [() => input.FetchOwner !== void 0, () => input[_FO].toString()],
[_sa]: [, input[_SA]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListObjectsV2Command");
se_ListObjectVersionsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xaebo]: input[_EBO],
[_xarp]: input[_RP],
[_xaooa]: [() => isSerializableHeaderValue(input[_OOA]), () => (input[_OOA] || []).map(quoteHeader).join(", ")]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_ver]: [, ""],
[_de]: [, input[_D]],
[_et]: [, input[_ET]],
[_km]: [, input[_KM]],
[_mk]: [() => input.MaxKeys !== void 0, () => input[_MK].toString()],
[_pr]: [, input[_P]],
[_vim]: [, input[_VIM]]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListObjectVersionsCommand");
se_ListPartsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "ListParts"],
[_mp]: [() => input.MaxParts !== void 0, () => input[_MP].toString()],
[_pnm]: [, input[_PNM]],
[_uI]: [, expectNonNull(input[_UI], `UploadId`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListPartsCommand");
se_PutBucketAccelerateConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: input[_EBO],
[_xasca]: input[_CA]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_ac]: [, ""]
});
let body;
let contents;
if (input.AccelerateConfiguration !== void 0) {
contents = se_AccelerateConfiguration(input.AccelerateConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketAccelerateConfigurationCommand");
se_PutBucketAclCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaa]: input[_ACL],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xagfc]: input[_GFC],
[_xagr]: input[_GR],
[_xagra]: input[_GRACP],
[_xagw]: input[_GW],
[_xagwa]: input[_GWACP],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_acl]: [, ""]
});
let body;
let contents;
if (input.AccessControlPolicy !== void 0) {
contents = se_AccessControlPolicy(input.AccessControlPolicy, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketAclCommand");
se_PutBucketAnalyticsConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_a2]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
let contents;
if (input.AnalyticsConfiguration !== void 0) {
contents = se_AnalyticsConfiguration(input.AnalyticsConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketAnalyticsConfigurationCommand");
se_PutBucketCorsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_c2]: [, ""]
});
let body;
let contents;
if (input.CORSConfiguration !== void 0) {
contents = se_CORSConfiguration(input.CORSConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketCorsCommand");
se_PutBucketEncryptionCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_en]: [, ""]
});
let body;
let contents;
if (input.ServerSideEncryptionConfiguration !== void 0) {
contents = se_ServerSideEncryptionConfiguration(input.ServerSideEncryptionConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketEncryptionCommand");
se_PutBucketIntelligentTieringConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {
"content-type": "application/xml"
};
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_it]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
let contents;
if (input.IntelligentTieringConfiguration !== void 0) {
contents = se_IntelligentTieringConfiguration(input.IntelligentTieringConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketIntelligentTieringConfigurationCommand");
se_PutBucketInventoryConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_in]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
let contents;
if (input.InventoryConfiguration !== void 0) {
contents = se_InventoryConfiguration(input.InventoryConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketInventoryConfigurationCommand");
se_PutBucketLifecycleConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xasca]: input[_CA],
[_xaebo]: input[_EBO],
[_xatdmos]: input[_TDMOS]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_l]: [, ""]
});
let body;
let contents;
if (input.LifecycleConfiguration !== void 0) {
contents = se_BucketLifecycleConfiguration(input.LifecycleConfiguration, context2);
contents = contents.n("LifecycleConfiguration");
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketLifecycleConfigurationCommand");
se_PutBucketLoggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_log]: [, ""]
});
let body;
let contents;
if (input.BucketLoggingStatus !== void 0) {
contents = se_BucketLoggingStatus(input.BucketLoggingStatus, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketLoggingCommand");
se_PutBucketMetricsConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_m]: [, ""],
[_i]: [, expectNonNull(input[_I], `Id`)]
});
let body;
let contents;
if (input.MetricsConfiguration !== void 0) {
contents = se_MetricsConfiguration(input.MetricsConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketMetricsConfigurationCommand");
se_PutBucketNotificationConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: input[_EBO],
[_xasdv]: [() => isSerializableHeaderValue(input[_SDV]), () => input[_SDV].toString()]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_n]: [, ""]
});
let body;
let contents;
if (input.NotificationConfiguration !== void 0) {
contents = se_NotificationConfiguration(input.NotificationConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketNotificationConfigurationCommand");
se_PutBucketOwnershipControlsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_oC]: [, ""]
});
let body;
let contents;
if (input.OwnershipControls !== void 0) {
contents = se_OwnershipControls(input.OwnershipControls, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketOwnershipControlsCommand");
se_PutBucketPolicyCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "text/plain",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xacrsba]: [() => isSerializableHeaderValue(input[_CRSBA]), () => input[_CRSBA].toString()],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_p]: [, ""]
});
let body;
let contents;
if (input.Policy !== void 0) {
contents = input.Policy;
body = contents;
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketPolicyCommand");
se_PutBucketReplicationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xabolt]: input[_To],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_r]: [, ""]
});
let body;
let contents;
if (input.ReplicationConfiguration !== void 0) {
contents = se_ReplicationConfiguration(input.ReplicationConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketReplicationCommand");
se_PutBucketRequestPaymentCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_rP]: [, ""]
});
let body;
let contents;
if (input.RequestPaymentConfiguration !== void 0) {
contents = se_RequestPaymentConfiguration(input.RequestPaymentConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketRequestPaymentCommand");
se_PutBucketTaggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_t]: [, ""]
});
let body;
let contents;
if (input.Tagging !== void 0) {
contents = se_Tagging(input.Tagging, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketTaggingCommand");
se_PutBucketVersioningCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xam]: input[_MFA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_v]: [, ""]
});
let body;
let contents;
if (input.VersioningConfiguration !== void 0) {
contents = se_VersioningConfiguration(input.VersioningConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketVersioningCommand");
se_PutBucketWebsiteCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_w]: [, ""]
});
let body;
let contents;
if (input.WebsiteConfiguration !== void 0) {
contents = se_WebsiteConfiguration(input.WebsiteConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutBucketWebsiteCommand");
se_PutObjectCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_ct]: input[_CT] || "application/octet-stream",
[_xaa]: input[_ACL],
[_cc]: input[_CC],
[_cd]: input[_CD],
[_ce]: input[_CE],
[_cl]: input[_CL],
[_cl_]: [() => isSerializableHeaderValue(input[_CLo]), () => input[_CLo].toString()],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xacc]: input[_CCRC],
[_xacc_]: input[_CCRCC],
[_xacs]: input[_CSHA],
[_xacs_]: input[_CSHAh],
[_e]: [() => isSerializableHeaderValue(input[_E]), () => dateToUtcString(input[_E]).toString()],
[_im]: input[_IM],
[_inm]: input[_INM],
[_xagfc]: input[_GFC],
[_xagr]: input[_GR],
[_xagra]: input[_GRACP],
[_xagwa]: input[_GWACP],
[_xawob]: [() => isSerializableHeaderValue(input[_WOB]), () => input[_WOB].toString()],
[_xasse]: input[_SSE],
[_xasc]: input[_SC],
[_xawrl]: input[_WRL],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xasseakki]: input[_SSEKMSKI],
[_xassec]: input[_SSEKMSEC],
[_xassebke]: [() => isSerializableHeaderValue(input[_BKE]), () => input[_BKE].toString()],
[_xarp]: input[_RP],
[_xat]: input[_T],
[_xaolm]: input[_OLM],
[_xaolrud]: [() => isSerializableHeaderValue(input[_OLRUD]), () => serializeDateTime(input[_OLRUD]).toString()],
[_xaollh]: input[_OLLHS],
[_xaebo]: input[_EBO],
...input.Metadata !== void 0 && Object.keys(input.Metadata).reduce((acc, suffix) => {
acc[`x-amz-meta-${suffix.toLowerCase()}`] = input.Metadata[suffix];
return acc;
}, {})
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "PutObject"]
});
let body;
let contents;
if (input.Body !== void 0) {
contents = input.Body;
body = contents;
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutObjectCommand");
se_PutObjectAclCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaa]: input[_ACL],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xagfc]: input[_GFC],
[_xagr]: input[_GR],
[_xagra]: input[_GRACP],
[_xagw]: input[_GW],
[_xagwa]: input[_GWACP],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_acl]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
let contents;
if (input.AccessControlPolicy !== void 0) {
contents = se_AccessControlPolicy(input.AccessControlPolicy, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutObjectAclCommand");
se_PutObjectLegalHoldCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: input[_RP],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_lh]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
let contents;
if (input.LegalHold !== void 0) {
contents = se_ObjectLockLegalHold(input.LegalHold, context2);
contents = contents.n("LegalHold");
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutObjectLegalHoldCommand");
se_PutObjectLockConfigurationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: input[_RP],
[_xabolt]: input[_To],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_ol]: [, ""]
});
let body;
let contents;
if (input.ObjectLockConfiguration !== void 0) {
contents = se_ObjectLockConfiguration(input.ObjectLockConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutObjectLockConfigurationCommand");
se_PutObjectRetentionCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: input[_RP],
[_xabgr]: [() => isSerializableHeaderValue(input[_BGR]), () => input[_BGR].toString()],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_ret]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
let contents;
if (input.Retention !== void 0) {
contents = se_ObjectLockRetention(input.Retention, context2);
contents = contents.n("Retention");
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutObjectRetentionCommand");
se_PutObjectTaggingCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO],
[_xarp]: input[_RP]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_t]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
let contents;
if (input.Tagging !== void 0) {
contents = se_Tagging(input.Tagging, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutObjectTaggingCommand");
se_PutPublicAccessBlockCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
const query = map({
[_pAB]: [, ""]
});
let body;
let contents;
if (input.PublicAccessBlockConfiguration !== void 0) {
contents = se_PublicAccessBlockConfiguration(input.PublicAccessBlockConfiguration, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_PutPublicAccessBlockCommand");
se_RestoreObjectCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: input[_RP],
[_xasca]: input[_CA],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_res]: [, ""],
[_vI]: [, input[_VI]]
});
let body;
let contents;
if (input.RestoreRequest !== void 0) {
contents = se_RestoreRequest(input.RestoreRequest, context2);
body = _ve;
contents.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
body += contents.toString();
}
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_RestoreObjectCommand");
se_SelectObjectContentCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_se]: [, ""],
[_st]: [, "2"]
});
let body;
body = _ve;
const bn2 = new XmlNode(_SOCR);
bn2.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
bn2.cc(input, _Ex);
bn2.cc(input, _ETx);
if (input[_IS] != null) {
bn2.c(se_InputSerialization(input[_IS], context2).n(_IS));
}
if (input[_OS] != null) {
bn2.c(se_OutputSerialization(input[_OS], context2).n(_OS));
}
if (input[_RPe] != null) {
bn2.c(se_RequestProgress(input[_RPe], context2).n(_RPe));
}
if (input[_SR] != null) {
bn2.c(se_ScanRange(input[_SR], context2).n(_SR));
}
body += bn2.toString();
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_SelectObjectContentCommand");
se_UploadPartCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"content-type": "application/octet-stream",
[_cl_]: [() => isSerializableHeaderValue(input[_CLo]), () => input[_CLo].toString()],
[_cm]: input[_CMD],
[_xasca]: input[_CA],
[_xacc]: input[_CCRC],
[_xacc_]: input[_CCRCC],
[_xacs]: input[_CSHA],
[_xacs_]: input[_CSHAh],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "UploadPart"],
[_pN]: [expectNonNull(input.PartNumber, `PartNumber`) != null, () => input[_PN].toString()],
[_uI]: [, expectNonNull(input[_UI], `UploadId`)]
});
let body;
let contents;
if (input.Body !== void 0) {
contents = input.Body;
body = contents;
}
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_UploadPartCommand");
se_UploadPartCopyCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xacs__]: input[_CS],
[_xacsim]: input[_CSIM],
[_xacsims]: [() => isSerializableHeaderValue(input[_CSIMS]), () => dateToUtcString(input[_CSIMS]).toString()],
[_xacsinm]: input[_CSINM],
[_xacsius]: [() => isSerializableHeaderValue(input[_CSIUS]), () => dateToUtcString(input[_CSIUS]).toString()],
[_xacsr]: input[_CSR],
[_xasseca]: input[_SSECA],
[_xasseck]: input[_SSECK],
[_xasseckm]: input[_SSECKMD],
[_xacssseca]: input[_CSSSECA],
[_xacssseck]: input[_CSSSECK],
[_xacssseckm]: input[_CSSSECKMD],
[_xarp]: input[_RP],
[_xaebo]: input[_EBO],
[_xasebo]: input[_ESBO]
});
b6.bp("/{Key+}");
b6.p("Bucket", () => input.Bucket, "{Bucket}", false);
b6.p("Key", () => input.Key, "{Key+}", true);
const query = map({
[_xi]: [, "UploadPartCopy"],
[_pN]: [expectNonNull(input.PartNumber, `PartNumber`) != null, () => input[_PN].toString()],
[_uI]: [, expectNonNull(input[_UI], `UploadId`)]
});
let body;
b6.m("PUT").h(headers).q(query).b(body);
return b6.build();
}, "se_UploadPartCopyCommand");
se_WriteGetObjectResponseCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
"x-amz-content-sha256": "UNSIGNED-PAYLOAD",
"content-type": "application/octet-stream",
[_xarr]: input[_RR],
[_xart]: input[_RT],
[_xafs]: [() => isSerializableHeaderValue(input[_SCt]), () => input[_SCt].toString()],
[_xafec]: input[_EC],
[_xafem]: input[_EM],
[_xafhar]: input[_AR],
[_xafhcc]: input[_CC],
[_xafhcd]: input[_CD],
[_xafhce]: input[_CE],
[_xafhcl]: input[_CL],
[_cl_]: [() => isSerializableHeaderValue(input[_CLo]), () => input[_CLo].toString()],
[_xafhcr]: input[_CR],
[_xafhct]: input[_CT],
[_xafhxacc]: input[_CCRC],
[_xafhxacc_]: input[_CCRCC],
[_xafhxacs]: input[_CSHA],
[_xafhxacs_]: input[_CSHAh],
[_xafhxadm]: [() => isSerializableHeaderValue(input[_DM]), () => input[_DM].toString()],
[_xafhe]: input[_ETa],
[_xafhe_]: [() => isSerializableHeaderValue(input[_E]), () => dateToUtcString(input[_E]).toString()],
[_xafhxae]: input[_Exp],
[_xafhlm]: [() => isSerializableHeaderValue(input[_LM]), () => dateToUtcString(input[_LM]).toString()],
[_xafhxamm]: [() => isSerializableHeaderValue(input[_MM]), () => input[_MM].toString()],
[_xafhxaolm]: input[_OLM],
[_xafhxaollh]: input[_OLLHS],
[_xafhxaolrud]: [
() => isSerializableHeaderValue(input[_OLRUD]),
() => serializeDateTime(input[_OLRUD]).toString()
],
[_xafhxampc]: [() => isSerializableHeaderValue(input[_PC]), () => input[_PC].toString()],
[_xafhxars]: input[_RS],
[_xafhxarc]: input[_RC],
[_xafhxar]: input[_Re],
[_xafhxasse]: input[_SSE],
[_xafhxasseca]: input[_SSECA],
[_xafhxasseakki]: input[_SSEKMSKI],
[_xafhxasseckm]: input[_SSECKMD],
[_xafhxasc]: input[_SC],
[_xafhxatc]: [() => isSerializableHeaderValue(input[_TC]), () => input[_TC].toString()],
[_xafhxavi]: input[_VI],
[_xafhxassebke]: [() => isSerializableHeaderValue(input[_BKE]), () => input[_BKE].toString()],
...input.Metadata !== void 0 && Object.keys(input.Metadata).reduce((acc, suffix) => {
acc[`x-amz-meta-${suffix.toLowerCase()}`] = input.Metadata[suffix];
return acc;
}, {})
});
b6.bp("/WriteGetObjectResponse");
let body;
let contents;
if (input.Body !== void 0) {
contents = input.Body;
body = contents;
}
let { hostname: resolvedHostname } = await context2.endpoint();
if (context2.disableHostPrefix !== true) {
resolvedHostname = "{RequestRoute}." + resolvedHostname;
if (input.RequestRoute === void 0) {
throw new Error("Empty value provided for input host prefix: RequestRoute.");
}
resolvedHostname = resolvedHostname.replace("{RequestRoute}", input.RequestRoute);
if (!isValidHostname(resolvedHostname)) {
throw new Error("ValidationError: prefixed hostname must be hostname compatible.");
}
}
b6.hn(resolvedHostname);
b6.m("POST").h(headers).b(body);
return b6.build();
}, "se_WriteGetObjectResponseCommand");
de_AbortMultipartUploadCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_AbortMultipartUploadCommand");
de_CompleteMultipartUploadCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_Exp]: [, output.headers[_xae]],
[_SSE]: [, output.headers[_xasse]],
[_VI]: [, output.headers[_xavi]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_B] != null) {
contents[_B] = expectString(data[_B]);
}
if (data[_CCRC] != null) {
contents[_CCRC] = expectString(data[_CCRC]);
}
if (data[_CCRCC] != null) {
contents[_CCRCC] = expectString(data[_CCRCC]);
}
if (data[_CSHA] != null) {
contents[_CSHA] = expectString(data[_CSHA]);
}
if (data[_CSHAh] != null) {
contents[_CSHAh] = expectString(data[_CSHAh]);
}
if (data[_ETa] != null) {
contents[_ETa] = expectString(data[_ETa]);
}
if (data[_K] != null) {
contents[_K] = expectString(data[_K]);
}
if (data[_L] != null) {
contents[_L] = expectString(data[_L]);
}
return contents;
}, "de_CompleteMultipartUploadCommand");
de_CopyObjectCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_Exp]: [, output.headers[_xae]],
[_CSVI]: [, output.headers[_xacsvi]],
[_VI]: [, output.headers[_xavi]],
[_SSE]: [, output.headers[_xasse]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_SSEKMSEC]: [, output.headers[_xassec]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_RC]: [, output.headers[_xarc]]
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.CopyObjectResult = de_CopyObjectResult(data, context2);
return contents;
}, "de_CopyObjectCommand");
de_CreateBucketCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_L]: [, output.headers[_lo]]
});
await collectBody(output.body, context2);
return contents;
}, "de_CreateBucketCommand");
de_CreateBucketMetadataTableConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_CreateBucketMetadataTableConfigurationCommand");
de_CreateMultipartUploadCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_AD]: [
() => void 0 !== output.headers[_xaad],
() => expectNonNull(parseRfc7231DateTime(output.headers[_xaad]))
],
[_ARI]: [, output.headers[_xaari]],
[_SSE]: [, output.headers[_xasse]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_SSEKMSEC]: [, output.headers[_xassec]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_RC]: [, output.headers[_xarc]],
[_CA]: [, output.headers[_xaca]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_B] != null) {
contents[_B] = expectString(data[_B]);
}
if (data[_K] != null) {
contents[_K] = expectString(data[_K]);
}
if (data[_UI] != null) {
contents[_UI] = expectString(data[_UI]);
}
return contents;
}, "de_CreateMultipartUploadCommand");
de_CreateSessionCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_SSE]: [, output.headers[_xasse]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_SSEKMSEC]: [, output.headers[_xassec]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_C] != null) {
contents[_C] = de_SessionCredentials(data[_C], context2);
}
return contents;
}, "de_CreateSessionCommand");
de_DeleteBucketCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketCommand");
de_DeleteBucketAnalyticsConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketAnalyticsConfigurationCommand");
de_DeleteBucketCorsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketCorsCommand");
de_DeleteBucketEncryptionCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketEncryptionCommand");
de_DeleteBucketIntelligentTieringConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketIntelligentTieringConfigurationCommand");
de_DeleteBucketInventoryConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketInventoryConfigurationCommand");
de_DeleteBucketLifecycleCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketLifecycleCommand");
de_DeleteBucketMetadataTableConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketMetadataTableConfigurationCommand");
de_DeleteBucketMetricsConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketMetricsConfigurationCommand");
de_DeleteBucketOwnershipControlsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketOwnershipControlsCommand");
de_DeleteBucketPolicyCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketPolicyCommand");
de_DeleteBucketReplicationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketReplicationCommand");
de_DeleteBucketTaggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketTaggingCommand");
de_DeleteBucketWebsiteCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteBucketWebsiteCommand");
de_DeleteObjectCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_DM]: [() => void 0 !== output.headers[_xadm], () => parseBoolean(output.headers[_xadm])],
[_VI]: [, output.headers[_xavi]],
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteObjectCommand");
de_DeleteObjectsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.Deleted === "") {
contents[_De] = [];
} else if (data[_De] != null) {
contents[_De] = de_DeletedObjects(getArrayIfSingleItem(data[_De]), context2);
}
if (data.Error === "") {
contents[_Err] = [];
} else if (data[_Er] != null) {
contents[_Err] = de_Errors(getArrayIfSingleItem(data[_Er]), context2);
}
return contents;
}, "de_DeleteObjectsCommand");
de_DeleteObjectTaggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_VI]: [, output.headers[_xavi]]
});
await collectBody(output.body, context2);
return contents;
}, "de_DeleteObjectTaggingCommand");
de_DeletePublicAccessBlockCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 204 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_DeletePublicAccessBlockCommand");
de_GetBucketAccelerateConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_S] != null) {
contents[_S] = expectString(data[_S]);
}
return contents;
}, "de_GetBucketAccelerateConfigurationCommand");
de_GetBucketAclCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.AccessControlList === "") {
contents[_Gr] = [];
} else if (data[_ACLc] != null && data[_ACLc][_G] != null) {
contents[_Gr] = de_Grants(getArrayIfSingleItem(data[_ACLc][_G]), context2);
}
if (data[_O] != null) {
contents[_O] = de_Owner(data[_O], context2);
}
return contents;
}, "de_GetBucketAclCommand");
de_GetBucketAnalyticsConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.AnalyticsConfiguration = de_AnalyticsConfiguration(data, context2);
return contents;
}, "de_GetBucketAnalyticsConfigurationCommand");
de_GetBucketCorsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.CORSRule === "") {
contents[_CORSRu] = [];
} else if (data[_CORSR] != null) {
contents[_CORSRu] = de_CORSRules(getArrayIfSingleItem(data[_CORSR]), context2);
}
return contents;
}, "de_GetBucketCorsCommand");
de_GetBucketEncryptionCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.ServerSideEncryptionConfiguration = de_ServerSideEncryptionConfiguration(data, context2);
return contents;
}, "de_GetBucketEncryptionCommand");
de_GetBucketIntelligentTieringConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.IntelligentTieringConfiguration = de_IntelligentTieringConfiguration(data, context2);
return contents;
}, "de_GetBucketIntelligentTieringConfigurationCommand");
de_GetBucketInventoryConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.InventoryConfiguration = de_InventoryConfiguration(data, context2);
return contents;
}, "de_GetBucketInventoryConfigurationCommand");
de_GetBucketLifecycleConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_TDMOS]: [, output.headers[_xatdmos]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.Rule === "") {
contents[_Rul] = [];
} else if (data[_Ru] != null) {
contents[_Rul] = de_LifecycleRules(getArrayIfSingleItem(data[_Ru]), context2);
}
return contents;
}, "de_GetBucketLifecycleConfigurationCommand");
de_GetBucketLocationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_LC] != null) {
contents[_LC] = expectString(data[_LC]);
}
return contents;
}, "de_GetBucketLocationCommand");
de_GetBucketLoggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_LE] != null) {
contents[_LE] = de_LoggingEnabled(data[_LE], context2);
}
return contents;
}, "de_GetBucketLoggingCommand");
de_GetBucketMetadataTableConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.GetBucketMetadataTableConfigurationResult = de_GetBucketMetadataTableConfigurationResult(data, context2);
return contents;
}, "de_GetBucketMetadataTableConfigurationCommand");
de_GetBucketMetricsConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.MetricsConfiguration = de_MetricsConfiguration(data, context2);
return contents;
}, "de_GetBucketMetricsConfigurationCommand");
de_GetBucketNotificationConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_EBC] != null) {
contents[_EBC] = de_EventBridgeConfiguration(data[_EBC], context2);
}
if (data.CloudFunctionConfiguration === "") {
contents[_LFC] = [];
} else if (data[_CFC] != null) {
contents[_LFC] = de_LambdaFunctionConfigurationList(getArrayIfSingleItem(data[_CFC]), context2);
}
if (data.QueueConfiguration === "") {
contents[_QCu] = [];
} else if (data[_QC] != null) {
contents[_QCu] = de_QueueConfigurationList(getArrayIfSingleItem(data[_QC]), context2);
}
if (data.TopicConfiguration === "") {
contents[_TCop] = [];
} else if (data[_TCo] != null) {
contents[_TCop] = de_TopicConfigurationList(getArrayIfSingleItem(data[_TCo]), context2);
}
return contents;
}, "de_GetBucketNotificationConfigurationCommand");
de_GetBucketOwnershipControlsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.OwnershipControls = de_OwnershipControls(data, context2);
return contents;
}, "de_GetBucketOwnershipControlsCommand");
de_GetBucketPolicyCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = await collectBodyString2(output.body, context2);
contents.Policy = expectString(data);
return contents;
}, "de_GetBucketPolicyCommand");
de_GetBucketPolicyStatusCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.PolicyStatus = de_PolicyStatus(data, context2);
return contents;
}, "de_GetBucketPolicyStatusCommand");
de_GetBucketReplicationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.ReplicationConfiguration = de_ReplicationConfiguration(data, context2);
return contents;
}, "de_GetBucketReplicationCommand");
de_GetBucketRequestPaymentCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_Pa] != null) {
contents[_Pa] = expectString(data[_Pa]);
}
return contents;
}, "de_GetBucketRequestPaymentCommand");
de_GetBucketTaggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.TagSet === "") {
contents[_TS] = [];
} else if (data[_TS] != null && data[_TS][_Ta] != null) {
contents[_TS] = de_TagSet(getArrayIfSingleItem(data[_TS][_Ta]), context2);
}
return contents;
}, "de_GetBucketTaggingCommand");
de_GetBucketVersioningCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_MDf] != null) {
contents[_MFAD] = expectString(data[_MDf]);
}
if (data[_S] != null) {
contents[_S] = expectString(data[_S]);
}
return contents;
}, "de_GetBucketVersioningCommand");
de_GetBucketWebsiteCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_ED] != null) {
contents[_ED] = de_ErrorDocument(data[_ED], context2);
}
if (data[_ID] != null) {
contents[_ID] = de_IndexDocument(data[_ID], context2);
}
if (data[_RART] != null) {
contents[_RART] = de_RedirectAllRequestsTo(data[_RART], context2);
}
if (data.RoutingRules === "") {
contents[_RRo] = [];
} else if (data[_RRo] != null && data[_RRo][_RRou] != null) {
contents[_RRo] = de_RoutingRules(getArrayIfSingleItem(data[_RRo][_RRou]), context2);
}
return contents;
}, "de_GetBucketWebsiteCommand");
de_GetObjectCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_DM]: [() => void 0 !== output.headers[_xadm], () => parseBoolean(output.headers[_xadm])],
[_AR]: [, output.headers[_ar]],
[_Exp]: [, output.headers[_xae]],
[_Re]: [, output.headers[_xar]],
[_LM]: [() => void 0 !== output.headers[_lm], () => expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],
[_CLo]: [() => void 0 !== output.headers[_cl_], () => strictParseLong(output.headers[_cl_])],
[_ETa]: [, output.headers[_eta]],
[_CCRC]: [, output.headers[_xacc]],
[_CCRCC]: [, output.headers[_xacc_]],
[_CSHA]: [, output.headers[_xacs]],
[_CSHAh]: [, output.headers[_xacs_]],
[_MM]: [() => void 0 !== output.headers[_xamm], () => strictParseInt32(output.headers[_xamm])],
[_VI]: [, output.headers[_xavi]],
[_CC]: [, output.headers[_cc]],
[_CD]: [, output.headers[_cd]],
[_CE]: [, output.headers[_ce]],
[_CL]: [, output.headers[_cl]],
[_CR]: [, output.headers[_cr]],
[_CT]: [, output.headers[_ct]],
[_E]: [() => void 0 !== output.headers[_e], () => expectNonNull(parseRfc7231DateTime(output.headers[_e]))],
[_ES]: [, output.headers[_ex]],
[_WRL]: [, output.headers[_xawrl]],
[_SSE]: [, output.headers[_xasse]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_SC]: [, output.headers[_xasc]],
[_RC]: [, output.headers[_xarc]],
[_RS]: [, output.headers[_xars]],
[_PC]: [() => void 0 !== output.headers[_xampc], () => strictParseInt32(output.headers[_xampc])],
[_TC]: [() => void 0 !== output.headers[_xatc], () => strictParseInt32(output.headers[_xatc])],
[_OLM]: [, output.headers[_xaolm]],
[_OLRUD]: [
() => void 0 !== output.headers[_xaolrud],
() => expectNonNull(parseRfc3339DateTimeWithOffset(output.headers[_xaolrud]))
],
[_OLLHS]: [, output.headers[_xaollh]],
Metadata: [
,
Object.keys(output.headers).filter((header) => header.startsWith("x-amz-meta-")).reduce((acc, header) => {
acc[header.substring(11)] = output.headers[header];
return acc;
}, {})
]
});
const data = output.body;
context2.sdkStreamMixin(data);
contents.Body = data;
return contents;
}, "de_GetObjectCommand");
de_GetObjectAclCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.AccessControlList === "") {
contents[_Gr] = [];
} else if (data[_ACLc] != null && data[_ACLc][_G] != null) {
contents[_Gr] = de_Grants(getArrayIfSingleItem(data[_ACLc][_G]), context2);
}
if (data[_O] != null) {
contents[_O] = de_Owner(data[_O], context2);
}
return contents;
}, "de_GetObjectAclCommand");
de_GetObjectAttributesCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_DM]: [() => void 0 !== output.headers[_xadm], () => parseBoolean(output.headers[_xadm])],
[_LM]: [() => void 0 !== output.headers[_lm], () => expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],
[_VI]: [, output.headers[_xavi]],
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_Ch] != null) {
contents[_Ch] = de_Checksum(data[_Ch], context2);
}
if (data[_ETa] != null) {
contents[_ETa] = expectString(data[_ETa]);
}
if (data[_OP] != null) {
contents[_OP] = de_GetObjectAttributesParts(data[_OP], context2);
}
if (data[_OSb] != null) {
contents[_OSb] = strictParseLong(data[_OSb]);
}
if (data[_SC] != null) {
contents[_SC] = expectString(data[_SC]);
}
return contents;
}, "de_GetObjectAttributesCommand");
de_GetObjectLegalHoldCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.LegalHold = de_ObjectLockLegalHold(data, context2);
return contents;
}, "de_GetObjectLegalHoldCommand");
de_GetObjectLockConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.ObjectLockConfiguration = de_ObjectLockConfiguration(data, context2);
return contents;
}, "de_GetObjectLockConfigurationCommand");
de_GetObjectRetentionCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.Retention = de_ObjectLockRetention(data, context2);
return contents;
}, "de_GetObjectRetentionCommand");
de_GetObjectTaggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_VI]: [, output.headers[_xavi]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.TagSet === "") {
contents[_TS] = [];
} else if (data[_TS] != null && data[_TS][_Ta] != null) {
contents[_TS] = de_TagSet(getArrayIfSingleItem(data[_TS][_Ta]), context2);
}
return contents;
}, "de_GetObjectTaggingCommand");
de_GetObjectTorrentCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = output.body;
context2.sdkStreamMixin(data);
contents.Body = data;
return contents;
}, "de_GetObjectTorrentCommand");
de_GetPublicAccessBlockCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.PublicAccessBlockConfiguration = de_PublicAccessBlockConfiguration(data, context2);
return contents;
}, "de_GetPublicAccessBlockCommand");
de_HeadBucketCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_BLT]: [, output.headers[_xablt]],
[_BLN]: [, output.headers[_xabln]],
[_BR]: [, output.headers[_xabr]],
[_APA]: [() => void 0 !== output.headers[_xaapa], () => parseBoolean(output.headers[_xaapa])]
});
await collectBody(output.body, context2);
return contents;
}, "de_HeadBucketCommand");
de_HeadObjectCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_DM]: [() => void 0 !== output.headers[_xadm], () => parseBoolean(output.headers[_xadm])],
[_AR]: [, output.headers[_ar]],
[_Exp]: [, output.headers[_xae]],
[_Re]: [, output.headers[_xar]],
[_AS]: [, output.headers[_xaas]],
[_LM]: [() => void 0 !== output.headers[_lm], () => expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],
[_CLo]: [() => void 0 !== output.headers[_cl_], () => strictParseLong(output.headers[_cl_])],
[_CCRC]: [, output.headers[_xacc]],
[_CCRCC]: [, output.headers[_xacc_]],
[_CSHA]: [, output.headers[_xacs]],
[_CSHAh]: [, output.headers[_xacs_]],
[_ETa]: [, output.headers[_eta]],
[_MM]: [() => void 0 !== output.headers[_xamm], () => strictParseInt32(output.headers[_xamm])],
[_VI]: [, output.headers[_xavi]],
[_CC]: [, output.headers[_cc]],
[_CD]: [, output.headers[_cd]],
[_CE]: [, output.headers[_ce]],
[_CL]: [, output.headers[_cl]],
[_CT]: [, output.headers[_ct]],
[_E]: [() => void 0 !== output.headers[_e], () => expectNonNull(parseRfc7231DateTime(output.headers[_e]))],
[_ES]: [, output.headers[_ex]],
[_WRL]: [, output.headers[_xawrl]],
[_SSE]: [, output.headers[_xasse]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_SC]: [, output.headers[_xasc]],
[_RC]: [, output.headers[_xarc]],
[_RS]: [, output.headers[_xars]],
[_PC]: [() => void 0 !== output.headers[_xampc], () => strictParseInt32(output.headers[_xampc])],
[_OLM]: [, output.headers[_xaolm]],
[_OLRUD]: [
() => void 0 !== output.headers[_xaolrud],
() => expectNonNull(parseRfc3339DateTimeWithOffset(output.headers[_xaolrud]))
],
[_OLLHS]: [, output.headers[_xaollh]],
Metadata: [
,
Object.keys(output.headers).filter((header) => header.startsWith("x-amz-meta-")).reduce((acc, header) => {
acc[header.substring(11)] = output.headers[header];
return acc;
}, {})
]
});
await collectBody(output.body, context2);
return contents;
}, "de_HeadObjectCommand");
de_ListBucketAnalyticsConfigurationsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.AnalyticsConfiguration === "") {
contents[_ACLn] = [];
} else if (data[_AC] != null) {
contents[_ACLn] = de_AnalyticsConfigurationList(getArrayIfSingleItem(data[_AC]), context2);
}
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_NCT] != null) {
contents[_NCT] = expectString(data[_NCT]);
}
return contents;
}, "de_ListBucketAnalyticsConfigurationsCommand");
de_ListBucketIntelligentTieringConfigurationsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
if (data.IntelligentTieringConfiguration === "") {
contents[_ITCL] = [];
} else if (data[_ITC] != null) {
contents[_ITCL] = de_IntelligentTieringConfigurationList(getArrayIfSingleItem(data[_ITC]), context2);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_NCT] != null) {
contents[_NCT] = expectString(data[_NCT]);
}
return contents;
}, "de_ListBucketIntelligentTieringConfigurationsCommand");
de_ListBucketInventoryConfigurationsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
if (data.InventoryConfiguration === "") {
contents[_ICL] = [];
} else if (data[_IC] != null) {
contents[_ICL] = de_InventoryConfigurationList(getArrayIfSingleItem(data[_IC]), context2);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_NCT] != null) {
contents[_NCT] = expectString(data[_NCT]);
}
return contents;
}, "de_ListBucketInventoryConfigurationsCommand");
de_ListBucketMetricsConfigurationsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data.MetricsConfiguration === "") {
contents[_MCL] = [];
} else if (data[_MC] != null) {
contents[_MCL] = de_MetricsConfigurationList(getArrayIfSingleItem(data[_MC]), context2);
}
if (data[_NCT] != null) {
contents[_NCT] = expectString(data[_NCT]);
}
return contents;
}, "de_ListBucketMetricsConfigurationsCommand");
de_ListBucketsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.Buckets === "") {
contents[_Bu] = [];
} else if (data[_Bu] != null && data[_Bu][_B] != null) {
contents[_Bu] = de_Buckets(getArrayIfSingleItem(data[_Bu][_B]), context2);
}
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
if (data[_O] != null) {
contents[_O] = de_Owner(data[_O], context2);
}
if (data[_P] != null) {
contents[_P] = expectString(data[_P]);
}
return contents;
}, "de_ListBucketsCommand");
de_ListDirectoryBucketsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.Buckets === "") {
contents[_Bu] = [];
} else if (data[_Bu] != null && data[_Bu][_B] != null) {
contents[_Bu] = de_Buckets(getArrayIfSingleItem(data[_Bu][_B]), context2);
}
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
return contents;
}, "de_ListDirectoryBucketsCommand");
de_ListMultipartUploadsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_B] != null) {
contents[_B] = expectString(data[_B]);
}
if (data.CommonPrefixes === "") {
contents[_CP] = [];
} else if (data[_CP] != null) {
contents[_CP] = de_CommonPrefixList(getArrayIfSingleItem(data[_CP]), context2);
}
if (data[_D] != null) {
contents[_D] = expectString(data[_D]);
}
if (data[_ET] != null) {
contents[_ET] = expectString(data[_ET]);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_KM] != null) {
contents[_KM] = expectString(data[_KM]);
}
if (data[_MU] != null) {
contents[_MU] = strictParseInt32(data[_MU]);
}
if (data[_NKM] != null) {
contents[_NKM] = expectString(data[_NKM]);
}
if (data[_NUIM] != null) {
contents[_NUIM] = expectString(data[_NUIM]);
}
if (data[_P] != null) {
contents[_P] = expectString(data[_P]);
}
if (data[_UIM] != null) {
contents[_UIM] = expectString(data[_UIM]);
}
if (data.Upload === "") {
contents[_Up] = [];
} else if (data[_U] != null) {
contents[_Up] = de_MultipartUploadList(getArrayIfSingleItem(data[_U]), context2);
}
return contents;
}, "de_ListMultipartUploadsCommand");
de_ListObjectsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.CommonPrefixes === "") {
contents[_CP] = [];
} else if (data[_CP] != null) {
contents[_CP] = de_CommonPrefixList(getArrayIfSingleItem(data[_CP]), context2);
}
if (data.Contents === "") {
contents[_Co] = [];
} else if (data[_Co] != null) {
contents[_Co] = de_ObjectList(getArrayIfSingleItem(data[_Co]), context2);
}
if (data[_D] != null) {
contents[_D] = expectString(data[_D]);
}
if (data[_ET] != null) {
contents[_ET] = expectString(data[_ET]);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_M] != null) {
contents[_M] = expectString(data[_M]);
}
if (data[_MK] != null) {
contents[_MK] = strictParseInt32(data[_MK]);
}
if (data[_N] != null) {
contents[_N] = expectString(data[_N]);
}
if (data[_NM] != null) {
contents[_NM] = expectString(data[_NM]);
}
if (data[_P] != null) {
contents[_P] = expectString(data[_P]);
}
return contents;
}, "de_ListObjectsCommand");
de_ListObjectsV2Command = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.CommonPrefixes === "") {
contents[_CP] = [];
} else if (data[_CP] != null) {
contents[_CP] = de_CommonPrefixList(getArrayIfSingleItem(data[_CP]), context2);
}
if (data.Contents === "") {
contents[_Co] = [];
} else if (data[_Co] != null) {
contents[_Co] = de_ObjectList(getArrayIfSingleItem(data[_Co]), context2);
}
if (data[_CTo] != null) {
contents[_CTo] = expectString(data[_CTo]);
}
if (data[_D] != null) {
contents[_D] = expectString(data[_D]);
}
if (data[_ET] != null) {
contents[_ET] = expectString(data[_ET]);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_KC] != null) {
contents[_KC] = strictParseInt32(data[_KC]);
}
if (data[_MK] != null) {
contents[_MK] = strictParseInt32(data[_MK]);
}
if (data[_N] != null) {
contents[_N] = expectString(data[_N]);
}
if (data[_NCT] != null) {
contents[_NCT] = expectString(data[_NCT]);
}
if (data[_P] != null) {
contents[_P] = expectString(data[_P]);
}
if (data[_SA] != null) {
contents[_SA] = expectString(data[_SA]);
}
return contents;
}, "de_ListObjectsV2Command");
de_ListObjectVersionsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data.CommonPrefixes === "") {
contents[_CP] = [];
} else if (data[_CP] != null) {
contents[_CP] = de_CommonPrefixList(getArrayIfSingleItem(data[_CP]), context2);
}
if (data.DeleteMarker === "") {
contents[_DMe] = [];
} else if (data[_DM] != null) {
contents[_DMe] = de_DeleteMarkers(getArrayIfSingleItem(data[_DM]), context2);
}
if (data[_D] != null) {
contents[_D] = expectString(data[_D]);
}
if (data[_ET] != null) {
contents[_ET] = expectString(data[_ET]);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_KM] != null) {
contents[_KM] = expectString(data[_KM]);
}
if (data[_MK] != null) {
contents[_MK] = strictParseInt32(data[_MK]);
}
if (data[_N] != null) {
contents[_N] = expectString(data[_N]);
}
if (data[_NKM] != null) {
contents[_NKM] = expectString(data[_NKM]);
}
if (data[_NVIM] != null) {
contents[_NVIM] = expectString(data[_NVIM]);
}
if (data[_P] != null) {
contents[_P] = expectString(data[_P]);
}
if (data[_VIM] != null) {
contents[_VIM] = expectString(data[_VIM]);
}
if (data.Version === "") {
contents[_Ve] = [];
} else if (data[_V] != null) {
contents[_Ve] = de_ObjectVersionList(getArrayIfSingleItem(data[_V]), context2);
}
return contents;
}, "de_ListObjectVersionsCommand");
de_ListPartsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_AD]: [
() => void 0 !== output.headers[_xaad],
() => expectNonNull(parseRfc7231DateTime(output.headers[_xaad]))
],
[_ARI]: [, output.headers[_xaari]],
[_RC]: [, output.headers[_xarc]]
});
const data = expectNonNull(expectObject(await parseXmlBody(output.body, context2)), "body");
if (data[_B] != null) {
contents[_B] = expectString(data[_B]);
}
if (data[_CA] != null) {
contents[_CA] = expectString(data[_CA]);
}
if (data[_In] != null) {
contents[_In] = de_Initiator(data[_In], context2);
}
if (data[_IT] != null) {
contents[_IT] = parseBoolean(data[_IT]);
}
if (data[_K] != null) {
contents[_K] = expectString(data[_K]);
}
if (data[_MP] != null) {
contents[_MP] = strictParseInt32(data[_MP]);
}
if (data[_NPNM] != null) {
contents[_NPNM] = expectString(data[_NPNM]);
}
if (data[_O] != null) {
contents[_O] = de_Owner(data[_O], context2);
}
if (data[_PNM] != null) {
contents[_PNM] = expectString(data[_PNM]);
}
if (data.Part === "") {
contents[_Part] = [];
} else if (data[_Par] != null) {
contents[_Part] = de_Parts(getArrayIfSingleItem(data[_Par]), context2);
}
if (data[_SC] != null) {
contents[_SC] = expectString(data[_SC]);
}
if (data[_UI] != null) {
contents[_UI] = expectString(data[_UI]);
}
return contents;
}, "de_ListPartsCommand");
de_PutBucketAccelerateConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketAccelerateConfigurationCommand");
de_PutBucketAclCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketAclCommand");
de_PutBucketAnalyticsConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketAnalyticsConfigurationCommand");
de_PutBucketCorsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketCorsCommand");
de_PutBucketEncryptionCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketEncryptionCommand");
de_PutBucketIntelligentTieringConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketIntelligentTieringConfigurationCommand");
de_PutBucketInventoryConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketInventoryConfigurationCommand");
de_PutBucketLifecycleConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_TDMOS]: [, output.headers[_xatdmos]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketLifecycleConfigurationCommand");
de_PutBucketLoggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketLoggingCommand");
de_PutBucketMetricsConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketMetricsConfigurationCommand");
de_PutBucketNotificationConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketNotificationConfigurationCommand");
de_PutBucketOwnershipControlsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketOwnershipControlsCommand");
de_PutBucketPolicyCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketPolicyCommand");
de_PutBucketReplicationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketReplicationCommand");
de_PutBucketRequestPaymentCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketRequestPaymentCommand");
de_PutBucketTaggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketTaggingCommand");
de_PutBucketVersioningCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketVersioningCommand");
de_PutBucketWebsiteCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutBucketWebsiteCommand");
de_PutObjectCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_Exp]: [, output.headers[_xae]],
[_ETa]: [, output.headers[_eta]],
[_CCRC]: [, output.headers[_xacc]],
[_CCRCC]: [, output.headers[_xacc_]],
[_CSHA]: [, output.headers[_xacs]],
[_CSHAh]: [, output.headers[_xacs_]],
[_SSE]: [, output.headers[_xasse]],
[_VI]: [, output.headers[_xavi]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_SSEKMSEC]: [, output.headers[_xassec]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_Si]: [() => void 0 !== output.headers[_xaos], () => strictParseLong(output.headers[_xaos])],
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutObjectCommand");
de_PutObjectAclCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutObjectAclCommand");
de_PutObjectLegalHoldCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutObjectLegalHoldCommand");
de_PutObjectLockConfigurationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutObjectLockConfigurationCommand");
de_PutObjectRetentionCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutObjectRetentionCommand");
de_PutObjectTaggingCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_VI]: [, output.headers[_xavi]]
});
await collectBody(output.body, context2);
return contents;
}, "de_PutObjectTaggingCommand");
de_PutPublicAccessBlockCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_PutPublicAccessBlockCommand");
de_RestoreObjectCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_RC]: [, output.headers[_xarc]],
[_ROP]: [, output.headers[_xarop]]
});
await collectBody(output.body, context2);
return contents;
}, "de_RestoreObjectCommand");
de_SelectObjectContentCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
const data = output.body;
contents.Payload = de_SelectObjectContentEventStream(data, context2);
return contents;
}, "de_SelectObjectContentCommand");
de_UploadPartCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_SSE]: [, output.headers[_xasse]],
[_ETa]: [, output.headers[_eta]],
[_CCRC]: [, output.headers[_xacc]],
[_CCRCC]: [, output.headers[_xacc_]],
[_CSHA]: [, output.headers[_xacs]],
[_CSHAh]: [, output.headers[_xacs_]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_RC]: [, output.headers[_xarc]]
});
await collectBody(output.body, context2);
return contents;
}, "de_UploadPartCommand");
de_UploadPartCopyCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output),
[_CSVI]: [, output.headers[_xacsvi]],
[_SSE]: [, output.headers[_xasse]],
[_SSECA]: [, output.headers[_xasseca]],
[_SSECKMD]: [, output.headers[_xasseckm]],
[_SSEKMSKI]: [, output.headers[_xasseakki]],
[_BKE]: [() => void 0 !== output.headers[_xassebke], () => parseBoolean(output.headers[_xassebke])],
[_RC]: [, output.headers[_xarc]]
});
const data = expectObject(await parseXmlBody(output.body, context2));
contents.CopyPartResult = de_CopyPartResult(data, context2);
return contents;
}, "de_UploadPartCopyCommand");
de_WriteGetObjectResponseCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError(output, context2);
}
const contents = map({
$metadata: deserializeMetadata2(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_WriteGetObjectResponseCommand");
de_CommandError = /* @__PURE__ */ __name(async (output, context2) => {
const parsedOutput = {
...output,
body: await parseXmlErrorBody(output.body, context2)
};
const errorCode = loadRestXmlErrorCode(output, parsedOutput.body);
switch (errorCode) {
case "NoSuchUpload":
case "com.amazonaws.s3#NoSuchUpload":
throw await de_NoSuchUploadRes(parsedOutput, context2);
case "ObjectNotInActiveTierError":
case "com.amazonaws.s3#ObjectNotInActiveTierError":
throw await de_ObjectNotInActiveTierErrorRes(parsedOutput, context2);
case "BucketAlreadyExists":
case "com.amazonaws.s3#BucketAlreadyExists":
throw await de_BucketAlreadyExistsRes(parsedOutput, context2);
case "BucketAlreadyOwnedByYou":
case "com.amazonaws.s3#BucketAlreadyOwnedByYou":
throw await de_BucketAlreadyOwnedByYouRes(parsedOutput, context2);
case "NoSuchBucket":
case "com.amazonaws.s3#NoSuchBucket":
throw await de_NoSuchBucketRes(parsedOutput, context2);
case "InvalidObjectState":
case "com.amazonaws.s3#InvalidObjectState":
throw await de_InvalidObjectStateRes(parsedOutput, context2);
case "NoSuchKey":
case "com.amazonaws.s3#NoSuchKey":
throw await de_NoSuchKeyRes(parsedOutput, context2);
case "NotFound":
case "com.amazonaws.s3#NotFound":
throw await de_NotFoundRes(parsedOutput, context2);
case "EncryptionTypeMismatch":
case "com.amazonaws.s3#EncryptionTypeMismatch":
throw await de_EncryptionTypeMismatchRes(parsedOutput, context2);
case "InvalidRequest":
case "com.amazonaws.s3#InvalidRequest":
throw await de_InvalidRequestRes(parsedOutput, context2);
case "InvalidWriteOffset":
case "com.amazonaws.s3#InvalidWriteOffset":
throw await de_InvalidWriteOffsetRes(parsedOutput, context2);
case "TooManyParts":
case "com.amazonaws.s3#TooManyParts":
throw await de_TooManyPartsRes(parsedOutput, context2);
case "ObjectAlreadyInActiveTierError":
case "com.amazonaws.s3#ObjectAlreadyInActiveTierError":
throw await de_ObjectAlreadyInActiveTierErrorRes(parsedOutput, context2);
default:
const parsedBody = parsedOutput.body;
return throwDefaultError2({
output,
parsedBody,
errorCode
});
}
}, "de_CommandError");
throwDefaultError2 = withBaseException(S3ServiceException);
de_BucketAlreadyExistsRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new BucketAlreadyExists({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_BucketAlreadyExistsRes");
de_BucketAlreadyOwnedByYouRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new BucketAlreadyOwnedByYou({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_BucketAlreadyOwnedByYouRes");
de_EncryptionTypeMismatchRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new EncryptionTypeMismatch({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_EncryptionTypeMismatchRes");
de_InvalidObjectStateRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
if (data[_AT] != null) {
contents[_AT] = expectString(data[_AT]);
}
if (data[_SC] != null) {
contents[_SC] = expectString(data[_SC]);
}
const exception = new InvalidObjectState({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidObjectStateRes");
de_InvalidRequestRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new InvalidRequest({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidRequestRes");
de_InvalidWriteOffsetRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new InvalidWriteOffset({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidWriteOffsetRes");
de_NoSuchBucketRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new NoSuchBucket({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_NoSuchBucketRes");
de_NoSuchKeyRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new NoSuchKey({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_NoSuchKeyRes");
de_NoSuchUploadRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new NoSuchUpload({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_NoSuchUploadRes");
de_NotFoundRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new NotFound({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_NotFoundRes");
de_ObjectAlreadyInActiveTierErrorRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new ObjectAlreadyInActiveTierError({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_ObjectAlreadyInActiveTierErrorRes");
de_ObjectNotInActiveTierErrorRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new ObjectNotInActiveTierError({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_ObjectNotInActiveTierErrorRes");
de_TooManyPartsRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const exception = new TooManyParts({
$metadata: deserializeMetadata2(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_TooManyPartsRes");
de_SelectObjectContentEventStream = /* @__PURE__ */ __name((output, context2) => {
return context2.eventStreamMarshaller.deserialize(output, async (event) => {
if (event["Records"] != null) {
return {
Records: await de_RecordsEvent_event(event["Records"], context2)
};
}
if (event["Stats"] != null) {
return {
Stats: await de_StatsEvent_event(event["Stats"], context2)
};
}
if (event["Progress"] != null) {
return {
Progress: await de_ProgressEvent_event(event["Progress"], context2)
};
}
if (event["Cont"] != null) {
return {
Cont: await de_ContinuationEvent_event(event["Cont"], context2)
};
}
if (event["End"] != null) {
return {
End: await de_EndEvent_event(event["End"], context2)
};
}
return { $unknown: output };
});
}, "de_SelectObjectContentEventStream");
de_ContinuationEvent_event = /* @__PURE__ */ __name(async (output, context2) => {
const contents = {};
const data = await parseXmlBody(output.body, context2);
Object.assign(contents, de_ContinuationEvent(data, context2));
return contents;
}, "de_ContinuationEvent_event");
de_EndEvent_event = /* @__PURE__ */ __name(async (output, context2) => {
const contents = {};
const data = await parseXmlBody(output.body, context2);
Object.assign(contents, de_EndEvent(data, context2));
return contents;
}, "de_EndEvent_event");
de_ProgressEvent_event = /* @__PURE__ */ __name(async (output, context2) => {
const contents = {};
const data = await parseXmlBody(output.body, context2);
contents.Details = de_Progress(data, context2);
return contents;
}, "de_ProgressEvent_event");
de_RecordsEvent_event = /* @__PURE__ */ __name(async (output, context2) => {
const contents = {};
contents.Payload = output.body;
return contents;
}, "de_RecordsEvent_event");
de_StatsEvent_event = /* @__PURE__ */ __name(async (output, context2) => {
const contents = {};
const data = await parseXmlBody(output.body, context2);
contents.Details = de_Stats(data, context2);
return contents;
}, "de_StatsEvent_event");
se_AbortIncompleteMultipartUpload = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_AIMU);
if (input[_DAI] != null) {
bn2.c(XmlNode.of(_DAI, String(input[_DAI])).n(_DAI));
}
return bn2;
}, "se_AbortIncompleteMultipartUpload");
se_AccelerateConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ACc);
if (input[_S] != null) {
bn2.c(XmlNode.of(_BAS, input[_S]).n(_S));
}
return bn2;
}, "se_AccelerateConfiguration");
se_AccessControlPolicy = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ACP);
bn2.lc(input, "Grants", "AccessControlList", () => se_Grants(input[_Gr], context2));
if (input[_O] != null) {
bn2.c(se_Owner(input[_O], context2).n(_O));
}
return bn2;
}, "se_AccessControlPolicy");
se_AccessControlTranslation = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ACT);
if (input[_O] != null) {
bn2.c(XmlNode.of(_OOw, input[_O]).n(_O));
}
return bn2;
}, "se_AccessControlTranslation");
se_AllowedHeaders = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = XmlNode.of(_AH, entry);
return n6.n(_me);
});
}, "se_AllowedHeaders");
se_AllowedMethods = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = XmlNode.of(_AM, entry);
return n6.n(_me);
});
}, "se_AllowedMethods");
se_AllowedOrigins = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = XmlNode.of(_AO, entry);
return n6.n(_me);
});
}, "se_AllowedOrigins");
se_AnalyticsAndOperator = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_AAO);
bn2.cc(input, _P);
bn2.l(input, "Tags", "Tag", () => se_TagSet(input[_Tag], context2));
return bn2;
}, "se_AnalyticsAndOperator");
se_AnalyticsConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_AC);
if (input[_I] != null) {
bn2.c(XmlNode.of(_AI, input[_I]).n(_I));
}
if (input[_F] != null) {
bn2.c(se_AnalyticsFilter(input[_F], context2).n(_F));
}
if (input[_SCA] != null) {
bn2.c(se_StorageClassAnalysis(input[_SCA], context2).n(_SCA));
}
return bn2;
}, "se_AnalyticsConfiguration");
se_AnalyticsExportDestination = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_AED);
if (input[_SBD] != null) {
bn2.c(se_AnalyticsS3BucketDestination(input[_SBD], context2).n(_SBD));
}
return bn2;
}, "se_AnalyticsExportDestination");
se_AnalyticsFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_AF);
AnalyticsFilter.visit(input, {
Prefix: /* @__PURE__ */ __name((value) => {
if (input[_P] != null) {
bn2.c(XmlNode.of(_P, value).n(_P));
}
}, "Prefix"),
Tag: /* @__PURE__ */ __name((value) => {
if (input[_Ta] != null) {
bn2.c(se_Tag(value, context2).n(_Ta));
}
}, "Tag"),
And: /* @__PURE__ */ __name((value) => {
if (input[_A] != null) {
bn2.c(se_AnalyticsAndOperator(value, context2).n(_A));
}
}, "And"),
_: /* @__PURE__ */ __name((name2, value) => {
if (!(value instanceof XmlNode || value instanceof XmlText)) {
throw new Error("Unable to serialize unknown union members in XML.");
}
bn2.c(new XmlNode(name2).c(value));
}, "_")
});
return bn2;
}, "se_AnalyticsFilter");
se_AnalyticsS3BucketDestination = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ASBD);
if (input[_Fo] != null) {
bn2.c(XmlNode.of(_ASEFF, input[_Fo]).n(_Fo));
}
if (input[_BAI] != null) {
bn2.c(XmlNode.of(_AIc, input[_BAI]).n(_BAI));
}
if (input[_B] != null) {
bn2.c(XmlNode.of(_BN, input[_B]).n(_B));
}
bn2.cc(input, _P);
return bn2;
}, "se_AnalyticsS3BucketDestination");
se_BucketInfo = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_BI);
bn2.cc(input, _DR);
if (input[_Ty] != null) {
bn2.c(XmlNode.of(_BT, input[_Ty]).n(_Ty));
}
return bn2;
}, "se_BucketInfo");
se_BucketLifecycleConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_BLC);
bn2.l(input, "Rules", "Rule", () => se_LifecycleRules(input[_Rul], context2));
return bn2;
}, "se_BucketLifecycleConfiguration");
se_BucketLoggingStatus = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_BLS);
if (input[_LE] != null) {
bn2.c(se_LoggingEnabled(input[_LE], context2).n(_LE));
}
return bn2;
}, "se_BucketLoggingStatus");
se_CompletedMultipartUpload = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CMU);
bn2.l(input, "Parts", "Part", () => se_CompletedPartList(input[_Part], context2));
return bn2;
}, "se_CompletedMultipartUpload");
se_CompletedPart = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CPo);
bn2.cc(input, _ETa);
bn2.cc(input, _CCRC);
bn2.cc(input, _CCRCC);
bn2.cc(input, _CSHA);
bn2.cc(input, _CSHAh);
if (input[_PN] != null) {
bn2.c(XmlNode.of(_PN, String(input[_PN])).n(_PN));
}
return bn2;
}, "se_CompletedPart");
se_CompletedPartList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_CompletedPart(entry, context2);
return n6.n(_me);
});
}, "se_CompletedPartList");
se_Condition = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Con);
bn2.cc(input, _HECRE);
bn2.cc(input, _KPE);
return bn2;
}, "se_Condition");
se_CORSConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CORSC);
bn2.l(input, "CORSRules", "CORSRule", () => se_CORSRules(input[_CORSRu], context2));
return bn2;
}, "se_CORSConfiguration");
se_CORSRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CORSR);
bn2.cc(input, _ID_);
bn2.l(input, "AllowedHeaders", "AllowedHeader", () => se_AllowedHeaders(input[_AHl], context2));
bn2.l(input, "AllowedMethods", "AllowedMethod", () => se_AllowedMethods(input[_AMl], context2));
bn2.l(input, "AllowedOrigins", "AllowedOrigin", () => se_AllowedOrigins(input[_AOl], context2));
bn2.l(input, "ExposeHeaders", "ExposeHeader", () => se_ExposeHeaders(input[_EH], context2));
if (input[_MAS] != null) {
bn2.c(XmlNode.of(_MAS, String(input[_MAS])).n(_MAS));
}
return bn2;
}, "se_CORSRule");
se_CORSRules = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_CORSRule(entry, context2);
return n6.n(_me);
});
}, "se_CORSRules");
se_CreateBucketConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CBC);
if (input[_LC] != null) {
bn2.c(XmlNode.of(_BLCu, input[_LC]).n(_LC));
}
if (input[_L] != null) {
bn2.c(se_LocationInfo(input[_L], context2).n(_L));
}
if (input[_B] != null) {
bn2.c(se_BucketInfo(input[_B], context2).n(_B));
}
return bn2;
}, "se_CreateBucketConfiguration");
se_CSVInput = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CSVIn);
bn2.cc(input, _FHI);
bn2.cc(input, _Com);
bn2.cc(input, _QEC);
bn2.cc(input, _RD);
bn2.cc(input, _FD);
bn2.cc(input, _QCuo);
if (input[_AQRD] != null) {
bn2.c(XmlNode.of(_AQRD, String(input[_AQRD])).n(_AQRD));
}
return bn2;
}, "se_CSVInput");
se_CSVOutput = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_CSVO);
bn2.cc(input, _QF);
bn2.cc(input, _QEC);
bn2.cc(input, _RD);
bn2.cc(input, _FD);
bn2.cc(input, _QCuo);
return bn2;
}, "se_CSVOutput");
se_DefaultRetention = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_DRe);
if (input[_Mo] != null) {
bn2.c(XmlNode.of(_OLRM, input[_Mo]).n(_Mo));
}
if (input[_Da] != null) {
bn2.c(XmlNode.of(_Da, String(input[_Da])).n(_Da));
}
if (input[_Y] != null) {
bn2.c(XmlNode.of(_Y, String(input[_Y])).n(_Y));
}
return bn2;
}, "se_DefaultRetention");
se_Delete = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Del);
bn2.l(input, "Objects", "Object", () => se_ObjectIdentifierList(input[_Ob], context2));
if (input[_Q] != null) {
bn2.c(XmlNode.of(_Q, String(input[_Q])).n(_Q));
}
return bn2;
}, "se_Delete");
se_DeleteMarkerReplication = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_DMR);
if (input[_S] != null) {
bn2.c(XmlNode.of(_DMRS, input[_S]).n(_S));
}
return bn2;
}, "se_DeleteMarkerReplication");
se_Destination = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Des);
if (input[_B] != null) {
bn2.c(XmlNode.of(_BN, input[_B]).n(_B));
}
if (input[_Ac] != null) {
bn2.c(XmlNode.of(_AIc, input[_Ac]).n(_Ac));
}
bn2.cc(input, _SC);
if (input[_ACT] != null) {
bn2.c(se_AccessControlTranslation(input[_ACT], context2).n(_ACT));
}
if (input[_ECn] != null) {
bn2.c(se_EncryptionConfiguration(input[_ECn], context2).n(_ECn));
}
if (input[_RTe] != null) {
bn2.c(se_ReplicationTime(input[_RTe], context2).n(_RTe));
}
if (input[_Me] != null) {
bn2.c(se_Metrics(input[_Me], context2).n(_Me));
}
return bn2;
}, "se_Destination");
se_Encryption = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_En);
if (input[_ETn] != null) {
bn2.c(XmlNode.of(_SSE, input[_ETn]).n(_ETn));
}
if (input[_KMSKI] != null) {
bn2.c(XmlNode.of(_SSEKMSKI, input[_KMSKI]).n(_KMSKI));
}
bn2.cc(input, _KMSC);
return bn2;
}, "se_Encryption");
se_EncryptionConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ECn);
bn2.cc(input, _RKKID);
return bn2;
}, "se_EncryptionConfiguration");
se_ErrorDocument = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ED);
if (input[_K] != null) {
bn2.c(XmlNode.of(_OK, input[_K]).n(_K));
}
return bn2;
}, "se_ErrorDocument");
se_EventBridgeConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_EBC);
return bn2;
}, "se_EventBridgeConfiguration");
se_EventList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = XmlNode.of(_Ev, entry);
return n6.n(_me);
});
}, "se_EventList");
se_ExistingObjectReplication = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_EOR);
if (input[_S] != null) {
bn2.c(XmlNode.of(_EORS, input[_S]).n(_S));
}
return bn2;
}, "se_ExistingObjectReplication");
se_ExposeHeaders = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = XmlNode.of(_EHx, entry);
return n6.n(_me);
});
}, "se_ExposeHeaders");
se_FilterRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_FR);
if (input[_N] != null) {
bn2.c(XmlNode.of(_FRN, input[_N]).n(_N));
}
if (input[_Va] != null) {
bn2.c(XmlNode.of(_FRV, input[_Va]).n(_Va));
}
return bn2;
}, "se_FilterRule");
se_FilterRuleList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_FilterRule(entry, context2);
return n6.n(_me);
});
}, "se_FilterRuleList");
se_GlacierJobParameters = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_GJP);
bn2.cc(input, _Ti);
return bn2;
}, "se_GlacierJobParameters");
se_Grant = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_G);
if (input[_Gra] != null) {
const n6 = se_Grantee(input[_Gra], context2).n(_Gra);
n6.a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
bn2.c(n6);
}
bn2.cc(input, _Pe);
return bn2;
}, "se_Grant");
se_Grantee = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Gra);
bn2.cc(input, _DN);
bn2.cc(input, _EA);
bn2.cc(input, _ID_);
bn2.cc(input, _URI);
bn2.a("xsi:type", input[_Ty]);
return bn2;
}, "se_Grantee");
se_Grants = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_Grant(entry, context2);
return n6.n(_G);
});
}, "se_Grants");
se_IndexDocument = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ID);
bn2.cc(input, _Su);
return bn2;
}, "se_IndexDocument");
se_InputSerialization = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_IS);
if (input[_CSV] != null) {
bn2.c(se_CSVInput(input[_CSV], context2).n(_CSV));
}
bn2.cc(input, _CTom);
if (input[_JSON] != null) {
bn2.c(se_JSONInput(input[_JSON], context2).n(_JSON));
}
if (input[_Parq] != null) {
bn2.c(se_ParquetInput(input[_Parq], context2).n(_Parq));
}
return bn2;
}, "se_InputSerialization");
se_IntelligentTieringAndOperator = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ITAO);
bn2.cc(input, _P);
bn2.l(input, "Tags", "Tag", () => se_TagSet(input[_Tag], context2));
return bn2;
}, "se_IntelligentTieringAndOperator");
se_IntelligentTieringConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ITC);
if (input[_I] != null) {
bn2.c(XmlNode.of(_ITI, input[_I]).n(_I));
}
if (input[_F] != null) {
bn2.c(se_IntelligentTieringFilter(input[_F], context2).n(_F));
}
if (input[_S] != null) {
bn2.c(XmlNode.of(_ITS, input[_S]).n(_S));
}
bn2.l(input, "Tierings", "Tiering", () => se_TieringList(input[_Tie], context2));
return bn2;
}, "se_IntelligentTieringConfiguration");
se_IntelligentTieringFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ITF);
bn2.cc(input, _P);
if (input[_Ta] != null) {
bn2.c(se_Tag(input[_Ta], context2).n(_Ta));
}
if (input[_A] != null) {
bn2.c(se_IntelligentTieringAndOperator(input[_A], context2).n(_A));
}
return bn2;
}, "se_IntelligentTieringFilter");
se_InventoryConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_IC);
if (input[_Des] != null) {
bn2.c(se_InventoryDestination(input[_Des], context2).n(_Des));
}
if (input[_IE] != null) {
bn2.c(XmlNode.of(_IE, String(input[_IE])).n(_IE));
}
if (input[_F] != null) {
bn2.c(se_InventoryFilter(input[_F], context2).n(_F));
}
if (input[_I] != null) {
bn2.c(XmlNode.of(_II, input[_I]).n(_I));
}
if (input[_IOV] != null) {
bn2.c(XmlNode.of(_IIOV, input[_IOV]).n(_IOV));
}
bn2.lc(input, "OptionalFields", "OptionalFields", () => se_InventoryOptionalFields(input[_OF], context2));
if (input[_Sc] != null) {
bn2.c(se_InventorySchedule(input[_Sc], context2).n(_Sc));
}
return bn2;
}, "se_InventoryConfiguration");
se_InventoryDestination = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_IDn);
if (input[_SBD] != null) {
bn2.c(se_InventoryS3BucketDestination(input[_SBD], context2).n(_SBD));
}
return bn2;
}, "se_InventoryDestination");
se_InventoryEncryption = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_IEn);
if (input[_SSES] != null) {
bn2.c(se_SSES3(input[_SSES], context2).n(_SS));
}
if (input[_SSEKMS] != null) {
bn2.c(se_SSEKMS(input[_SSEKMS], context2).n(_SK));
}
return bn2;
}, "se_InventoryEncryption");
se_InventoryFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_IF);
bn2.cc(input, _P);
return bn2;
}, "se_InventoryFilter");
se_InventoryOptionalFields = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = XmlNode.of(_IOF, entry);
return n6.n(_Fi);
});
}, "se_InventoryOptionalFields");
se_InventoryS3BucketDestination = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ISBD);
bn2.cc(input, _AIc);
if (input[_B] != null) {
bn2.c(XmlNode.of(_BN, input[_B]).n(_B));
}
if (input[_Fo] != null) {
bn2.c(XmlNode.of(_IFn, input[_Fo]).n(_Fo));
}
bn2.cc(input, _P);
if (input[_En] != null) {
bn2.c(se_InventoryEncryption(input[_En], context2).n(_En));
}
return bn2;
}, "se_InventoryS3BucketDestination");
se_InventorySchedule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ISn);
if (input[_Fr] != null) {
bn2.c(XmlNode.of(_IFnv, input[_Fr]).n(_Fr));
}
return bn2;
}, "se_InventorySchedule");
se_JSONInput = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_JSONI);
if (input[_Ty] != null) {
bn2.c(XmlNode.of(_JSONT, input[_Ty]).n(_Ty));
}
return bn2;
}, "se_JSONInput");
se_JSONOutput = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_JSONO);
bn2.cc(input, _RD);
return bn2;
}, "se_JSONOutput");
se_LambdaFunctionConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LFCa);
if (input[_I] != null) {
bn2.c(XmlNode.of(_NI, input[_I]).n(_I));
}
if (input[_LFA] != null) {
bn2.c(XmlNode.of(_LFA, input[_LFA]).n(_CF));
}
bn2.l(input, "Events", "Event", () => se_EventList(input[_Eve], context2));
if (input[_F] != null) {
bn2.c(se_NotificationConfigurationFilter(input[_F], context2).n(_F));
}
return bn2;
}, "se_LambdaFunctionConfiguration");
se_LambdaFunctionConfigurationList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_LambdaFunctionConfiguration(entry, context2);
return n6.n(_me);
});
}, "se_LambdaFunctionConfigurationList");
se_LifecycleExpiration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LEi);
if (input[_Dat] != null) {
bn2.c(XmlNode.of(_Dat, serializeDateTime(input[_Dat]).toString()).n(_Dat));
}
if (input[_Da] != null) {
bn2.c(XmlNode.of(_Da, String(input[_Da])).n(_Da));
}
if (input[_EODM] != null) {
bn2.c(XmlNode.of(_EODM, String(input[_EODM])).n(_EODM));
}
return bn2;
}, "se_LifecycleExpiration");
se_LifecycleRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LR);
if (input[_Exp] != null) {
bn2.c(se_LifecycleExpiration(input[_Exp], context2).n(_Exp));
}
bn2.cc(input, _ID_);
bn2.cc(input, _P);
if (input[_F] != null) {
bn2.c(se_LifecycleRuleFilter(input[_F], context2).n(_F));
}
if (input[_S] != null) {
bn2.c(XmlNode.of(_ESx, input[_S]).n(_S));
}
bn2.l(input, "Transitions", "Transition", () => se_TransitionList(input[_Tr], context2));
bn2.l(input, "NoncurrentVersionTransitions", "NoncurrentVersionTransition", () => se_NoncurrentVersionTransitionList(input[_NVT], context2));
if (input[_NVE] != null) {
bn2.c(se_NoncurrentVersionExpiration(input[_NVE], context2).n(_NVE));
}
if (input[_AIMU] != null) {
bn2.c(se_AbortIncompleteMultipartUpload(input[_AIMU], context2).n(_AIMU));
}
return bn2;
}, "se_LifecycleRule");
se_LifecycleRuleAndOperator = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LRAO);
bn2.cc(input, _P);
bn2.l(input, "Tags", "Tag", () => se_TagSet(input[_Tag], context2));
if (input[_OSGT] != null) {
bn2.c(XmlNode.of(_OSGTB, String(input[_OSGT])).n(_OSGT));
}
if (input[_OSLT] != null) {
bn2.c(XmlNode.of(_OSLTB, String(input[_OSLT])).n(_OSLT));
}
return bn2;
}, "se_LifecycleRuleAndOperator");
se_LifecycleRuleFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LRF);
bn2.cc(input, _P);
if (input[_Ta] != null) {
bn2.c(se_Tag(input[_Ta], context2).n(_Ta));
}
if (input[_OSGT] != null) {
bn2.c(XmlNode.of(_OSGTB, String(input[_OSGT])).n(_OSGT));
}
if (input[_OSLT] != null) {
bn2.c(XmlNode.of(_OSLTB, String(input[_OSLT])).n(_OSLT));
}
if (input[_A] != null) {
bn2.c(se_LifecycleRuleAndOperator(input[_A], context2).n(_A));
}
return bn2;
}, "se_LifecycleRuleFilter");
se_LifecycleRules = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_LifecycleRule(entry, context2);
return n6.n(_me);
});
}, "se_LifecycleRules");
se_LocationInfo = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LI);
if (input[_Ty] != null) {
bn2.c(XmlNode.of(_LT, input[_Ty]).n(_Ty));
}
if (input[_N] != null) {
bn2.c(XmlNode.of(_LNAS, input[_N]).n(_N));
}
return bn2;
}, "se_LocationInfo");
se_LoggingEnabled = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_LE);
bn2.cc(input, _TB);
bn2.lc(input, "TargetGrants", "TargetGrants", () => se_TargetGrants(input[_TG], context2));
bn2.cc(input, _TP);
if (input[_TOKF] != null) {
bn2.c(se_TargetObjectKeyFormat(input[_TOKF], context2).n(_TOKF));
}
return bn2;
}, "se_LoggingEnabled");
se_MetadataEntry = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_ME);
if (input[_N] != null) {
bn2.c(XmlNode.of(_MKe, input[_N]).n(_N));
}
if (input[_Va] != null) {
bn2.c(XmlNode.of(_MV, input[_Va]).n(_Va));
}
return bn2;
}, "se_MetadataEntry");
se_MetadataTableConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_MTC);
if (input[_STD] != null) {
bn2.c(se_S3TablesDestination(input[_STD], context2).n(_STD));
}
return bn2;
}, "se_MetadataTableConfiguration");
se_Metrics = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Me);
if (input[_S] != null) {
bn2.c(XmlNode.of(_MS, input[_S]).n(_S));
}
if (input[_ETv] != null) {
bn2.c(se_ReplicationTimeValue(input[_ETv], context2).n(_ETv));
}
return bn2;
}, "se_Metrics");
se_MetricsAndOperator = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_MAO);
bn2.cc(input, _P);
bn2.l(input, "Tags", "Tag", () => se_TagSet(input[_Tag], context2));
bn2.cc(input, _APAc);
return bn2;
}, "se_MetricsAndOperator");
se_MetricsConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_MC);
if (input[_I] != null) {
bn2.c(XmlNode.of(_MI, input[_I]).n(_I));
}
if (input[_F] != null) {
bn2.c(se_MetricsFilter(input[_F], context2).n(_F));
}
return bn2;
}, "se_MetricsConfiguration");
se_MetricsFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_MF);
MetricsFilter.visit(input, {
Prefix: /* @__PURE__ */ __name((value) => {
if (input[_P] != null) {
bn2.c(XmlNode.of(_P, value).n(_P));
}
}, "Prefix"),
Tag: /* @__PURE__ */ __name((value) => {
if (input[_Ta] != null) {
bn2.c(se_Tag(value, context2).n(_Ta));
}
}, "Tag"),
AccessPointArn: /* @__PURE__ */ __name((value) => {
if (input[_APAc] != null) {
bn2.c(XmlNode.of(_APAc, value).n(_APAc));
}
}, "AccessPointArn"),
And: /* @__PURE__ */ __name((value) => {
if (input[_A] != null) {
bn2.c(se_MetricsAndOperator(value, context2).n(_A));
}
}, "And"),
_: /* @__PURE__ */ __name((name2, value) => {
if (!(value instanceof XmlNode || value instanceof XmlText)) {
throw new Error("Unable to serialize unknown union members in XML.");
}
bn2.c(new XmlNode(name2).c(value));
}, "_")
});
return bn2;
}, "se_MetricsFilter");
se_NoncurrentVersionExpiration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_NVE);
if (input[_ND] != null) {
bn2.c(XmlNode.of(_Da, String(input[_ND])).n(_ND));
}
if (input[_NNV] != null) {
bn2.c(XmlNode.of(_VC, String(input[_NNV])).n(_NNV));
}
return bn2;
}, "se_NoncurrentVersionExpiration");
se_NoncurrentVersionTransition = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_NVTo);
if (input[_ND] != null) {
bn2.c(XmlNode.of(_Da, String(input[_ND])).n(_ND));
}
if (input[_SC] != null) {
bn2.c(XmlNode.of(_TSC, input[_SC]).n(_SC));
}
if (input[_NNV] != null) {
bn2.c(XmlNode.of(_VC, String(input[_NNV])).n(_NNV));
}
return bn2;
}, "se_NoncurrentVersionTransition");
se_NoncurrentVersionTransitionList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_NoncurrentVersionTransition(entry, context2);
return n6.n(_me);
});
}, "se_NoncurrentVersionTransitionList");
se_NotificationConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_NC);
bn2.l(input, "TopicConfigurations", "TopicConfiguration", () => se_TopicConfigurationList(input[_TCop], context2));
bn2.l(input, "QueueConfigurations", "QueueConfiguration", () => se_QueueConfigurationList(input[_QCu], context2));
bn2.l(input, "LambdaFunctionConfigurations", "CloudFunctionConfiguration", () => se_LambdaFunctionConfigurationList(input[_LFC], context2));
if (input[_EBC] != null) {
bn2.c(se_EventBridgeConfiguration(input[_EBC], context2).n(_EBC));
}
return bn2;
}, "se_NotificationConfiguration");
se_NotificationConfigurationFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_NCF);
if (input[_K] != null) {
bn2.c(se_S3KeyFilter(input[_K], context2).n(_SKe));
}
return bn2;
}, "se_NotificationConfigurationFilter");
se_ObjectIdentifier = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OI);
if (input[_K] != null) {
bn2.c(XmlNode.of(_OK, input[_K]).n(_K));
}
if (input[_VI] != null) {
bn2.c(XmlNode.of(_OVI, input[_VI]).n(_VI));
}
bn2.cc(input, _ETa);
if (input[_LMT] != null) {
bn2.c(XmlNode.of(_LMT, dateToUtcString(input[_LMT]).toString()).n(_LMT));
}
if (input[_Si] != null) {
bn2.c(XmlNode.of(_Si, String(input[_Si])).n(_Si));
}
return bn2;
}, "se_ObjectIdentifier");
se_ObjectIdentifierList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_ObjectIdentifier(entry, context2);
return n6.n(_me);
});
}, "se_ObjectIdentifierList");
se_ObjectLockConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OLC);
bn2.cc(input, _OLE);
if (input[_Ru] != null) {
bn2.c(se_ObjectLockRule(input[_Ru], context2).n(_Ru));
}
return bn2;
}, "se_ObjectLockConfiguration");
se_ObjectLockLegalHold = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OLLH);
if (input[_S] != null) {
bn2.c(XmlNode.of(_OLLHS, input[_S]).n(_S));
}
return bn2;
}, "se_ObjectLockLegalHold");
se_ObjectLockRetention = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OLR);
if (input[_Mo] != null) {
bn2.c(XmlNode.of(_OLRM, input[_Mo]).n(_Mo));
}
if (input[_RUD] != null) {
bn2.c(XmlNode.of(_Dat, serializeDateTime(input[_RUD]).toString()).n(_RUD));
}
return bn2;
}, "se_ObjectLockRetention");
se_ObjectLockRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OLRb);
if (input[_DRe] != null) {
bn2.c(se_DefaultRetention(input[_DRe], context2).n(_DRe));
}
return bn2;
}, "se_ObjectLockRule");
se_OutputLocation = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OL);
if (input[_S_] != null) {
bn2.c(se_S3Location(input[_S_], context2).n(_S_));
}
return bn2;
}, "se_OutputLocation");
se_OutputSerialization = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OS);
if (input[_CSV] != null) {
bn2.c(se_CSVOutput(input[_CSV], context2).n(_CSV));
}
if (input[_JSON] != null) {
bn2.c(se_JSONOutput(input[_JSON], context2).n(_JSON));
}
return bn2;
}, "se_OutputSerialization");
se_Owner = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_O);
bn2.cc(input, _DN);
bn2.cc(input, _ID_);
return bn2;
}, "se_Owner");
se_OwnershipControls = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OC);
bn2.l(input, "Rules", "Rule", () => se_OwnershipControlsRules(input[_Rul], context2));
return bn2;
}, "se_OwnershipControls");
se_OwnershipControlsRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_OCR);
bn2.cc(input, _OO);
return bn2;
}, "se_OwnershipControlsRule");
se_OwnershipControlsRules = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_OwnershipControlsRule(entry, context2);
return n6.n(_me);
});
}, "se_OwnershipControlsRules");
se_ParquetInput = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_PI);
return bn2;
}, "se_ParquetInput");
se_PartitionedPrefix = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_PP);
bn2.cc(input, _PDS);
return bn2;
}, "se_PartitionedPrefix");
se_PublicAccessBlockConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_PABC);
if (input[_BPA] != null) {
bn2.c(XmlNode.of(_Se, String(input[_BPA])).n(_BPA));
}
if (input[_IPA] != null) {
bn2.c(XmlNode.of(_Se, String(input[_IPA])).n(_IPA));
}
if (input[_BPP] != null) {
bn2.c(XmlNode.of(_Se, String(input[_BPP])).n(_BPP));
}
if (input[_RPB] != null) {
bn2.c(XmlNode.of(_Se, String(input[_RPB])).n(_RPB));
}
return bn2;
}, "se_PublicAccessBlockConfiguration");
se_QueueConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_QC);
if (input[_I] != null) {
bn2.c(XmlNode.of(_NI, input[_I]).n(_I));
}
if (input[_QA] != null) {
bn2.c(XmlNode.of(_QA, input[_QA]).n(_Qu));
}
bn2.l(input, "Events", "Event", () => se_EventList(input[_Eve], context2));
if (input[_F] != null) {
bn2.c(se_NotificationConfigurationFilter(input[_F], context2).n(_F));
}
return bn2;
}, "se_QueueConfiguration");
se_QueueConfigurationList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_QueueConfiguration(entry, context2);
return n6.n(_me);
});
}, "se_QueueConfigurationList");
se_Redirect = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Red);
bn2.cc(input, _HN);
bn2.cc(input, _HRC);
bn2.cc(input, _Pr);
bn2.cc(input, _RKPW);
bn2.cc(input, _RKW);
return bn2;
}, "se_Redirect");
se_RedirectAllRequestsTo = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RART);
bn2.cc(input, _HN);
bn2.cc(input, _Pr);
return bn2;
}, "se_RedirectAllRequestsTo");
se_ReplicaModifications = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RM);
if (input[_S] != null) {
bn2.c(XmlNode.of(_RMS, input[_S]).n(_S));
}
return bn2;
}, "se_ReplicaModifications");
se_ReplicationConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RCe);
bn2.cc(input, _Ro);
bn2.l(input, "Rules", "Rule", () => se_ReplicationRules(input[_Rul], context2));
return bn2;
}, "se_ReplicationConfiguration");
se_ReplicationRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RRe);
bn2.cc(input, _ID_);
if (input[_Pri] != null) {
bn2.c(XmlNode.of(_Pri, String(input[_Pri])).n(_Pri));
}
bn2.cc(input, _P);
if (input[_F] != null) {
bn2.c(se_ReplicationRuleFilter(input[_F], context2).n(_F));
}
if (input[_S] != null) {
bn2.c(XmlNode.of(_RRS, input[_S]).n(_S));
}
if (input[_SSC] != null) {
bn2.c(se_SourceSelectionCriteria(input[_SSC], context2).n(_SSC));
}
if (input[_EOR] != null) {
bn2.c(se_ExistingObjectReplication(input[_EOR], context2).n(_EOR));
}
if (input[_Des] != null) {
bn2.c(se_Destination(input[_Des], context2).n(_Des));
}
if (input[_DMR] != null) {
bn2.c(se_DeleteMarkerReplication(input[_DMR], context2).n(_DMR));
}
return bn2;
}, "se_ReplicationRule");
se_ReplicationRuleAndOperator = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RRAO);
bn2.cc(input, _P);
bn2.l(input, "Tags", "Tag", () => se_TagSet(input[_Tag], context2));
return bn2;
}, "se_ReplicationRuleAndOperator");
se_ReplicationRuleFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RRF);
bn2.cc(input, _P);
if (input[_Ta] != null) {
bn2.c(se_Tag(input[_Ta], context2).n(_Ta));
}
if (input[_A] != null) {
bn2.c(se_ReplicationRuleAndOperator(input[_A], context2).n(_A));
}
return bn2;
}, "se_ReplicationRuleFilter");
se_ReplicationRules = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_ReplicationRule(entry, context2);
return n6.n(_me);
});
}, "se_ReplicationRules");
se_ReplicationTime = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RTe);
if (input[_S] != null) {
bn2.c(XmlNode.of(_RTS, input[_S]).n(_S));
}
if (input[_Tim] != null) {
bn2.c(se_ReplicationTimeValue(input[_Tim], context2).n(_Tim));
}
return bn2;
}, "se_ReplicationTime");
se_ReplicationTimeValue = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RTV);
if (input[_Mi] != null) {
bn2.c(XmlNode.of(_Mi, String(input[_Mi])).n(_Mi));
}
return bn2;
}, "se_ReplicationTimeValue");
se_RequestPaymentConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RPC);
bn2.cc(input, _Pa);
return bn2;
}, "se_RequestPaymentConfiguration");
se_RequestProgress = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RPe);
if (input[_Ena] != null) {
bn2.c(XmlNode.of(_ERP, String(input[_Ena])).n(_Ena));
}
return bn2;
}, "se_RequestProgress");
se_RestoreRequest = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RRes);
if (input[_Da] != null) {
bn2.c(XmlNode.of(_Da, String(input[_Da])).n(_Da));
}
if (input[_GJP] != null) {
bn2.c(se_GlacierJobParameters(input[_GJP], context2).n(_GJP));
}
if (input[_Ty] != null) {
bn2.c(XmlNode.of(_RRT, input[_Ty]).n(_Ty));
}
bn2.cc(input, _Ti);
bn2.cc(input, _Desc);
if (input[_SP] != null) {
bn2.c(se_SelectParameters(input[_SP], context2).n(_SP));
}
if (input[_OL] != null) {
bn2.c(se_OutputLocation(input[_OL], context2).n(_OL));
}
return bn2;
}, "se_RestoreRequest");
se_RoutingRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_RRou);
if (input[_Con] != null) {
bn2.c(se_Condition(input[_Con], context2).n(_Con));
}
if (input[_Red] != null) {
bn2.c(se_Redirect(input[_Red], context2).n(_Red));
}
return bn2;
}, "se_RoutingRule");
se_RoutingRules = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_RoutingRule(entry, context2);
return n6.n(_RRou);
});
}, "se_RoutingRules");
se_S3KeyFilter = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SKF);
bn2.l(input, "FilterRules", "FilterRule", () => se_FilterRuleList(input[_FRi], context2));
return bn2;
}, "se_S3KeyFilter");
se_S3Location = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SL);
bn2.cc(input, _BN);
if (input[_P] != null) {
bn2.c(XmlNode.of(_LP, input[_P]).n(_P));
}
if (input[_En] != null) {
bn2.c(se_Encryption(input[_En], context2).n(_En));
}
if (input[_CACL] != null) {
bn2.c(XmlNode.of(_OCACL, input[_CACL]).n(_CACL));
}
bn2.lc(input, "AccessControlList", "AccessControlList", () => se_Grants(input[_ACLc], context2));
if (input[_T] != null) {
bn2.c(se_Tagging(input[_T], context2).n(_T));
}
bn2.lc(input, "UserMetadata", "UserMetadata", () => se_UserMetadata(input[_UM], context2));
bn2.cc(input, _SC);
return bn2;
}, "se_S3Location");
se_S3TablesDestination = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_STD);
if (input[_TBA] != null) {
bn2.c(XmlNode.of(_STBA, input[_TBA]).n(_TBA));
}
if (input[_TN] != null) {
bn2.c(XmlNode.of(_STN, input[_TN]).n(_TN));
}
return bn2;
}, "se_S3TablesDestination");
se_ScanRange = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SR);
if (input[_St] != null) {
bn2.c(XmlNode.of(_St, String(input[_St])).n(_St));
}
if (input[_End] != null) {
bn2.c(XmlNode.of(_End, String(input[_End])).n(_End));
}
return bn2;
}, "se_ScanRange");
se_SelectParameters = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SP);
if (input[_IS] != null) {
bn2.c(se_InputSerialization(input[_IS], context2).n(_IS));
}
bn2.cc(input, _ETx);
bn2.cc(input, _Ex);
if (input[_OS] != null) {
bn2.c(se_OutputSerialization(input[_OS], context2).n(_OS));
}
return bn2;
}, "se_SelectParameters");
se_ServerSideEncryptionByDefault = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SSEBD);
if (input[_SSEA] != null) {
bn2.c(XmlNode.of(_SSE, input[_SSEA]).n(_SSEA));
}
if (input[_KMSMKID] != null) {
bn2.c(XmlNode.of(_SSEKMSKI, input[_KMSMKID]).n(_KMSMKID));
}
return bn2;
}, "se_ServerSideEncryptionByDefault");
se_ServerSideEncryptionConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SSEC);
bn2.l(input, "Rules", "Rule", () => se_ServerSideEncryptionRules(input[_Rul], context2));
return bn2;
}, "se_ServerSideEncryptionConfiguration");
se_ServerSideEncryptionRule = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SSER);
if (input[_ASSEBD] != null) {
bn2.c(se_ServerSideEncryptionByDefault(input[_ASSEBD], context2).n(_ASSEBD));
}
if (input[_BKE] != null) {
bn2.c(XmlNode.of(_BKE, String(input[_BKE])).n(_BKE));
}
return bn2;
}, "se_ServerSideEncryptionRule");
se_ServerSideEncryptionRules = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_ServerSideEncryptionRule(entry, context2);
return n6.n(_me);
});
}, "se_ServerSideEncryptionRules");
se_SimplePrefix = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SPi);
return bn2;
}, "se_SimplePrefix");
se_SourceSelectionCriteria = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SSC);
if (input[_SKEO] != null) {
bn2.c(se_SseKmsEncryptedObjects(input[_SKEO], context2).n(_SKEO));
}
if (input[_RM] != null) {
bn2.c(se_ReplicaModifications(input[_RM], context2).n(_RM));
}
return bn2;
}, "se_SourceSelectionCriteria");
se_SSEKMS = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SK);
if (input[_KI] != null) {
bn2.c(XmlNode.of(_SSEKMSKI, input[_KI]).n(_KI));
}
return bn2;
}, "se_SSEKMS");
se_SseKmsEncryptedObjects = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SKEO);
if (input[_S] != null) {
bn2.c(XmlNode.of(_SKEOS, input[_S]).n(_S));
}
return bn2;
}, "se_SseKmsEncryptedObjects");
se_SSES3 = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SS);
return bn2;
}, "se_SSES3");
se_StorageClassAnalysis = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SCA);
if (input[_DE] != null) {
bn2.c(se_StorageClassAnalysisDataExport(input[_DE], context2).n(_DE));
}
return bn2;
}, "se_StorageClassAnalysis");
se_StorageClassAnalysisDataExport = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_SCADE);
if (input[_OSV] != null) {
bn2.c(XmlNode.of(_SCASV, input[_OSV]).n(_OSV));
}
if (input[_Des] != null) {
bn2.c(se_AnalyticsExportDestination(input[_Des], context2).n(_Des));
}
return bn2;
}, "se_StorageClassAnalysisDataExport");
se_Tag = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Ta);
if (input[_K] != null) {
bn2.c(XmlNode.of(_OK, input[_K]).n(_K));
}
bn2.cc(input, _Va);
return bn2;
}, "se_Tag");
se_Tagging = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_T);
bn2.lc(input, "TagSet", "TagSet", () => se_TagSet(input[_TS], context2));
return bn2;
}, "se_Tagging");
se_TagSet = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_Tag(entry, context2);
return n6.n(_Ta);
});
}, "se_TagSet");
se_TargetGrant = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_TGa);
if (input[_Gra] != null) {
const n6 = se_Grantee(input[_Gra], context2).n(_Gra);
n6.a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
bn2.c(n6);
}
if (input[_Pe] != null) {
bn2.c(XmlNode.of(_BLP, input[_Pe]).n(_Pe));
}
return bn2;
}, "se_TargetGrant");
se_TargetGrants = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_TargetGrant(entry, context2);
return n6.n(_G);
});
}, "se_TargetGrants");
se_TargetObjectKeyFormat = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_TOKF);
if (input[_SPi] != null) {
bn2.c(se_SimplePrefix(input[_SPi], context2).n(_SPi));
}
if (input[_PP] != null) {
bn2.c(se_PartitionedPrefix(input[_PP], context2).n(_PP));
}
return bn2;
}, "se_TargetObjectKeyFormat");
se_Tiering = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Tier);
if (input[_Da] != null) {
bn2.c(XmlNode.of(_ITD, String(input[_Da])).n(_Da));
}
if (input[_AT] != null) {
bn2.c(XmlNode.of(_ITAT, input[_AT]).n(_AT));
}
return bn2;
}, "se_Tiering");
se_TieringList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_Tiering(entry, context2);
return n6.n(_me);
});
}, "se_TieringList");
se_TopicConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_TCo);
if (input[_I] != null) {
bn2.c(XmlNode.of(_NI, input[_I]).n(_I));
}
if (input[_TA] != null) {
bn2.c(XmlNode.of(_TA, input[_TA]).n(_Top));
}
bn2.l(input, "Events", "Event", () => se_EventList(input[_Eve], context2));
if (input[_F] != null) {
bn2.c(se_NotificationConfigurationFilter(input[_F], context2).n(_F));
}
return bn2;
}, "se_TopicConfiguration");
se_TopicConfigurationList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_TopicConfiguration(entry, context2);
return n6.n(_me);
});
}, "se_TopicConfigurationList");
se_Transition = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_Tra);
if (input[_Dat] != null) {
bn2.c(XmlNode.of(_Dat, serializeDateTime(input[_Dat]).toString()).n(_Dat));
}
if (input[_Da] != null) {
bn2.c(XmlNode.of(_Da, String(input[_Da])).n(_Da));
}
if (input[_SC] != null) {
bn2.c(XmlNode.of(_TSC, input[_SC]).n(_SC));
}
return bn2;
}, "se_Transition");
se_TransitionList = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_Transition(entry, context2);
return n6.n(_me);
});
}, "se_TransitionList");
se_UserMetadata = /* @__PURE__ */ __name((input, context2) => {
return input.filter((e7) => e7 != null).map((entry) => {
const n6 = se_MetadataEntry(entry, context2);
return n6.n(_ME);
});
}, "se_UserMetadata");
se_VersioningConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_VCe);
if (input[_MFAD] != null) {
bn2.c(XmlNode.of(_MFAD, input[_MFAD]).n(_MDf));
}
if (input[_S] != null) {
bn2.c(XmlNode.of(_BVS, input[_S]).n(_S));
}
return bn2;
}, "se_VersioningConfiguration");
se_WebsiteConfiguration = /* @__PURE__ */ __name((input, context2) => {
const bn2 = new XmlNode(_WC);
if (input[_ED] != null) {
bn2.c(se_ErrorDocument(input[_ED], context2).n(_ED));
}
if (input[_ID] != null) {
bn2.c(se_IndexDocument(input[_ID], context2).n(_ID));
}
if (input[_RART] != null) {
bn2.c(se_RedirectAllRequestsTo(input[_RART], context2).n(_RART));
}
bn2.lc(input, "RoutingRules", "RoutingRules", () => se_RoutingRules(input[_RRo], context2));
return bn2;
}, "se_WebsiteConfiguration");
de_AbortIncompleteMultipartUpload = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_DAI] != null) {
contents[_DAI] = strictParseInt32(output[_DAI]);
}
return contents;
}, "de_AbortIncompleteMultipartUpload");
de_AccessControlTranslation = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_O] != null) {
contents[_O] = expectString(output[_O]);
}
return contents;
}, "de_AccessControlTranslation");
de_AllowedHeaders = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_AllowedHeaders");
de_AllowedMethods = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_AllowedMethods");
de_AllowedOrigins = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_AllowedOrigins");
de_AnalyticsAndOperator = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output.Tag === "") {
contents[_Tag] = [];
} else if (output[_Ta] != null) {
contents[_Tag] = de_TagSet(getArrayIfSingleItem(output[_Ta]), context2);
}
return contents;
}, "de_AnalyticsAndOperator");
de_AnalyticsConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output.Filter === "") {
} else if (output[_F] != null) {
contents[_F] = de_AnalyticsFilter(expectUnion(output[_F]), context2);
}
if (output[_SCA] != null) {
contents[_SCA] = de_StorageClassAnalysis(output[_SCA], context2);
}
return contents;
}, "de_AnalyticsConfiguration");
de_AnalyticsConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_AnalyticsConfiguration(entry, context2);
});
}, "de_AnalyticsConfigurationList");
de_AnalyticsExportDestination = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SBD] != null) {
contents[_SBD] = de_AnalyticsS3BucketDestination(output[_SBD], context2);
}
return contents;
}, "de_AnalyticsExportDestination");
de_AnalyticsFilter = /* @__PURE__ */ __name((output, context2) => {
if (output[_P] != null) {
return {
Prefix: expectString(output[_P])
};
}
if (output[_Ta] != null) {
return {
Tag: de_Tag(output[_Ta], context2)
};
}
if (output[_A] != null) {
return {
And: de_AnalyticsAndOperator(output[_A], context2)
};
}
return { $unknown: Object.entries(output)[0] };
}, "de_AnalyticsFilter");
de_AnalyticsS3BucketDestination = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Fo] != null) {
contents[_Fo] = expectString(output[_Fo]);
}
if (output[_BAI] != null) {
contents[_BAI] = expectString(output[_BAI]);
}
if (output[_B] != null) {
contents[_B] = expectString(output[_B]);
}
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
return contents;
}, "de_AnalyticsS3BucketDestination");
de_Bucket = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_N] != null) {
contents[_N] = expectString(output[_N]);
}
if (output[_CDr] != null) {
contents[_CDr] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_CDr]));
}
if (output[_BR] != null) {
contents[_BR] = expectString(output[_BR]);
}
return contents;
}, "de_Bucket");
de_Buckets = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_Bucket(entry, context2);
});
}, "de_Buckets");
de_Checksum = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_CCRC] != null) {
contents[_CCRC] = expectString(output[_CCRC]);
}
if (output[_CCRCC] != null) {
contents[_CCRCC] = expectString(output[_CCRCC]);
}
if (output[_CSHA] != null) {
contents[_CSHA] = expectString(output[_CSHA]);
}
if (output[_CSHAh] != null) {
contents[_CSHAh] = expectString(output[_CSHAh]);
}
return contents;
}, "de_Checksum");
de_ChecksumAlgorithmList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_ChecksumAlgorithmList");
de_CommonPrefix = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
return contents;
}, "de_CommonPrefix");
de_CommonPrefixList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_CommonPrefix(entry, context2);
});
}, "de_CommonPrefixList");
de_Condition = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_HECRE] != null) {
contents[_HECRE] = expectString(output[_HECRE]);
}
if (output[_KPE] != null) {
contents[_KPE] = expectString(output[_KPE]);
}
return contents;
}, "de_Condition");
de_ContinuationEvent = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
return contents;
}, "de_ContinuationEvent");
de_CopyObjectResult = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ETa] != null) {
contents[_ETa] = expectString(output[_ETa]);
}
if (output[_LM] != null) {
contents[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM]));
}
if (output[_CCRC] != null) {
contents[_CCRC] = expectString(output[_CCRC]);
}
if (output[_CCRCC] != null) {
contents[_CCRCC] = expectString(output[_CCRCC]);
}
if (output[_CSHA] != null) {
contents[_CSHA] = expectString(output[_CSHA]);
}
if (output[_CSHAh] != null) {
contents[_CSHAh] = expectString(output[_CSHAh]);
}
return contents;
}, "de_CopyObjectResult");
de_CopyPartResult = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ETa] != null) {
contents[_ETa] = expectString(output[_ETa]);
}
if (output[_LM] != null) {
contents[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM]));
}
if (output[_CCRC] != null) {
contents[_CCRC] = expectString(output[_CCRC]);
}
if (output[_CCRCC] != null) {
contents[_CCRCC] = expectString(output[_CCRCC]);
}
if (output[_CSHA] != null) {
contents[_CSHA] = expectString(output[_CSHA]);
}
if (output[_CSHAh] != null) {
contents[_CSHAh] = expectString(output[_CSHAh]);
}
return contents;
}, "de_CopyPartResult");
de_CORSRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ID_] != null) {
contents[_ID_] = expectString(output[_ID_]);
}
if (output.AllowedHeader === "") {
contents[_AHl] = [];
} else if (output[_AH] != null) {
contents[_AHl] = de_AllowedHeaders(getArrayIfSingleItem(output[_AH]), context2);
}
if (output.AllowedMethod === "") {
contents[_AMl] = [];
} else if (output[_AM] != null) {
contents[_AMl] = de_AllowedMethods(getArrayIfSingleItem(output[_AM]), context2);
}
if (output.AllowedOrigin === "") {
contents[_AOl] = [];
} else if (output[_AO] != null) {
contents[_AOl] = de_AllowedOrigins(getArrayIfSingleItem(output[_AO]), context2);
}
if (output.ExposeHeader === "") {
contents[_EH] = [];
} else if (output[_EHx] != null) {
contents[_EH] = de_ExposeHeaders(getArrayIfSingleItem(output[_EHx]), context2);
}
if (output[_MAS] != null) {
contents[_MAS] = strictParseInt32(output[_MAS]);
}
return contents;
}, "de_CORSRule");
de_CORSRules = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_CORSRule(entry, context2);
});
}, "de_CORSRules");
de_DefaultRetention = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Mo] != null) {
contents[_Mo] = expectString(output[_Mo]);
}
if (output[_Da] != null) {
contents[_Da] = strictParseInt32(output[_Da]);
}
if (output[_Y] != null) {
contents[_Y] = strictParseInt32(output[_Y]);
}
return contents;
}, "de_DefaultRetention");
de_DeletedObject = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_VI] != null) {
contents[_VI] = expectString(output[_VI]);
}
if (output[_DM] != null) {
contents[_DM] = parseBoolean(output[_DM]);
}
if (output[_DMVI] != null) {
contents[_DMVI] = expectString(output[_DMVI]);
}
return contents;
}, "de_DeletedObject");
de_DeletedObjects = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_DeletedObject(entry, context2);
});
}, "de_DeletedObjects");
de_DeleteMarkerEntry = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_O] != null) {
contents[_O] = de_Owner(output[_O], context2);
}
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_VI] != null) {
contents[_VI] = expectString(output[_VI]);
}
if (output[_IL] != null) {
contents[_IL] = parseBoolean(output[_IL]);
}
if (output[_LM] != null) {
contents[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM]));
}
return contents;
}, "de_DeleteMarkerEntry");
de_DeleteMarkerReplication = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
return contents;
}, "de_DeleteMarkerReplication");
de_DeleteMarkers = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_DeleteMarkerEntry(entry, context2);
});
}, "de_DeleteMarkers");
de_Destination = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_B] != null) {
contents[_B] = expectString(output[_B]);
}
if (output[_Ac] != null) {
contents[_Ac] = expectString(output[_Ac]);
}
if (output[_SC] != null) {
contents[_SC] = expectString(output[_SC]);
}
if (output[_ACT] != null) {
contents[_ACT] = de_AccessControlTranslation(output[_ACT], context2);
}
if (output[_ECn] != null) {
contents[_ECn] = de_EncryptionConfiguration(output[_ECn], context2);
}
if (output[_RTe] != null) {
contents[_RTe] = de_ReplicationTime(output[_RTe], context2);
}
if (output[_Me] != null) {
contents[_Me] = de_Metrics(output[_Me], context2);
}
return contents;
}, "de_Destination");
de_EncryptionConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_RKKID] != null) {
contents[_RKKID] = expectString(output[_RKKID]);
}
return contents;
}, "de_EncryptionConfiguration");
de_EndEvent = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
return contents;
}, "de_EndEvent");
de__Error = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_VI] != null) {
contents[_VI] = expectString(output[_VI]);
}
if (output[_Cod] != null) {
contents[_Cod] = expectString(output[_Cod]);
}
if (output[_Mes] != null) {
contents[_Mes] = expectString(output[_Mes]);
}
return contents;
}, "de__Error");
de_ErrorDetails = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_EC] != null) {
contents[_EC] = expectString(output[_EC]);
}
if (output[_EM] != null) {
contents[_EM] = expectString(output[_EM]);
}
return contents;
}, "de_ErrorDetails");
de_ErrorDocument = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
return contents;
}, "de_ErrorDocument");
de_Errors = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de__Error(entry, context2);
});
}, "de_Errors");
de_EventBridgeConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
return contents;
}, "de_EventBridgeConfiguration");
de_EventList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_EventList");
de_ExistingObjectReplication = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
return contents;
}, "de_ExistingObjectReplication");
de_ExposeHeaders = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_ExposeHeaders");
de_FilterRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_N] != null) {
contents[_N] = expectString(output[_N]);
}
if (output[_Va] != null) {
contents[_Va] = expectString(output[_Va]);
}
return contents;
}, "de_FilterRule");
de_FilterRuleList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_FilterRule(entry, context2);
});
}, "de_FilterRuleList");
de_GetBucketMetadataTableConfigurationResult = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_MTCR] != null) {
contents[_MTCR] = de_MetadataTableConfigurationResult(output[_MTCR], context2);
}
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
if (output[_Er] != null) {
contents[_Er] = de_ErrorDetails(output[_Er], context2);
}
return contents;
}, "de_GetBucketMetadataTableConfigurationResult");
de_GetObjectAttributesParts = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_PC] != null) {
contents[_TPC] = strictParseInt32(output[_PC]);
}
if (output[_PNM] != null) {
contents[_PNM] = expectString(output[_PNM]);
}
if (output[_NPNM] != null) {
contents[_NPNM] = expectString(output[_NPNM]);
}
if (output[_MP] != null) {
contents[_MP] = strictParseInt32(output[_MP]);
}
if (output[_IT] != null) {
contents[_IT] = parseBoolean(output[_IT]);
}
if (output.Part === "") {
contents[_Part] = [];
} else if (output[_Par] != null) {
contents[_Part] = de_PartsList(getArrayIfSingleItem(output[_Par]), context2);
}
return contents;
}, "de_GetObjectAttributesParts");
de_Grant = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Gra] != null) {
contents[_Gra] = de_Grantee(output[_Gra], context2);
}
if (output[_Pe] != null) {
contents[_Pe] = expectString(output[_Pe]);
}
return contents;
}, "de_Grant");
de_Grantee = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_DN] != null) {
contents[_DN] = expectString(output[_DN]);
}
if (output[_EA] != null) {
contents[_EA] = expectString(output[_EA]);
}
if (output[_ID_] != null) {
contents[_ID_] = expectString(output[_ID_]);
}
if (output[_URI] != null) {
contents[_URI] = expectString(output[_URI]);
}
if (output[_x] != null) {
contents[_Ty] = expectString(output[_x]);
}
return contents;
}, "de_Grantee");
de_Grants = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_Grant(entry, context2);
});
}, "de_Grants");
de_IndexDocument = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Su] != null) {
contents[_Su] = expectString(output[_Su]);
}
return contents;
}, "de_IndexDocument");
de_Initiator = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ID_] != null) {
contents[_ID_] = expectString(output[_ID_]);
}
if (output[_DN] != null) {
contents[_DN] = expectString(output[_DN]);
}
return contents;
}, "de_Initiator");
de_IntelligentTieringAndOperator = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output.Tag === "") {
contents[_Tag] = [];
} else if (output[_Ta] != null) {
contents[_Tag] = de_TagSet(getArrayIfSingleItem(output[_Ta]), context2);
}
return contents;
}, "de_IntelligentTieringAndOperator");
de_IntelligentTieringConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output[_F] != null) {
contents[_F] = de_IntelligentTieringFilter(output[_F], context2);
}
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
if (output.Tiering === "") {
contents[_Tie] = [];
} else if (output[_Tier] != null) {
contents[_Tie] = de_TieringList(getArrayIfSingleItem(output[_Tier]), context2);
}
return contents;
}, "de_IntelligentTieringConfiguration");
de_IntelligentTieringConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_IntelligentTieringConfiguration(entry, context2);
});
}, "de_IntelligentTieringConfigurationList");
de_IntelligentTieringFilter = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output[_Ta] != null) {
contents[_Ta] = de_Tag(output[_Ta], context2);
}
if (output[_A] != null) {
contents[_A] = de_IntelligentTieringAndOperator(output[_A], context2);
}
return contents;
}, "de_IntelligentTieringFilter");
de_InventoryConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Des] != null) {
contents[_Des] = de_InventoryDestination(output[_Des], context2);
}
if (output[_IE] != null) {
contents[_IE] = parseBoolean(output[_IE]);
}
if (output[_F] != null) {
contents[_F] = de_InventoryFilter(output[_F], context2);
}
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output[_IOV] != null) {
contents[_IOV] = expectString(output[_IOV]);
}
if (output.OptionalFields === "") {
contents[_OF] = [];
} else if (output[_OF] != null && output[_OF][_Fi] != null) {
contents[_OF] = de_InventoryOptionalFields(getArrayIfSingleItem(output[_OF][_Fi]), context2);
}
if (output[_Sc] != null) {
contents[_Sc] = de_InventorySchedule(output[_Sc], context2);
}
return contents;
}, "de_InventoryConfiguration");
de_InventoryConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_InventoryConfiguration(entry, context2);
});
}, "de_InventoryConfigurationList");
de_InventoryDestination = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SBD] != null) {
contents[_SBD] = de_InventoryS3BucketDestination(output[_SBD], context2);
}
return contents;
}, "de_InventoryDestination");
de_InventoryEncryption = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SS] != null) {
contents[_SSES] = de_SSES3(output[_SS], context2);
}
if (output[_SK] != null) {
contents[_SSEKMS] = de_SSEKMS(output[_SK], context2);
}
return contents;
}, "de_InventoryEncryption");
de_InventoryFilter = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
return contents;
}, "de_InventoryFilter");
de_InventoryOptionalFields = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return expectString(entry);
});
}, "de_InventoryOptionalFields");
de_InventoryS3BucketDestination = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_AIc] != null) {
contents[_AIc] = expectString(output[_AIc]);
}
if (output[_B] != null) {
contents[_B] = expectString(output[_B]);
}
if (output[_Fo] != null) {
contents[_Fo] = expectString(output[_Fo]);
}
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output[_En] != null) {
contents[_En] = de_InventoryEncryption(output[_En], context2);
}
return contents;
}, "de_InventoryS3BucketDestination");
de_InventorySchedule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Fr] != null) {
contents[_Fr] = expectString(output[_Fr]);
}
return contents;
}, "de_InventorySchedule");
de_LambdaFunctionConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output[_CF] != null) {
contents[_LFA] = expectString(output[_CF]);
}
if (output.Event === "") {
contents[_Eve] = [];
} else if (output[_Ev] != null) {
contents[_Eve] = de_EventList(getArrayIfSingleItem(output[_Ev]), context2);
}
if (output[_F] != null) {
contents[_F] = de_NotificationConfigurationFilter(output[_F], context2);
}
return contents;
}, "de_LambdaFunctionConfiguration");
de_LambdaFunctionConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_LambdaFunctionConfiguration(entry, context2);
});
}, "de_LambdaFunctionConfigurationList");
de_LifecycleExpiration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Dat] != null) {
contents[_Dat] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_Dat]));
}
if (output[_Da] != null) {
contents[_Da] = strictParseInt32(output[_Da]);
}
if (output[_EODM] != null) {
contents[_EODM] = parseBoolean(output[_EODM]);
}
return contents;
}, "de_LifecycleExpiration");
de_LifecycleRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Exp] != null) {
contents[_Exp] = de_LifecycleExpiration(output[_Exp], context2);
}
if (output[_ID_] != null) {
contents[_ID_] = expectString(output[_ID_]);
}
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output[_F] != null) {
contents[_F] = de_LifecycleRuleFilter(output[_F], context2);
}
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
if (output.Transition === "") {
contents[_Tr] = [];
} else if (output[_Tra] != null) {
contents[_Tr] = de_TransitionList(getArrayIfSingleItem(output[_Tra]), context2);
}
if (output.NoncurrentVersionTransition === "") {
contents[_NVT] = [];
} else if (output[_NVTo] != null) {
contents[_NVT] = de_NoncurrentVersionTransitionList(getArrayIfSingleItem(output[_NVTo]), context2);
}
if (output[_NVE] != null) {
contents[_NVE] = de_NoncurrentVersionExpiration(output[_NVE], context2);
}
if (output[_AIMU] != null) {
contents[_AIMU] = de_AbortIncompleteMultipartUpload(output[_AIMU], context2);
}
return contents;
}, "de_LifecycleRule");
de_LifecycleRuleAndOperator = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output.Tag === "") {
contents[_Tag] = [];
} else if (output[_Ta] != null) {
contents[_Tag] = de_TagSet(getArrayIfSingleItem(output[_Ta]), context2);
}
if (output[_OSGT] != null) {
contents[_OSGT] = strictParseLong(output[_OSGT]);
}
if (output[_OSLT] != null) {
contents[_OSLT] = strictParseLong(output[_OSLT]);
}
return contents;
}, "de_LifecycleRuleAndOperator");
de_LifecycleRuleFilter = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output[_Ta] != null) {
contents[_Ta] = de_Tag(output[_Ta], context2);
}
if (output[_OSGT] != null) {
contents[_OSGT] = strictParseLong(output[_OSGT]);
}
if (output[_OSLT] != null) {
contents[_OSLT] = strictParseLong(output[_OSLT]);
}
if (output[_A] != null) {
contents[_A] = de_LifecycleRuleAndOperator(output[_A], context2);
}
return contents;
}, "de_LifecycleRuleFilter");
de_LifecycleRules = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_LifecycleRule(entry, context2);
});
}, "de_LifecycleRules");
de_LoggingEnabled = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_TB] != null) {
contents[_TB] = expectString(output[_TB]);
}
if (output.TargetGrants === "") {
contents[_TG] = [];
} else if (output[_TG] != null && output[_TG][_G] != null) {
contents[_TG] = de_TargetGrants(getArrayIfSingleItem(output[_TG][_G]), context2);
}
if (output[_TP] != null) {
contents[_TP] = expectString(output[_TP]);
}
if (output[_TOKF] != null) {
contents[_TOKF] = de_TargetObjectKeyFormat(output[_TOKF], context2);
}
return contents;
}, "de_LoggingEnabled");
de_MetadataTableConfigurationResult = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_STDR] != null) {
contents[_STDR] = de_S3TablesDestinationResult(output[_STDR], context2);
}
return contents;
}, "de_MetadataTableConfigurationResult");
de_Metrics = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
if (output[_ETv] != null) {
contents[_ETv] = de_ReplicationTimeValue(output[_ETv], context2);
}
return contents;
}, "de_Metrics");
de_MetricsAndOperator = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output.Tag === "") {
contents[_Tag] = [];
} else if (output[_Ta] != null) {
contents[_Tag] = de_TagSet(getArrayIfSingleItem(output[_Ta]), context2);
}
if (output[_APAc] != null) {
contents[_APAc] = expectString(output[_APAc]);
}
return contents;
}, "de_MetricsAndOperator");
de_MetricsConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output.Filter === "") {
} else if (output[_F] != null) {
contents[_F] = de_MetricsFilter(expectUnion(output[_F]), context2);
}
return contents;
}, "de_MetricsConfiguration");
de_MetricsConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_MetricsConfiguration(entry, context2);
});
}, "de_MetricsConfigurationList");
de_MetricsFilter = /* @__PURE__ */ __name((output, context2) => {
if (output[_P] != null) {
return {
Prefix: expectString(output[_P])
};
}
if (output[_Ta] != null) {
return {
Tag: de_Tag(output[_Ta], context2)
};
}
if (output[_APAc] != null) {
return {
AccessPointArn: expectString(output[_APAc])
};
}
if (output[_A] != null) {
return {
And: de_MetricsAndOperator(output[_A], context2)
};
}
return { $unknown: Object.entries(output)[0] };
}, "de_MetricsFilter");
de_MultipartUpload = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_UI] != null) {
contents[_UI] = expectString(output[_UI]);
}
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_Ini] != null) {
contents[_Ini] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_Ini]));
}
if (output[_SC] != null) {
contents[_SC] = expectString(output[_SC]);
}
if (output[_O] != null) {
contents[_O] = de_Owner(output[_O], context2);
}
if (output[_In] != null) {
contents[_In] = de_Initiator(output[_In], context2);
}
if (output[_CA] != null) {
contents[_CA] = expectString(output[_CA]);
}
return contents;
}, "de_MultipartUpload");
de_MultipartUploadList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_MultipartUpload(entry, context2);
});
}, "de_MultipartUploadList");
de_NoncurrentVersionExpiration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ND] != null) {
contents[_ND] = strictParseInt32(output[_ND]);
}
if (output[_NNV] != null) {
contents[_NNV] = strictParseInt32(output[_NNV]);
}
return contents;
}, "de_NoncurrentVersionExpiration");
de_NoncurrentVersionTransition = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ND] != null) {
contents[_ND] = strictParseInt32(output[_ND]);
}
if (output[_SC] != null) {
contents[_SC] = expectString(output[_SC]);
}
if (output[_NNV] != null) {
contents[_NNV] = strictParseInt32(output[_NNV]);
}
return contents;
}, "de_NoncurrentVersionTransition");
de_NoncurrentVersionTransitionList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_NoncurrentVersionTransition(entry, context2);
});
}, "de_NoncurrentVersionTransitionList");
de_NotificationConfigurationFilter = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SKe] != null) {
contents[_K] = de_S3KeyFilter(output[_SKe], context2);
}
return contents;
}, "de_NotificationConfigurationFilter");
de__Object = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_LM] != null) {
contents[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM]));
}
if (output[_ETa] != null) {
contents[_ETa] = expectString(output[_ETa]);
}
if (output.ChecksumAlgorithm === "") {
contents[_CA] = [];
} else if (output[_CA] != null) {
contents[_CA] = de_ChecksumAlgorithmList(getArrayIfSingleItem(output[_CA]), context2);
}
if (output[_Si] != null) {
contents[_Si] = strictParseLong(output[_Si]);
}
if (output[_SC] != null) {
contents[_SC] = expectString(output[_SC]);
}
if (output[_O] != null) {
contents[_O] = de_Owner(output[_O], context2);
}
if (output[_RSe] != null) {
contents[_RSe] = de_RestoreStatus(output[_RSe], context2);
}
return contents;
}, "de__Object");
de_ObjectList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de__Object(entry, context2);
});
}, "de_ObjectList");
de_ObjectLockConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_OLE] != null) {
contents[_OLE] = expectString(output[_OLE]);
}
if (output[_Ru] != null) {
contents[_Ru] = de_ObjectLockRule(output[_Ru], context2);
}
return contents;
}, "de_ObjectLockConfiguration");
de_ObjectLockLegalHold = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
return contents;
}, "de_ObjectLockLegalHold");
de_ObjectLockRetention = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Mo] != null) {
contents[_Mo] = expectString(output[_Mo]);
}
if (output[_RUD] != null) {
contents[_RUD] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_RUD]));
}
return contents;
}, "de_ObjectLockRetention");
de_ObjectLockRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_DRe] != null) {
contents[_DRe] = de_DefaultRetention(output[_DRe], context2);
}
return contents;
}, "de_ObjectLockRule");
de_ObjectPart = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_PN] != null) {
contents[_PN] = strictParseInt32(output[_PN]);
}
if (output[_Si] != null) {
contents[_Si] = strictParseLong(output[_Si]);
}
if (output[_CCRC] != null) {
contents[_CCRC] = expectString(output[_CCRC]);
}
if (output[_CCRCC] != null) {
contents[_CCRCC] = expectString(output[_CCRCC]);
}
if (output[_CSHA] != null) {
contents[_CSHA] = expectString(output[_CSHA]);
}
if (output[_CSHAh] != null) {
contents[_CSHAh] = expectString(output[_CSHAh]);
}
return contents;
}, "de_ObjectPart");
de_ObjectVersion = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ETa] != null) {
contents[_ETa] = expectString(output[_ETa]);
}
if (output.ChecksumAlgorithm === "") {
contents[_CA] = [];
} else if (output[_CA] != null) {
contents[_CA] = de_ChecksumAlgorithmList(getArrayIfSingleItem(output[_CA]), context2);
}
if (output[_Si] != null) {
contents[_Si] = strictParseLong(output[_Si]);
}
if (output[_SC] != null) {
contents[_SC] = expectString(output[_SC]);
}
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_VI] != null) {
contents[_VI] = expectString(output[_VI]);
}
if (output[_IL] != null) {
contents[_IL] = parseBoolean(output[_IL]);
}
if (output[_LM] != null) {
contents[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM]));
}
if (output[_O] != null) {
contents[_O] = de_Owner(output[_O], context2);
}
if (output[_RSe] != null) {
contents[_RSe] = de_RestoreStatus(output[_RSe], context2);
}
return contents;
}, "de_ObjectVersion");
de_ObjectVersionList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_ObjectVersion(entry, context2);
});
}, "de_ObjectVersionList");
de_Owner = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_DN] != null) {
contents[_DN] = expectString(output[_DN]);
}
if (output[_ID_] != null) {
contents[_ID_] = expectString(output[_ID_]);
}
return contents;
}, "de_Owner");
de_OwnershipControls = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output.Rule === "") {
contents[_Rul] = [];
} else if (output[_Ru] != null) {
contents[_Rul] = de_OwnershipControlsRules(getArrayIfSingleItem(output[_Ru]), context2);
}
return contents;
}, "de_OwnershipControls");
de_OwnershipControlsRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_OO] != null) {
contents[_OO] = expectString(output[_OO]);
}
return contents;
}, "de_OwnershipControlsRule");
de_OwnershipControlsRules = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_OwnershipControlsRule(entry, context2);
});
}, "de_OwnershipControlsRules");
de_Part = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_PN] != null) {
contents[_PN] = strictParseInt32(output[_PN]);
}
if (output[_LM] != null) {
contents[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM]));
}
if (output[_ETa] != null) {
contents[_ETa] = expectString(output[_ETa]);
}
if (output[_Si] != null) {
contents[_Si] = strictParseLong(output[_Si]);
}
if (output[_CCRC] != null) {
contents[_CCRC] = expectString(output[_CCRC]);
}
if (output[_CCRCC] != null) {
contents[_CCRCC] = expectString(output[_CCRCC]);
}
if (output[_CSHA] != null) {
contents[_CSHA] = expectString(output[_CSHA]);
}
if (output[_CSHAh] != null) {
contents[_CSHAh] = expectString(output[_CSHAh]);
}
return contents;
}, "de_Part");
de_PartitionedPrefix = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_PDS] != null) {
contents[_PDS] = expectString(output[_PDS]);
}
return contents;
}, "de_PartitionedPrefix");
de_Parts = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_Part(entry, context2);
});
}, "de_Parts");
de_PartsList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_ObjectPart(entry, context2);
});
}, "de_PartsList");
de_PolicyStatus = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_IP] != null) {
contents[_IP] = parseBoolean(output[_IP]);
}
return contents;
}, "de_PolicyStatus");
de_Progress = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_BS] != null) {
contents[_BS] = strictParseLong(output[_BS]);
}
if (output[_BP] != null) {
contents[_BP] = strictParseLong(output[_BP]);
}
if (output[_BRy] != null) {
contents[_BRy] = strictParseLong(output[_BRy]);
}
return contents;
}, "de_Progress");
de_PublicAccessBlockConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_BPA] != null) {
contents[_BPA] = parseBoolean(output[_BPA]);
}
if (output[_IPA] != null) {
contents[_IPA] = parseBoolean(output[_IPA]);
}
if (output[_BPP] != null) {
contents[_BPP] = parseBoolean(output[_BPP]);
}
if (output[_RPB] != null) {
contents[_RPB] = parseBoolean(output[_RPB]);
}
return contents;
}, "de_PublicAccessBlockConfiguration");
de_QueueConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output[_Qu] != null) {
contents[_QA] = expectString(output[_Qu]);
}
if (output.Event === "") {
contents[_Eve] = [];
} else if (output[_Ev] != null) {
contents[_Eve] = de_EventList(getArrayIfSingleItem(output[_Ev]), context2);
}
if (output[_F] != null) {
contents[_F] = de_NotificationConfigurationFilter(output[_F], context2);
}
return contents;
}, "de_QueueConfiguration");
de_QueueConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_QueueConfiguration(entry, context2);
});
}, "de_QueueConfigurationList");
de_Redirect = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_HN] != null) {
contents[_HN] = expectString(output[_HN]);
}
if (output[_HRC] != null) {
contents[_HRC] = expectString(output[_HRC]);
}
if (output[_Pr] != null) {
contents[_Pr] = expectString(output[_Pr]);
}
if (output[_RKPW] != null) {
contents[_RKPW] = expectString(output[_RKPW]);
}
if (output[_RKW] != null) {
contents[_RKW] = expectString(output[_RKW]);
}
return contents;
}, "de_Redirect");
de_RedirectAllRequestsTo = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_HN] != null) {
contents[_HN] = expectString(output[_HN]);
}
if (output[_Pr] != null) {
contents[_Pr] = expectString(output[_Pr]);
}
return contents;
}, "de_RedirectAllRequestsTo");
de_ReplicaModifications = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
return contents;
}, "de_ReplicaModifications");
de_ReplicationConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Ro] != null) {
contents[_Ro] = expectString(output[_Ro]);
}
if (output.Rule === "") {
contents[_Rul] = [];
} else if (output[_Ru] != null) {
contents[_Rul] = de_ReplicationRules(getArrayIfSingleItem(output[_Ru]), context2);
}
return contents;
}, "de_ReplicationConfiguration");
de_ReplicationRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ID_] != null) {
contents[_ID_] = expectString(output[_ID_]);
}
if (output[_Pri] != null) {
contents[_Pri] = strictParseInt32(output[_Pri]);
}
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output[_F] != null) {
contents[_F] = de_ReplicationRuleFilter(output[_F], context2);
}
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
if (output[_SSC] != null) {
contents[_SSC] = de_SourceSelectionCriteria(output[_SSC], context2);
}
if (output[_EOR] != null) {
contents[_EOR] = de_ExistingObjectReplication(output[_EOR], context2);
}
if (output[_Des] != null) {
contents[_Des] = de_Destination(output[_Des], context2);
}
if (output[_DMR] != null) {
contents[_DMR] = de_DeleteMarkerReplication(output[_DMR], context2);
}
return contents;
}, "de_ReplicationRule");
de_ReplicationRuleAndOperator = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output.Tag === "") {
contents[_Tag] = [];
} else if (output[_Ta] != null) {
contents[_Tag] = de_TagSet(getArrayIfSingleItem(output[_Ta]), context2);
}
return contents;
}, "de_ReplicationRuleAndOperator");
de_ReplicationRuleFilter = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_P] != null) {
contents[_P] = expectString(output[_P]);
}
if (output[_Ta] != null) {
contents[_Ta] = de_Tag(output[_Ta], context2);
}
if (output[_A] != null) {
contents[_A] = de_ReplicationRuleAndOperator(output[_A], context2);
}
return contents;
}, "de_ReplicationRuleFilter");
de_ReplicationRules = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_ReplicationRule(entry, context2);
});
}, "de_ReplicationRules");
de_ReplicationTime = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
if (output[_Tim] != null) {
contents[_Tim] = de_ReplicationTimeValue(output[_Tim], context2);
}
return contents;
}, "de_ReplicationTime");
de_ReplicationTimeValue = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Mi] != null) {
contents[_Mi] = strictParseInt32(output[_Mi]);
}
return contents;
}, "de_ReplicationTimeValue");
de_RestoreStatus = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_IRIP] != null) {
contents[_IRIP] = parseBoolean(output[_IRIP]);
}
if (output[_RED] != null) {
contents[_RED] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_RED]));
}
return contents;
}, "de_RestoreStatus");
de_RoutingRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Con] != null) {
contents[_Con] = de_Condition(output[_Con], context2);
}
if (output[_Red] != null) {
contents[_Red] = de_Redirect(output[_Red], context2);
}
return contents;
}, "de_RoutingRule");
de_RoutingRules = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_RoutingRule(entry, context2);
});
}, "de_RoutingRules");
de_S3KeyFilter = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output.FilterRule === "") {
contents[_FRi] = [];
} else if (output[_FR] != null) {
contents[_FRi] = de_FilterRuleList(getArrayIfSingleItem(output[_FR]), context2);
}
return contents;
}, "de_S3KeyFilter");
de_S3TablesDestinationResult = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_TBA] != null) {
contents[_TBA] = expectString(output[_TBA]);
}
if (output[_TN] != null) {
contents[_TN] = expectString(output[_TN]);
}
if (output[_TAa] != null) {
contents[_TAa] = expectString(output[_TAa]);
}
if (output[_TNa] != null) {
contents[_TNa] = expectString(output[_TNa]);
}
return contents;
}, "de_S3TablesDestinationResult");
de_ServerSideEncryptionByDefault = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SSEA] != null) {
contents[_SSEA] = expectString(output[_SSEA]);
}
if (output[_KMSMKID] != null) {
contents[_KMSMKID] = expectString(output[_KMSMKID]);
}
return contents;
}, "de_ServerSideEncryptionByDefault");
de_ServerSideEncryptionConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output.Rule === "") {
contents[_Rul] = [];
} else if (output[_Ru] != null) {
contents[_Rul] = de_ServerSideEncryptionRules(getArrayIfSingleItem(output[_Ru]), context2);
}
return contents;
}, "de_ServerSideEncryptionConfiguration");
de_ServerSideEncryptionRule = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ASSEBD] != null) {
contents[_ASSEBD] = de_ServerSideEncryptionByDefault(output[_ASSEBD], context2);
}
if (output[_BKE] != null) {
contents[_BKE] = parseBoolean(output[_BKE]);
}
return contents;
}, "de_ServerSideEncryptionRule");
de_ServerSideEncryptionRules = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_ServerSideEncryptionRule(entry, context2);
});
}, "de_ServerSideEncryptionRules");
de_SessionCredentials = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_AKI] != null) {
contents[_AKI] = expectString(output[_AKI]);
}
if (output[_SAK] != null) {
contents[_SAK] = expectString(output[_SAK]);
}
if (output[_ST] != null) {
contents[_ST] = expectString(output[_ST]);
}
if (output[_Exp] != null) {
contents[_Exp] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_Exp]));
}
return contents;
}, "de_SessionCredentials");
de_SimplePrefix = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
return contents;
}, "de_SimplePrefix");
de_SourceSelectionCriteria = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SKEO] != null) {
contents[_SKEO] = de_SseKmsEncryptedObjects(output[_SKEO], context2);
}
if (output[_RM] != null) {
contents[_RM] = de_ReplicaModifications(output[_RM], context2);
}
return contents;
}, "de_SourceSelectionCriteria");
de_SSEKMS = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_KI] != null) {
contents[_KI] = expectString(output[_KI]);
}
return contents;
}, "de_SSEKMS");
de_SseKmsEncryptedObjects = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_S] != null) {
contents[_S] = expectString(output[_S]);
}
return contents;
}, "de_SseKmsEncryptedObjects");
de_SSES3 = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
return contents;
}, "de_SSES3");
de_Stats = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_BS] != null) {
contents[_BS] = strictParseLong(output[_BS]);
}
if (output[_BP] != null) {
contents[_BP] = strictParseLong(output[_BP]);
}
if (output[_BRy] != null) {
contents[_BRy] = strictParseLong(output[_BRy]);
}
return contents;
}, "de_Stats");
de_StorageClassAnalysis = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_DE] != null) {
contents[_DE] = de_StorageClassAnalysisDataExport(output[_DE], context2);
}
return contents;
}, "de_StorageClassAnalysis");
de_StorageClassAnalysisDataExport = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_OSV] != null) {
contents[_OSV] = expectString(output[_OSV]);
}
if (output[_Des] != null) {
contents[_Des] = de_AnalyticsExportDestination(output[_Des], context2);
}
return contents;
}, "de_StorageClassAnalysisDataExport");
de_Tag = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_K] != null) {
contents[_K] = expectString(output[_K]);
}
if (output[_Va] != null) {
contents[_Va] = expectString(output[_Va]);
}
return contents;
}, "de_Tag");
de_TagSet = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_Tag(entry, context2);
});
}, "de_TagSet");
de_TargetGrant = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Gra] != null) {
contents[_Gra] = de_Grantee(output[_Gra], context2);
}
if (output[_Pe] != null) {
contents[_Pe] = expectString(output[_Pe]);
}
return contents;
}, "de_TargetGrant");
de_TargetGrants = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_TargetGrant(entry, context2);
});
}, "de_TargetGrants");
de_TargetObjectKeyFormat = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_SPi] != null) {
contents[_SPi] = de_SimplePrefix(output[_SPi], context2);
}
if (output[_PP] != null) {
contents[_PP] = de_PartitionedPrefix(output[_PP], context2);
}
return contents;
}, "de_TargetObjectKeyFormat");
de_Tiering = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Da] != null) {
contents[_Da] = strictParseInt32(output[_Da]);
}
if (output[_AT] != null) {
contents[_AT] = expectString(output[_AT]);
}
return contents;
}, "de_Tiering");
de_TieringList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_Tiering(entry, context2);
});
}, "de_TieringList");
de_TopicConfiguration = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_I] != null) {
contents[_I] = expectString(output[_I]);
}
if (output[_Top] != null) {
contents[_TA] = expectString(output[_Top]);
}
if (output.Event === "") {
contents[_Eve] = [];
} else if (output[_Ev] != null) {
contents[_Eve] = de_EventList(getArrayIfSingleItem(output[_Ev]), context2);
}
if (output[_F] != null) {
contents[_F] = de_NotificationConfigurationFilter(output[_F], context2);
}
return contents;
}, "de_TopicConfiguration");
de_TopicConfigurationList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_TopicConfiguration(entry, context2);
});
}, "de_TopicConfigurationList");
de_Transition = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Dat] != null) {
contents[_Dat] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_Dat]));
}
if (output[_Da] != null) {
contents[_Da] = strictParseInt32(output[_Da]);
}
if (output[_SC] != null) {
contents[_SC] = expectString(output[_SC]);
}
return contents;
}, "de_Transition");
de_TransitionList = /* @__PURE__ */ __name((output, context2) => {
return (output || []).filter((e7) => e7 != null).map((entry) => {
return de_Transition(entry, context2);
});
}, "de_TransitionList");
deserializeMetadata2 = /* @__PURE__ */ __name((output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"]
}), "deserializeMetadata");
collectBodyString2 = /* @__PURE__ */ __name((streamBody, context2) => collectBody(streamBody, context2).then((body) => context2.utf8Encoder(body)), "collectBodyString");
_A = "And";
_AAO = "AnalyticsAndOperator";
_AC = "AnalyticsConfiguration";
_ACL = "ACL";
_ACLc = "AccessControlList";
_ACLn = "AnalyticsConfigurationList";
_ACP = "AccessControlPolicy";
_ACT = "AccessControlTranslation";
_ACc = "AccelerateConfiguration";
_AD = "AbortDate";
_AED = "AnalyticsExportDestination";
_AF = "AnalyticsFilter";
_AH = "AllowedHeader";
_AHl = "AllowedHeaders";
_AI = "AnalyticsId";
_AIMU = "AbortIncompleteMultipartUpload";
_AIc = "AccountId";
_AKI = "AccessKeyId";
_AM = "AllowedMethod";
_AMl = "AllowedMethods";
_AO = "AllowedOrigin";
_AOl = "AllowedOrigins";
_APA = "AccessPointAlias";
_APAc = "AccessPointArn";
_AQRD = "AllowQuotedRecordDelimiter";
_AR = "AcceptRanges";
_ARI = "AbortRuleId";
_AS = "ArchiveStatus";
_ASBD = "AnalyticsS3BucketDestination";
_ASEFF = "AnalyticsS3ExportFileFormat";
_ASSEBD = "ApplyServerSideEncryptionByDefault";
_AT = "AccessTier";
_Ac = "Account";
_B = "Bucket";
_BAI = "BucketAccountId";
_BAS = "BucketAccelerateStatus";
_BGR = "BypassGovernanceRetention";
_BI = "BucketInfo";
_BKE = "BucketKeyEnabled";
_BLC = "BucketLifecycleConfiguration";
_BLCu = "BucketLocationConstraint";
_BLN = "BucketLocationName";
_BLP = "BucketLogsPermission";
_BLS = "BucketLoggingStatus";
_BLT = "BucketLocationType";
_BN = "BucketName";
_BP = "BytesProcessed";
_BPA = "BlockPublicAcls";
_BPP = "BlockPublicPolicy";
_BR = "BucketRegion";
_BRy = "BytesReturned";
_BS = "BytesScanned";
_BT = "BucketType";
_BVS = "BucketVersioningStatus";
_Bu = "Buckets";
_C = "Credentials";
_CA = "ChecksumAlgorithm";
_CACL = "CannedACL";
_CBC = "CreateBucketConfiguration";
_CC = "CacheControl";
_CCRC = "ChecksumCRC32";
_CCRCC = "ChecksumCRC32C";
_CD = "ContentDisposition";
_CDr = "CreationDate";
_CE = "ContentEncoding";
_CF = "CloudFunction";
_CFC = "CloudFunctionConfiguration";
_CL = "ContentLanguage";
_CLo = "ContentLength";
_CM = "ChecksumMode";
_CMD = "ContentMD5";
_CMU = "CompletedMultipartUpload";
_CORSC = "CORSConfiguration";
_CORSR = "CORSRule";
_CORSRu = "CORSRules";
_CP = "CommonPrefixes";
_CPo = "CompletedPart";
_CR = "ContentRange";
_CRSBA = "ConfirmRemoveSelfBucketAccess";
_CS = "CopySource";
_CSHA = "ChecksumSHA1";
_CSHAh = "ChecksumSHA256";
_CSIM = "CopySourceIfMatch";
_CSIMS = "CopySourceIfModifiedSince";
_CSINM = "CopySourceIfNoneMatch";
_CSIUS = "CopySourceIfUnmodifiedSince";
_CSR = "CopySourceRange";
_CSSSECA = "CopySourceSSECustomerAlgorithm";
_CSSSECK = "CopySourceSSECustomerKey";
_CSSSECKMD = "CopySourceSSECustomerKeyMD5";
_CSV = "CSV";
_CSVI = "CopySourceVersionId";
_CSVIn = "CSVInput";
_CSVO = "CSVOutput";
_CT = "ContentType";
_CTo = "ContinuationToken";
_CTom = "CompressionType";
_Ch = "Checksum";
_Co = "Contents";
_Cod = "Code";
_Com = "Comments";
_Con = "Condition";
_D = "Delimiter";
_DAI = "DaysAfterInitiation";
_DE = "DataExport";
_DM = "DeleteMarker";
_DMR = "DeleteMarkerReplication";
_DMRS = "DeleteMarkerReplicationStatus";
_DMVI = "DeleteMarkerVersionId";
_DMe = "DeleteMarkers";
_DN = "DisplayName";
_DR = "DataRedundancy";
_DRe = "DefaultRetention";
_Da = "Days";
_Dat = "Date";
_De = "Deleted";
_Del = "Delete";
_Des = "Destination";
_Desc = "Description";
_E = "Expires";
_EA = "EmailAddress";
_EBC = "EventBridgeConfiguration";
_EBO = "ExpectedBucketOwner";
_EC = "ErrorCode";
_ECn = "EncryptionConfiguration";
_ED = "ErrorDocument";
_EH = "ExposeHeaders";
_EHx = "ExposeHeader";
_EM = "ErrorMessage";
_EODM = "ExpiredObjectDeleteMarker";
_EOR = "ExistingObjectReplication";
_EORS = "ExistingObjectReplicationStatus";
_ERP = "EnableRequestProgress";
_ES = "ExpiresString";
_ESBO = "ExpectedSourceBucketOwner";
_ESx = "ExpirationStatus";
_ET = "EncodingType";
_ETa = "ETag";
_ETn = "EncryptionType";
_ETv = "EventThreshold";
_ETx = "ExpressionType";
_En = "Encryption";
_Ena = "Enabled";
_End = "End";
_Er = "Error";
_Err = "Errors";
_Ev = "Event";
_Eve = "Events";
_Ex = "Expression";
_Exp = "Expiration";
_F = "Filter";
_FD = "FieldDelimiter";
_FHI = "FileHeaderInfo";
_FO = "FetchOwner";
_FR = "FilterRule";
_FRN = "FilterRuleName";
_FRV = "FilterRuleValue";
_FRi = "FilterRules";
_Fi = "Field";
_Fo = "Format";
_Fr = "Frequency";
_G = "Grant";
_GFC = "GrantFullControl";
_GJP = "GlacierJobParameters";
_GR = "GrantRead";
_GRACP = "GrantReadACP";
_GW = "GrantWrite";
_GWACP = "GrantWriteACP";
_Gr = "Grants";
_Gra = "Grantee";
_HECRE = "HttpErrorCodeReturnedEquals";
_HN = "HostName";
_HRC = "HttpRedirectCode";
_I = "Id";
_IC = "InventoryConfiguration";
_ICL = "InventoryConfigurationList";
_ID = "IndexDocument";
_ID_ = "ID";
_IDn = "InventoryDestination";
_IE = "IsEnabled";
_IEn = "InventoryEncryption";
_IF = "InventoryFilter";
_IFn = "InventoryFormat";
_IFnv = "InventoryFrequency";
_II = "InventoryId";
_IIOV = "InventoryIncludedObjectVersions";
_IL = "IsLatest";
_IM = "IfMatch";
_IMIT = "IfMatchInitiatedTime";
_IMLMT = "IfMatchLastModifiedTime";
_IMS = "IfMatchSize";
_IMSf = "IfModifiedSince";
_INM = "IfNoneMatch";
_IOF = "InventoryOptionalField";
_IOV = "IncludedObjectVersions";
_IP = "IsPublic";
_IPA = "IgnorePublicAcls";
_IRIP = "IsRestoreInProgress";
_IS = "InputSerialization";
_ISBD = "InventoryS3BucketDestination";
_ISn = "InventorySchedule";
_IT = "IsTruncated";
_ITAO = "IntelligentTieringAndOperator";
_ITAT = "IntelligentTieringAccessTier";
_ITC = "IntelligentTieringConfiguration";
_ITCL = "IntelligentTieringConfigurationList";
_ITD = "IntelligentTieringDays";
_ITF = "IntelligentTieringFilter";
_ITI = "IntelligentTieringId";
_ITS = "IntelligentTieringStatus";
_IUS = "IfUnmodifiedSince";
_In = "Initiator";
_Ini = "Initiated";
_JSON = "JSON";
_JSONI = "JSONInput";
_JSONO = "JSONOutput";
_JSONT = "JSONType";
_K = "Key";
_KC = "KeyCount";
_KI = "KeyId";
_KM = "KeyMarker";
_KMSC = "KMSContext";
_KMSKI = "KMSKeyId";
_KMSMKID = "KMSMasterKeyID";
_KPE = "KeyPrefixEquals";
_L = "Location";
_LC = "LocationConstraint";
_LE = "LoggingEnabled";
_LEi = "LifecycleExpiration";
_LFA = "LambdaFunctionArn";
_LFC = "LambdaFunctionConfigurations";
_LFCa = "LambdaFunctionConfiguration";
_LI = "LocationInfo";
_LM = "LastModified";
_LMT = "LastModifiedTime";
_LNAS = "LocationNameAsString";
_LP = "LocationPrefix";
_LR = "LifecycleRule";
_LRAO = "LifecycleRuleAndOperator";
_LRF = "LifecycleRuleFilter";
_LT = "LocationType";
_M = "Marker";
_MAO = "MetricsAndOperator";
_MAS = "MaxAgeSeconds";
_MB = "MaxBuckets";
_MC = "MetricsConfiguration";
_MCL = "MetricsConfigurationList";
_MD = "MetadataDirective";
_MDB = "MaxDirectoryBuckets";
_MDf = "MfaDelete";
_ME = "MetadataEntry";
_MF = "MetricsFilter";
_MFA = "MFA";
_MFAD = "MFADelete";
_MI = "MetricsId";
_MK = "MaxKeys";
_MKe = "MetadataKey";
_MM = "MissingMeta";
_MP = "MaxParts";
_MS = "MetricsStatus";
_MTC = "MetadataTableConfiguration";
_MTCR = "MetadataTableConfigurationResult";
_MU = "MaxUploads";
_MV = "MetadataValue";
_Me = "Metrics";
_Mes = "Message";
_Mi = "Minutes";
_Mo = "Mode";
_N = "Name";
_NC = "NotificationConfiguration";
_NCF = "NotificationConfigurationFilter";
_NCT = "NextContinuationToken";
_ND = "NoncurrentDays";
_NI = "NotificationId";
_NKM = "NextKeyMarker";
_NM = "NextMarker";
_NNV = "NewerNoncurrentVersions";
_NPNM = "NextPartNumberMarker";
_NUIM = "NextUploadIdMarker";
_NVE = "NoncurrentVersionExpiration";
_NVIM = "NextVersionIdMarker";
_NVT = "NoncurrentVersionTransitions";
_NVTo = "NoncurrentVersionTransition";
_O = "Owner";
_OA = "ObjectAttributes";
_OC = "OwnershipControls";
_OCACL = "ObjectCannedACL";
_OCR = "OwnershipControlsRule";
_OF = "OptionalFields";
_OI = "ObjectIdentifier";
_OK = "ObjectKey";
_OL = "OutputLocation";
_OLC = "ObjectLockConfiguration";
_OLE = "ObjectLockEnabled";
_OLEFB = "ObjectLockEnabledForBucket";
_OLLH = "ObjectLockLegalHold";
_OLLHS = "ObjectLockLegalHoldStatus";
_OLM = "ObjectLockMode";
_OLR = "ObjectLockRetention";
_OLRM = "ObjectLockRetentionMode";
_OLRUD = "ObjectLockRetainUntilDate";
_OLRb = "ObjectLockRule";
_OO = "ObjectOwnership";
_OOA = "OptionalObjectAttributes";
_OOw = "OwnerOverride";
_OP = "ObjectParts";
_OS = "OutputSerialization";
_OSGT = "ObjectSizeGreaterThan";
_OSGTB = "ObjectSizeGreaterThanBytes";
_OSLT = "ObjectSizeLessThan";
_OSLTB = "ObjectSizeLessThanBytes";
_OSV = "OutputSchemaVersion";
_OSb = "ObjectSize";
_OVI = "ObjectVersionId";
_Ob = "Objects";
_P = "Prefix";
_PABC = "PublicAccessBlockConfiguration";
_PC = "PartsCount";
_PDS = "PartitionDateSource";
_PI = "ParquetInput";
_PN = "PartNumber";
_PNM = "PartNumberMarker";
_PP = "PartitionedPrefix";
_Pa = "Payer";
_Par = "Part";
_Parq = "Parquet";
_Part = "Parts";
_Pe = "Permission";
_Pr = "Protocol";
_Pri = "Priority";
_Q = "Quiet";
_QA = "QueueArn";
_QC = "QueueConfiguration";
_QCu = "QueueConfigurations";
_QCuo = "QuoteCharacter";
_QEC = "QuoteEscapeCharacter";
_QF = "QuoteFields";
_Qu = "Queue";
_R = "Range";
_RART = "RedirectAllRequestsTo";
_RC = "RequestCharged";
_RCC = "ResponseCacheControl";
_RCD = "ResponseContentDisposition";
_RCE = "ResponseContentEncoding";
_RCL = "ResponseContentLanguage";
_RCT = "ResponseContentType";
_RCe = "ReplicationConfiguration";
_RD = "RecordDelimiter";
_RE = "ResponseExpires";
_RED = "RestoreExpiryDate";
_RKKID = "ReplicaKmsKeyID";
_RKPW = "ReplaceKeyPrefixWith";
_RKW = "ReplaceKeyWith";
_RM = "ReplicaModifications";
_RMS = "ReplicaModificationsStatus";
_ROP = "RestoreOutputPath";
_RP = "RequestPayer";
_RPB = "RestrictPublicBuckets";
_RPC = "RequestPaymentConfiguration";
_RPe = "RequestProgress";
_RR = "RequestRoute";
_RRAO = "ReplicationRuleAndOperator";
_RRF = "ReplicationRuleFilter";
_RRS = "ReplicationRuleStatus";
_RRT = "RestoreRequestType";
_RRe = "ReplicationRule";
_RRes = "RestoreRequest";
_RRo = "RoutingRules";
_RRou = "RoutingRule";
_RS = "ReplicationStatus";
_RSe = "RestoreStatus";
_RT = "RequestToken";
_RTS = "ReplicationTimeStatus";
_RTV = "ReplicationTimeValue";
_RTe = "ReplicationTime";
_RUD = "RetainUntilDate";
_Re = "Restore";
_Red = "Redirect";
_Ro = "Role";
_Ru = "Rule";
_Rul = "Rules";
_S = "Status";
_SA = "StartAfter";
_SAK = "SecretAccessKey";
_SBD = "S3BucketDestination";
_SC = "StorageClass";
_SCA = "StorageClassAnalysis";
_SCADE = "StorageClassAnalysisDataExport";
_SCASV = "StorageClassAnalysisSchemaVersion";
_SCt = "StatusCode";
_SDV = "SkipDestinationValidation";
_SK = "SSE-KMS";
_SKEO = "SseKmsEncryptedObjects";
_SKEOS = "SseKmsEncryptedObjectsStatus";
_SKF = "S3KeyFilter";
_SKe = "S3Key";
_SL = "S3Location";
_SM = "SessionMode";
_SOCR = "SelectObjectContentRequest";
_SP = "SelectParameters";
_SPi = "SimplePrefix";
_SR = "ScanRange";
_SS = "SSE-S3";
_SSC = "SourceSelectionCriteria";
_SSE = "ServerSideEncryption";
_SSEA = "SSEAlgorithm";
_SSEBD = "ServerSideEncryptionByDefault";
_SSEC = "ServerSideEncryptionConfiguration";
_SSECA = "SSECustomerAlgorithm";
_SSECK = "SSECustomerKey";
_SSECKMD = "SSECustomerKeyMD5";
_SSEKMS = "SSEKMS";
_SSEKMSEC = "SSEKMSEncryptionContext";
_SSEKMSKI = "SSEKMSKeyId";
_SSER = "ServerSideEncryptionRule";
_SSES = "SSES3";
_ST = "SessionToken";
_STBA = "S3TablesBucketArn";
_STD = "S3TablesDestination";
_STDR = "S3TablesDestinationResult";
_STN = "S3TablesName";
_S_ = "S3";
_Sc = "Schedule";
_Se = "Setting";
_Si = "Size";
_St = "Start";
_Su = "Suffix";
_T = "Tagging";
_TA = "TopicArn";
_TAa = "TableArn";
_TB = "TargetBucket";
_TBA = "TableBucketArn";
_TC = "TagCount";
_TCo = "TopicConfiguration";
_TCop = "TopicConfigurations";
_TD = "TaggingDirective";
_TDMOS = "TransitionDefaultMinimumObjectSize";
_TG = "TargetGrants";
_TGa = "TargetGrant";
_TN = "TableName";
_TNa = "TableNamespace";
_TOKF = "TargetObjectKeyFormat";
_TP = "TargetPrefix";
_TPC = "TotalPartsCount";
_TS = "TagSet";
_TSC = "TransitionStorageClass";
_Ta = "Tag";
_Tag = "Tags";
_Ti = "Tier";
_Tie = "Tierings";
_Tier = "Tiering";
_Tim = "Time";
_To = "Token";
_Top = "Topic";
_Tr = "Transitions";
_Tra = "Transition";
_Ty = "Type";
_U = "Upload";
_UI = "UploadId";
_UIM = "UploadIdMarker";
_UM = "UserMetadata";
_URI = "URI";
_Up = "Uploads";
_V = "Version";
_VC = "VersionCount";
_VCe = "VersioningConfiguration";
_VI = "VersionId";
_VIM = "VersionIdMarker";
_Va = "Value";
_Ve = "Versions";
_WC = "WebsiteConfiguration";
_WOB = "WriteOffsetBytes";
_WRL = "WebsiteRedirectLocation";
_Y = "Years";
_a2 = "analytics";
_ac = "accelerate";
_acl = "acl";
_ar = "accept-ranges";
_at = "attributes";
_br = "bucket-region";
_c2 = "cors";
_cc = "cache-control";
_cd = "content-disposition";
_ce = "content-encoding";
_cl = "content-language";
_cl_ = "content-length";
_cm = "content-md5";
_cr = "content-range";
_ct = "content-type";
_ct_ = "continuation-token";
_d = "delete";
_de = "delimiter";
_e = "expires";
_en = "encryption";
_et = "encoding-type";
_eta = "etag";
_ex = "expiresstring";
_fo = "fetch-owner";
_i = "id";
_im = "if-match";
_ims = "if-modified-since";
_in = "inventory";
_inm = "if-none-match";
_it = "intelligent-tiering";
_ius = "if-unmodified-since";
_km = "key-marker";
_l = "lifecycle";
_lh = "legal-hold";
_lm = "last-modified";
_lo = "location";
_log = "logging";
_lt = "list-type";
_m = "metrics";
_mT = "metadataTable";
_ma = "marker";
_mb = "max-buckets";
_mdb = "max-directory-buckets";
_me = "member";
_mk = "max-keys";
_mp = "max-parts";
_mu = "max-uploads";
_n = "notification";
_oC = "ownershipControls";
_ol = "object-lock";
_p = "policy";
_pAB = "publicAccessBlock";
_pN = "partNumber";
_pS = "policyStatus";
_pnm = "part-number-marker";
_pr = "prefix";
_r = "replication";
_rP = "requestPayment";
_ra = "range";
_rcc = "response-cache-control";
_rcd = "response-content-disposition";
_rce = "response-content-encoding";
_rcl = "response-content-language";
_rct = "response-content-type";
_re = "response-expires";
_res = "restore";
_ret = "retention";
_s = "session";
_sa = "start-after";
_se = "select";
_st = "select-type";
_t = "tagging";
_to = "torrent";
_u = "uploads";
_uI = "uploadId";
_uim = "upload-id-marker";
_v = "versioning";
_vI = "versionId";
_ve = '<?xml version="1.0" encoding="UTF-8"?>';
_ver = "versions";
_vim = "version-id-marker";
_w = "website";
_x = "xsi:type";
_xaa = "x-amz-acl";
_xaad = "x-amz-abort-date";
_xaapa = "x-amz-access-point-alias";
_xaari = "x-amz-abort-rule-id";
_xaas = "x-amz-archive-status";
_xabgr = "x-amz-bypass-governance-retention";
_xabln = "x-amz-bucket-location-name";
_xablt = "x-amz-bucket-location-type";
_xabole = "x-amz-bucket-object-lock-enabled";
_xabolt = "x-amz-bucket-object-lock-token";
_xabr = "x-amz-bucket-region";
_xaca = "x-amz-checksum-algorithm";
_xacc = "x-amz-checksum-crc32";
_xacc_ = "x-amz-checksum-crc32c";
_xacm = "x-amz-checksum-mode";
_xacrsba = "x-amz-confirm-remove-self-bucket-access";
_xacs = "x-amz-checksum-sha1";
_xacs_ = "x-amz-checksum-sha256";
_xacs__ = "x-amz-copy-source";
_xacsim = "x-amz-copy-source-if-match";
_xacsims = "x-amz-copy-source-if-modified-since";
_xacsinm = "x-amz-copy-source-if-none-match";
_xacsius = "x-amz-copy-source-if-unmodified-since";
_xacsm = "x-amz-create-session-mode";
_xacsr = "x-amz-copy-source-range";
_xacssseca = "x-amz-copy-source-server-side-encryption-customer-algorithm";
_xacssseck = "x-amz-copy-source-server-side-encryption-customer-key";
_xacssseckm = "x-amz-copy-source-server-side-encryption-customer-key-md5";
_xacsvi = "x-amz-copy-source-version-id";
_xadm = "x-amz-delete-marker";
_xae = "x-amz-expiration";
_xaebo = "x-amz-expected-bucket-owner";
_xafec = "x-amz-fwd-error-code";
_xafem = "x-amz-fwd-error-message";
_xafhar = "x-amz-fwd-header-accept-ranges";
_xafhcc = "x-amz-fwd-header-cache-control";
_xafhcd = "x-amz-fwd-header-content-disposition";
_xafhce = "x-amz-fwd-header-content-encoding";
_xafhcl = "x-amz-fwd-header-content-language";
_xafhcr = "x-amz-fwd-header-content-range";
_xafhct = "x-amz-fwd-header-content-type";
_xafhe = "x-amz-fwd-header-etag";
_xafhe_ = "x-amz-fwd-header-expires";
_xafhlm = "x-amz-fwd-header-last-modified";
_xafhxacc = "x-amz-fwd-header-x-amz-checksum-crc32";
_xafhxacc_ = "x-amz-fwd-header-x-amz-checksum-crc32c";
_xafhxacs = "x-amz-fwd-header-x-amz-checksum-sha1";
_xafhxacs_ = "x-amz-fwd-header-x-amz-checksum-sha256";
_xafhxadm = "x-amz-fwd-header-x-amz-delete-marker";
_xafhxae = "x-amz-fwd-header-x-amz-expiration";
_xafhxamm = "x-amz-fwd-header-x-amz-missing-meta";
_xafhxampc = "x-amz-fwd-header-x-amz-mp-parts-count";
_xafhxaollh = "x-amz-fwd-header-x-amz-object-lock-legal-hold";
_xafhxaolm = "x-amz-fwd-header-x-amz-object-lock-mode";
_xafhxaolrud = "x-amz-fwd-header-x-amz-object-lock-retain-until-date";
_xafhxar = "x-amz-fwd-header-x-amz-restore";
_xafhxarc = "x-amz-fwd-header-x-amz-request-charged";
_xafhxars = "x-amz-fwd-header-x-amz-replication-status";
_xafhxasc = "x-amz-fwd-header-x-amz-storage-class";
_xafhxasse = "x-amz-fwd-header-x-amz-server-side-encryption";
_xafhxasseakki = "x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id";
_xafhxassebke = "x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled";
_xafhxasseca = "x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm";
_xafhxasseckm = "x-amz-fwd-header-x-amz-server-side-encryption-customer-key-md5";
_xafhxatc = "x-amz-fwd-header-x-amz-tagging-count";
_xafhxavi = "x-amz-fwd-header-x-amz-version-id";
_xafs = "x-amz-fwd-status";
_xagfc = "x-amz-grant-full-control";
_xagr = "x-amz-grant-read";
_xagra = "x-amz-grant-read-acp";
_xagw = "x-amz-grant-write";
_xagwa = "x-amz-grant-write-acp";
_xaimit = "x-amz-if-match-initiated-time";
_xaimlmt = "x-amz-if-match-last-modified-time";
_xaims = "x-amz-if-match-size";
_xam = "x-amz-mfa";
_xamd = "x-amz-metadata-directive";
_xamm = "x-amz-missing-meta";
_xamp = "x-amz-max-parts";
_xampc = "x-amz-mp-parts-count";
_xaoa = "x-amz-object-attributes";
_xaollh = "x-amz-object-lock-legal-hold";
_xaolm = "x-amz-object-lock-mode";
_xaolrud = "x-amz-object-lock-retain-until-date";
_xaoo = "x-amz-object-ownership";
_xaooa = "x-amz-optional-object-attributes";
_xaos = "x-amz-object-size";
_xapnm = "x-amz-part-number-marker";
_xar = "x-amz-restore";
_xarc = "x-amz-request-charged";
_xarop = "x-amz-restore-output-path";
_xarp = "x-amz-request-payer";
_xarr = "x-amz-request-route";
_xars = "x-amz-replication-status";
_xart = "x-amz-request-token";
_xasc = "x-amz-storage-class";
_xasca = "x-amz-sdk-checksum-algorithm";
_xasdv = "x-amz-skip-destination-validation";
_xasebo = "x-amz-source-expected-bucket-owner";
_xasse = "x-amz-server-side-encryption";
_xasseakki = "x-amz-server-side-encryption-aws-kms-key-id";
_xassebke = "x-amz-server-side-encryption-bucket-key-enabled";
_xassec = "x-amz-server-side-encryption-context";
_xasseca = "x-amz-server-side-encryption-customer-algorithm";
_xasseck = "x-amz-server-side-encryption-customer-key";
_xasseckm = "x-amz-server-side-encryption-customer-key-md5";
_xat = "x-amz-tagging";
_xatc = "x-amz-tagging-count";
_xatd = "x-amz-tagging-directive";
_xatdmos = "x-amz-transition-default-minimum-object-size";
_xavi = "x-amz-version-id";
_xawob = "x-amz-write-offset-bytes";
_xawrl = "x-amz-website-redirect-location";
_xi = "x-id";
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateSessionCommand.js
var CreateSessionCommand;
var init_CreateSessionCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateSessionCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
CreateSessionCommand = class extends Command.classBuilder().ep({
...commonParams,
DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "CreateSession", {}).n("S3Client", "CreateSessionCommand").f(CreateSessionRequestFilterSensitiveLog, CreateSessionOutputFilterSensitiveLog).ser(se_CreateSessionCommand).de(de_CreateSessionCommand).build() {
static {
__name(this, "CreateSessionCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/package.json
var package_default;
var init_package2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/package.json"() {
package_default = {
name: "@aws-sdk/client-s3",
description: "AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native",
version: "3.721.0",
scripts: {
build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
"build:cjs": "node ../../scripts/compilation/inline client-s3",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
"build:types": "tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
"extract:docs": "api-extractor run --local",
"generate:client": "node ../../scripts/generate-clients/single-service --solo s3",
test: "yarn g:vitest run",
"test:browser": "node ./test/browser-build/esbuild && vitest run -c vitest.config.browser.ts --mode development",
"test:browser:watch": "node ./test/browser-build/esbuild && yarn g:vitest watch -c vitest.config.browser.ts",
"test:e2e": "yarn g:vitest run -c vitest.config.e2e.ts --mode development && yarn test:browser",
"test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.ts",
"test:watch": "yarn g:vitest watch"
},
main: "./dist-cjs/index.js",
types: "./dist-types/index.d.ts",
module: "./dist-es/index.js",
sideEffects: false,
dependencies: {
"@aws-crypto/sha1-browser": "5.2.0",
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/client-sso-oidc": "3.721.0",
"@aws-sdk/client-sts": "3.721.0",
"@aws-sdk/core": "3.716.0",
"@aws-sdk/credential-provider-node": "3.721.0",
"@aws-sdk/middleware-bucket-endpoint": "3.721.0",
"@aws-sdk/middleware-expect-continue": "3.714.0",
"@aws-sdk/middleware-flexible-checksums": "3.717.0",
"@aws-sdk/middleware-host-header": "3.714.0",
"@aws-sdk/middleware-location-constraint": "3.714.0",
"@aws-sdk/middleware-logger": "3.714.0",
"@aws-sdk/middleware-recursion-detection": "3.714.0",
"@aws-sdk/middleware-sdk-s3": "3.716.0",
"@aws-sdk/middleware-ssec": "3.714.0",
"@aws-sdk/middleware-user-agent": "3.721.0",
"@aws-sdk/region-config-resolver": "3.714.0",
"@aws-sdk/signature-v4-multi-region": "3.716.0",
"@aws-sdk/types": "3.714.0",
"@aws-sdk/util-endpoints": "3.714.0",
"@aws-sdk/util-user-agent-browser": "3.714.0",
"@aws-sdk/util-user-agent-node": "3.721.0",
"@aws-sdk/xml-builder": "3.709.0",
"@smithy/config-resolver": "^3.0.13",
"@smithy/core": "^2.5.5",
"@smithy/eventstream-serde-browser": "^3.0.14",
"@smithy/eventstream-serde-config-resolver": "^3.0.11",
"@smithy/eventstream-serde-node": "^3.0.13",
"@smithy/fetch-http-handler": "^4.1.2",
"@smithy/hash-blob-browser": "^3.1.10",
"@smithy/hash-node": "^3.0.11",
"@smithy/hash-stream-node": "^3.1.10",
"@smithy/invalid-dependency": "^3.0.11",
"@smithy/md5-js": "^3.0.11",
"@smithy/middleware-content-length": "^3.0.13",
"@smithy/middleware-endpoint": "^3.2.6",
"@smithy/middleware-retry": "^3.0.31",
"@smithy/middleware-serde": "^3.0.11",
"@smithy/middleware-stack": "^3.0.11",
"@smithy/node-config-provider": "^3.1.12",
"@smithy/node-http-handler": "^3.3.2",
"@smithy/protocol-http": "^4.1.8",
"@smithy/smithy-client": "^3.5.1",
"@smithy/types": "^3.7.2",
"@smithy/url-parser": "^3.0.11",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.31",
"@smithy/util-defaults-mode-node": "^3.0.31",
"@smithy/util-endpoints": "^2.1.7",
"@smithy/util-middleware": "^3.0.11",
"@smithy/util-retry": "^3.0.11",
"@smithy/util-stream": "^3.3.2",
"@smithy/util-utf8": "^3.0.0",
"@smithy/util-waiter": "^3.2.0",
tslib: "^2.6.2"
},
devDependencies: {
"@aws-sdk/signature-v4-crt": "3.721.0",
"@tsconfig/node16": "16.1.3",
"@types/node": "^16.18.96",
concurrently: "7.0.0",
"downlevel-dts": "0.10.1",
rimraf: "3.0.2",
typescript: "~4.9.5"
},
engines: {
node: ">=16.0.0"
},
typesVersions: {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
files: [
"dist-*/**"
],
author: {
name: "AWS SDK for JavaScript Team",
url: "https://aws.amazon.com/javascript/"
},
license: "Apache-2.0",
browser: {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
},
"react-native": {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
},
homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3",
repository: {
type: "git",
url: "https://github.com/aws/aws-sdk-js-v3.git",
directory: "clients/client-s3"
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.716.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js
var ENV_KEY, ENV_SECRET, ENV_SESSION, ENV_EXPIRATION, ENV_CREDENTIAL_SCOPE, ENV_ACCOUNT_ID, fromEnv2;
var init_fromEnv2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.716.0/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"() {
init_import_meta_url();
init_client5();
init_dist_es17();
ENV_KEY = "AWS_ACCESS_KEY_ID";
ENV_SECRET = "AWS_SECRET_ACCESS_KEY";
ENV_SESSION = "AWS_SESSION_TOKEN";
ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION";
ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE";
ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID";
fromEnv2 = /* @__PURE__ */ __name((init3) => async () => {
init3?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");
const accessKeyId = process.env[ENV_KEY];
const secretAccessKey = process.env[ENV_SECRET];
const sessionToken = process.env[ENV_SESSION];
const expiry = process.env[ENV_EXPIRATION];
const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];
const accountId = process.env[ENV_ACCOUNT_ID];
if (accessKeyId && secretAccessKey) {
const credentials = {
accessKeyId,
secretAccessKey,
...sessionToken && { sessionToken },
...expiry && { expiration: new Date(expiry) },
...credentialScope && { credentialScope },
...accountId && { accountId }
};
setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g");
return credentials;
}
throw new CredentialsProviderError("Unable to find environment variable credentials.", { logger: init3?.logger });
}, "fromEnv");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.716.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js
var dist_es_exports = {};
__export(dist_es_exports, {
ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID,
ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
ENV_EXPIRATION: () => ENV_EXPIRATION,
ENV_KEY: () => ENV_KEY,
ENV_SECRET: () => ENV_SECRET,
ENV_SESSION: () => ENV_SESSION,
fromEnv: () => fromEnv2
});
var init_dist_es48 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.716.0/node_modules/@aws-sdk/credential-provider-env/dist-es/index.js"() {
init_import_meta_url();
init_fromEnv2();
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js
function httpRequest(options) {
return new Promise((resolve25, reject) => {
const req = (0, import_http2.request)({
method: "GET",
...options,
hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1")
});
req.on("error", (err) => {
reject(Object.assign(new ProviderError("Unable to connect to instance metadata service"), err));
req.destroy();
});
req.on("timeout", () => {
reject(new ProviderError("TimeoutError from instance metadata service"));
req.destroy();
});
req.on("response", (res) => {
const { statusCode = 400 } = res;
if (statusCode < 200 || 300 <= statusCode) {
reject(Object.assign(new ProviderError("Error response received from instance metadata service"), { statusCode }));
req.destroy();
}
const chunks = [];
res.on("data", (chunk) => {
chunks.push(chunk);
});
res.on("end", () => {
resolve25(import_buffer3.Buffer.concat(chunks));
req.destroy();
});
});
req.end();
});
}
var import_buffer3, import_http2;
var init_httpRequest2 = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js"() {
init_import_meta_url();
init_dist_es17();
import_buffer3 = require("buffer");
import_http2 = require("http");
__name(httpRequest, "httpRequest");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js
var isImdsCredentials, fromImdsCredentials;
var init_ImdsCredentials = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js"() {
init_import_meta_url();
isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials");
fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({
accessKeyId: creds.AccessKeyId,
secretAccessKey: creds.SecretAccessKey,
sessionToken: creds.Token,
expiration: new Date(creds.Expiration),
...creds.AccountId && { accountId: creds.AccountId }
}), "fromImdsCredentials");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js
var DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, providerConfigFromInit;
var init_RemoteProviderInit = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js"() {
init_import_meta_url();
DEFAULT_TIMEOUT = 1e3;
DEFAULT_MAX_RETRIES = 0;
providerConfigFromInit = /* @__PURE__ */ __name(({ maxRetries = DEFAULT_MAX_RETRIES, timeout: timeout2 = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout: timeout2 }), "providerConfigFromInit");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js
var retry;
var init_retry4 = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js"() {
init_import_meta_url();
retry = /* @__PURE__ */ __name((toRetry, maxRetries) => {
let promise = toRetry();
for (let i5 = 0; i5 < maxRetries; i5++) {
promise = promise.catch(toRetry);
}
return promise;
}, "retry");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js
var import_url3, ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, ENV_CMDS_AUTH_TOKEN, fromContainerMetadata, requestFromEcsImds, CMDS_IP, GREENGRASS_HOSTS, GREENGRASS_PROTOCOLS, getCmdsUri;
var init_fromContainerMetadata = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js"() {
init_import_meta_url();
init_dist_es17();
import_url3 = require("url");
init_httpRequest2();
init_ImdsCredentials();
init_RemoteProviderInit();
init_retry4();
ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
fromContainerMetadata = /* @__PURE__ */ __name((init3 = {}) => {
const { timeout: timeout2, maxRetries } = providerConfigFromInit(init3);
return () => retry(async () => {
const requestOptions = await getCmdsUri({ logger: init3.logger });
const credsResponse = JSON.parse(await requestFromEcsImds(timeout2, requestOptions));
if (!isImdsCredentials(credsResponse)) {
throw new CredentialsProviderError("Invalid response received from instance metadata service.", {
logger: init3.logger
});
}
return fromImdsCredentials(credsResponse);
}, maxRetries);
}, "fromContainerMetadata");
requestFromEcsImds = /* @__PURE__ */ __name(async (timeout2, options) => {
if (process.env[ENV_CMDS_AUTH_TOKEN]) {
options.headers = {
...options.headers,
Authorization: process.env[ENV_CMDS_AUTH_TOKEN]
};
}
const buffer = await httpRequest({
...options,
timeout: timeout2
});
return buffer.toString();
}, "requestFromEcsImds");
CMDS_IP = "169.254.170.2";
GREENGRASS_HOSTS = {
localhost: true,
"127.0.0.1": true
};
GREENGRASS_PROTOCOLS = {
"http:": true,
"https:": true
};
getCmdsUri = /* @__PURE__ */ __name(async ({ logger: logger4 }) => {
if (process.env[ENV_CMDS_RELATIVE_URI]) {
return {
hostname: CMDS_IP,
path: process.env[ENV_CMDS_RELATIVE_URI]
};
}
if (process.env[ENV_CMDS_FULL_URI]) {
const parsed = (0, import_url3.parse)(process.env[ENV_CMDS_FULL_URI]);
if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {
throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {
tryNextLink: false,
logger: logger4
});
}
if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {
tryNextLink: false,
logger: logger4
});
}
return {
...parsed,
port: parsed.port ? parseInt(parsed.port, 10) : void 0
};
}
throw new CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, {
tryNextLink: false,
logger: logger4
});
}, "getCmdsUri");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js
var InstanceMetadataV1FallbackError;
var init_InstanceMetadataV1FallbackError = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js"() {
init_import_meta_url();
init_dist_es17();
InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends CredentialsProviderError {
static {
__name(this, "InstanceMetadataV1FallbackError");
}
constructor(message, tryNextLink = true) {
super(message, tryNextLink);
this.tryNextLink = tryNextLink;
this.name = "InstanceMetadataV1FallbackError";
Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js
var Endpoint;
var init_Endpoint = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js"() {
init_import_meta_url();
(function(Endpoint2) {
Endpoint2["IPv4"] = "http://169.254.169.254";
Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
})(Endpoint || (Endpoint = {}));
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js
var ENV_ENDPOINT_NAME, CONFIG_ENDPOINT_NAME, ENDPOINT_CONFIG_OPTIONS;
var init_EndpointConfigOptions = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js"() {
init_import_meta_url();
ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint";
ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => env6[ENV_ENDPOINT_NAME], "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => profile[CONFIG_ENDPOINT_NAME], "configFileSelector"),
default: void 0
};
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js
var EndpointMode;
var init_EndpointMode = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js"() {
init_import_meta_url();
(function(EndpointMode2) {
EndpointMode2["IPv4"] = "IPv4";
EndpointMode2["IPv6"] = "IPv6";
})(EndpointMode || (EndpointMode = {}));
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js
var ENV_ENDPOINT_MODE_NAME, CONFIG_ENDPOINT_MODE_NAME, ENDPOINT_MODE_CONFIG_OPTIONS;
var init_EndpointModeConfigOptions = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js"() {
init_import_meta_url();
init_EndpointMode();
ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode";
ENDPOINT_MODE_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => env6[ENV_ENDPOINT_MODE_NAME], "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => profile[CONFIG_ENDPOINT_MODE_NAME], "configFileSelector"),
default: EndpointMode.IPv4
};
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js
var getInstanceMetadataEndpoint, getFromEndpointConfig, getFromEndpointModeConfig;
var init_getInstanceMetadataEndpoint = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js"() {
init_import_meta_url();
init_dist_es39();
init_dist_es41();
init_Endpoint();
init_EndpointConfigOptions();
init_EndpointMode();
init_EndpointModeConfigOptions();
getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint");
getFromEndpointConfig = /* @__PURE__ */ __name(async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig");
getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => {
const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();
switch (endpointMode) {
case EndpointMode.IPv4:
return Endpoint.IPv4;
case EndpointMode.IPv6:
return Endpoint.IPv6;
default:
throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`);
}
}, "getFromEndpointModeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js
var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS, STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS, STATIC_STABILITY_DOC_URL, getExtendedInstanceMetadataCredentials;
var init_getExtendedInstanceMetadataCredentials = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js"() {
init_import_meta_url();
STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger4) => {
const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
const newExpiration = new Date(Date.now() + refreshInterval * 1e3);
logger4.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
const originalExpiration = credentials.originalExpiration ?? credentials.expiration;
return {
...credentials,
...originalExpiration ? { originalExpiration } : {},
expiration: newExpiration
};
}, "getExtendedInstanceMetadataCredentials");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js
var staticStabilityProvider;
var init_staticStabilityProvider = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"() {
init_import_meta_url();
init_getExtendedInstanceMetadataCredentials();
staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => {
const logger4 = options?.logger || console;
let pastCredentials;
return async () => {
let credentials;
try {
credentials = await provider();
if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {
credentials = getExtendedInstanceMetadataCredentials(credentials, logger4);
}
} catch (e7) {
if (pastCredentials) {
logger4.warn("Credential renew failed: ", e7);
credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger4);
} else {
throw e7;
}
}
pastCredentials = credentials;
return credentials;
};
}, "staticStabilityProvider");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js
var IMDS_PATH, IMDS_TOKEN_PATH, AWS_EC2_METADATA_V1_DISABLED, PROFILE_AWS_EC2_METADATA_V1_DISABLED, X_AWS_EC2_METADATA_TOKEN, fromInstanceMetadata, getInstanceMetadataProvider, getMetadataToken, getProfile, getCredentialsFromProfile;
var init_fromInstanceMetadata = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js"() {
init_import_meta_url();
init_dist_es39();
init_dist_es17();
init_InstanceMetadataV1FallbackError();
init_httpRequest2();
init_ImdsCredentials();
init_RemoteProviderInit();
init_retry4();
init_getInstanceMetadataEndpoint();
init_staticStabilityProvider();
IMDS_PATH = "/latest/meta-data/iam/security-credentials/";
IMDS_TOKEN_PATH = "/latest/api/token";
AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED";
PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled";
X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token";
fromInstanceMetadata = /* @__PURE__ */ __name((init3 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init3), { logger: init3.logger }), "fromInstanceMetadata");
getInstanceMetadataProvider = /* @__PURE__ */ __name((init3 = {}) => {
let disableFetchToken = false;
const { logger: logger4, profile } = init3;
const { timeout: timeout2, maxRetries } = providerConfigFromInit(init3);
const getCredentials2 = /* @__PURE__ */ __name(async (maxRetries2, options) => {
const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;
if (isImdsV1Fallback) {
let fallbackBlockedFromProfile = false;
let fallbackBlockedFromProcessEnv = false;
const configValue = await loadConfig({
environmentVariableSelector: /* @__PURE__ */ __name((env6) => {
const envValue = env6[AWS_EC2_METADATA_V1_DISABLED];
fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
if (envValue === void 0) {
throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init3.logger });
}
return fallbackBlockedFromProcessEnv;
}, "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile2) => {
const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED];
fallbackBlockedFromProfile = !!profileValue && profileValue !== "false";
return fallbackBlockedFromProfile;
}, "configFileSelector"),
default: false
}, {
profile
})();
if (init3.ec2MetadataV1Disabled || configValue) {
const causes = [];
if (init3.ec2MetadataV1Disabled)
causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");
if (fallbackBlockedFromProfile)
causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);
if (fallbackBlockedFromProcessEnv)
causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);
throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`);
}
}
const imdsProfile = (await retry(async () => {
let profile2;
try {
profile2 = await getProfile(options);
} catch (err) {
if (err.statusCode === 401) {
disableFetchToken = false;
}
throw err;
}
return profile2;
}, maxRetries2)).trim();
return retry(async () => {
let creds;
try {
creds = await getCredentialsFromProfile(imdsProfile, options, init3);
} catch (err) {
if (err.statusCode === 401) {
disableFetchToken = false;
}
throw err;
}
return creds;
}, maxRetries2);
}, "getCredentials");
return async () => {
const endpoint = await getInstanceMetadataEndpoint();
if (disableFetchToken) {
logger4?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
return getCredentials2(maxRetries, { ...endpoint, timeout: timeout2 });
} else {
let token;
try {
token = (await getMetadataToken({ ...endpoint, timeout: timeout2 })).toString();
} catch (error2) {
if (error2?.statusCode === 400) {
throw Object.assign(error2, {
message: "EC2 Metadata token request returned error"
});
} else if (error2.message === "TimeoutError" || [403, 404, 405].includes(error2.statusCode)) {
disableFetchToken = true;
}
logger4?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
return getCredentials2(maxRetries, { ...endpoint, timeout: timeout2 });
}
return getCredentials2(maxRetries, {
...endpoint,
headers: {
[X_AWS_EC2_METADATA_TOKEN]: token
},
timeout: timeout2
});
}
};
}, "getInstanceMetadataProvider");
getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({
...options,
path: IMDS_TOKEN_PATH,
method: "PUT",
headers: {
"x-aws-ec2-metadata-token-ttl-seconds": "21600"
}
}), "getMetadataToken");
getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile");
getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init3) => {
const credentialsResponse = JSON.parse((await httpRequest({
...options,
path: IMDS_PATH + profile
})).toString());
if (!isImdsCredentials(credentialsResponse)) {
throw new CredentialsProviderError("Invalid response received from instance metadata service.", {
logger: init3.logger
});
}
return fromImdsCredentials(credentialsResponse);
}, "getCredentialsFromProfile");
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/types.js
var init_types12 = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/index.js
var dist_es_exports2 = {};
__export(dist_es_exports2, {
DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
Endpoint: () => Endpoint,
fromContainerMetadata: () => fromContainerMetadata,
fromInstanceMetadata: () => fromInstanceMetadata,
getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
httpRequest: () => httpRequest,
providerConfigFromInit: () => providerConfigFromInit
});
var init_dist_es49 = __esm({
"../../node_modules/.pnpm/@smithy+credential-provider-imds@3.2.8/node_modules/@smithy/credential-provider-imds/dist-es/index.js"() {
init_import_meta_url();
init_fromContainerMetadata();
init_fromInstanceMetadata();
init_RemoteProviderInit();
init_types12();
init_httpRequest2();
init_getInstanceMetadataEndpoint();
init_Endpoint();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js
var ECS_CONTAINER_HOST, EKS_CONTAINER_HOST_IPv4, EKS_CONTAINER_HOST_IPv6, checkUrl;
var init_checkUrl = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js"() {
init_import_meta_url();
init_dist_es17();
ECS_CONTAINER_HOST = "169.254.170.2";
EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
checkUrl = /* @__PURE__ */ __name((url4, logger4) => {
if (url4.protocol === "https:") {
return;
}
if (url4.hostname === ECS_CONTAINER_HOST || url4.hostname === EKS_CONTAINER_HOST_IPv4 || url4.hostname === EKS_CONTAINER_HOST_IPv6) {
return;
}
if (url4.hostname.includes("[")) {
if (url4.hostname === "[::1]" || url4.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
return;
}
} else {
if (url4.hostname === "localhost") {
return;
}
const ipComponents = url4.hostname.split(".");
const inRange = /* @__PURE__ */ __name((component) => {
const num = parseInt(component, 10);
return 0 <= num && num <= 255;
}, "inRange");
if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) {
return;
}
}
throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
- loopback CIDR 127.0.0.0/8 or [::1/128]
- ECS container host 169.254.170.2
- EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger4 });
}, "checkUrl");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js
function createGetRequest(url4) {
return new HttpRequest({
protocol: url4.protocol,
hostname: url4.hostname,
port: Number(url4.port),
path: url4.pathname,
query: Array.from(url4.searchParams.entries()).reduce((acc, [k6, v7]) => {
acc[k6] = v7;
return acc;
}, {}),
fragment: url4.hash
});
}
async function getCredentials(response, logger4) {
const stream2 = sdkStreamMixin2(response.body);
const str = await stream2.transformToString();
if (response.statusCode === 200) {
const parsed = JSON.parse(str);
if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
throw new CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger4 });
}
return {
accessKeyId: parsed.AccessKeyId,
secretAccessKey: parsed.SecretAccessKey,
sessionToken: parsed.Token,
expiration: parseRfc3339DateTime(parsed.Expiration)
};
}
if (response.statusCode >= 400 && response.statusCode < 500) {
let parsedBody = {};
try {
parsedBody = JSON.parse(str);
} catch (e7) {
}
throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger4 }), {
Code: parsedBody.Code,
Message: parsedBody.Message
});
}
throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger4 });
}
var init_requestHelpers = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js"() {
init_import_meta_url();
init_dist_es17();
init_dist_es2();
init_dist_es20();
init_dist_es15();
__name(createGetRequest, "createGetRequest");
__name(getCredentials, "getCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js
var retryWrapper;
var init_retry_wrapper = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"() {
init_import_meta_url();
retryWrapper = /* @__PURE__ */ __name((toRetry, maxRetries, delayMs) => {
return async () => {
for (let i5 = 0; i5 < maxRetries; ++i5) {
try {
return await toRetry();
} catch (e7) {
await new Promise((resolve25) => setTimeout(resolve25, delayMs));
}
}
return await toRetry();
};
}, "retryWrapper");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js
var import_promises25, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, DEFAULT_LINK_LOCAL_HOST, AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, AWS_CONTAINER_AUTHORIZATION_TOKEN, fromHttp;
var init_fromHttp = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js"() {
init_import_meta_url();
init_client5();
init_dist_es12();
init_dist_es17();
import_promises25 = __toESM(require("fs/promises"));
init_checkUrl();
init_requestHelpers();
init_retry_wrapper();
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2";
AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
fromHttp = /* @__PURE__ */ __name((options = {}) => {
options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");
let host;
const relative15 = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];
const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];
const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];
const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];
const warn2 = options.logger?.constructor?.name === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn;
if (relative15 && full) {
warn2("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
warn2("awsContainerCredentialsFullUri will take precedence.");
}
if (token && tokenFile) {
warn2("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
warn2("awsContainerAuthorizationToken will take precedence.");
}
if (full) {
host = full;
} else if (relative15) {
host = `${DEFAULT_LINK_LOCAL_HOST}${relative15}`;
} else {
throw new CredentialsProviderError(`No HTTP credential provider host provided.
Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });
}
const url4 = new URL(host);
checkUrl(url4, options.logger);
const requestHandler = new NodeHttpHandler({
requestTimeout: options.timeout ?? 1e3,
connectionTimeout: options.timeout ?? 1e3
});
return retryWrapper(async () => {
const request4 = createGetRequest(url4);
if (token) {
request4.headers.Authorization = token;
} else if (tokenFile) {
request4.headers.Authorization = (await import_promises25.default.readFile(tokenFile)).toString();
}
try {
const result = await requestHandler.handle(request4);
return getCredentials(result.response).then((creds) => setCredentialFeature(creds, "CREDENTIALS_HTTP", "z"));
} catch (e7) {
throw new CredentialsProviderError(String(e7), { logger: options.logger });
}
}, options.maxRetries ?? 3, options.timeout ?? 1e3);
}, "fromHttp");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/index.js
var dist_es_exports3 = {};
__export(dist_es_exports3, {
fromHttp: () => fromHttp
});
var init_dist_es50 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.716.0/node_modules/@aws-sdk/credential-provider-http/dist-es/index.js"() {
init_import_meta_url();
init_fromHttp();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-st_nxdfcqjud2svw42kuw6i2zwn6q/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js
var ENV_IMDS_DISABLED, remoteProvider;
var init_remoteProvider = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-st_nxdfcqjud2svw42kuw6i2zwn6q/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js"() {
init_import_meta_url();
init_dist_es17();
ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
remoteProvider = /* @__PURE__ */ __name(async (init3) => {
const { ENV_CMDS_FULL_URI: ENV_CMDS_FULL_URI2, ENV_CMDS_RELATIVE_URI: ENV_CMDS_RELATIVE_URI2, fromContainerMetadata: fromContainerMetadata2, fromInstanceMetadata: fromInstanceMetadata2 } = await Promise.resolve().then(() => (init_dist_es49(), dist_es_exports2));
if (process.env[ENV_CMDS_RELATIVE_URI2] || process.env[ENV_CMDS_FULL_URI2]) {
init3.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");
const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es50(), dist_es_exports3));
return chain(fromHttp2(init3), fromContainerMetadata2(init3));
}
if (process.env[ENV_IMDS_DISABLED]) {
return async () => {
throw new CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init3.logger });
};
}
init3.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
return fromInstanceMetadata2(init3);
}, "remoteProvider");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js
var isSsoProfile;
var init_isSsoProfile = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js"() {
init_import_meta_url();
isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/constants.js
var EXPIRE_WINDOW_MS, REFRESH_MESSAGE;
var init_constants14 = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/constants.js"() {
init_import_meta_url();
EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption2(authParameters) {
return {
schemeId: "aws.auth#sigv4",
signingProperties: {
name: "sso-oauth",
region: authParameters.region
},
propertiesExtractor: /* @__PURE__ */ __name((config, context2) => ({
signingProperties: {
config,
context: context2
}
}), "propertiesExtractor")
};
}
function createSmithyApiNoAuthHttpAuthOption(authParameters) {
return {
schemeId: "smithy.api#noAuth"
};
}
var defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig2;
var init_httpAuthSchemeProvider2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/auth/httpAuthSchemeProvider.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es4();
defaultSSOOIDCHttpAuthSchemeParametersProvider = /* @__PURE__ */ __name(async (config, context2, input) => {
return {
operation: getSmithyContext(context2).operation,
region: await normalizeProvider(config.region)() || (() => {
throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
})()
};
}, "defaultSSOOIDCHttpAuthSchemeParametersProvider");
__name(createAwsAuthSigv4HttpAuthOption2, "createAwsAuthSigv4HttpAuthOption");
__name(createSmithyApiNoAuthHttpAuthOption, "createSmithyApiNoAuthHttpAuthOption");
defaultSSOOIDCHttpAuthSchemeProvider = /* @__PURE__ */ __name((authParameters) => {
const options = [];
switch (authParameters.operation) {
case "CreateToken": {
options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
break;
}
case "RegisterClient": {
options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
break;
}
case "StartDeviceAuthorization": {
options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
break;
}
default: {
options.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
}
}
return options;
}, "defaultSSOOIDCHttpAuthSchemeProvider");
resolveHttpAuthSchemeConfig2 = /* @__PURE__ */ __name((config) => {
const config_0 = resolveAwsSdkSigV4Config(config);
return {
...config_0
};
}, "resolveHttpAuthSchemeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters2, commonParams2;
var init_EndpointParameters2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/endpoint/EndpointParameters.js"() {
init_import_meta_url();
resolveClientEndpointParameters2 = /* @__PURE__ */ __name((options) => {
return {
...options,
useDualstackEndpoint: options.useDualstackEndpoint ?? false,
useFipsEndpoint: options.useFipsEndpoint ?? false,
defaultSigningName: "sso-oauth"
};
}, "resolveClientEndpointParameters");
commonParams2 = {
UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
Endpoint: { type: "builtInParams", name: "endpoint" },
Region: { type: "builtInParams", name: "region" },
UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/package.json
var package_default2;
var init_package3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/package.json"() {
package_default2 = {
name: "@aws-sdk/client-sso-oidc",
description: "AWS SDK for JavaScript Sso Oidc Client for Node.js, Browser and React Native",
version: "3.721.0",
scripts: {
build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
"build:cjs": "node ../../scripts/compilation/inline client-sso-oidc",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
"build:types": "tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
"extract:docs": "api-extractor run --local",
"generate:client": "node ../../scripts/generate-clients/single-service --solo sso-oidc"
},
main: "./dist-cjs/index.js",
types: "./dist-types/index.d.ts",
module: "./dist-es/index.js",
sideEffects: false,
dependencies: {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/core": "3.716.0",
"@aws-sdk/credential-provider-node": "3.721.0",
"@aws-sdk/middleware-host-header": "3.714.0",
"@aws-sdk/middleware-logger": "3.714.0",
"@aws-sdk/middleware-recursion-detection": "3.714.0",
"@aws-sdk/middleware-user-agent": "3.721.0",
"@aws-sdk/region-config-resolver": "3.714.0",
"@aws-sdk/types": "3.714.0",
"@aws-sdk/util-endpoints": "3.714.0",
"@aws-sdk/util-user-agent-browser": "3.714.0",
"@aws-sdk/util-user-agent-node": "3.721.0",
"@smithy/config-resolver": "^3.0.13",
"@smithy/core": "^2.5.5",
"@smithy/fetch-http-handler": "^4.1.2",
"@smithy/hash-node": "^3.0.11",
"@smithy/invalid-dependency": "^3.0.11",
"@smithy/middleware-content-length": "^3.0.13",
"@smithy/middleware-endpoint": "^3.2.6",
"@smithy/middleware-retry": "^3.0.31",
"@smithy/middleware-serde": "^3.0.11",
"@smithy/middleware-stack": "^3.0.11",
"@smithy/node-config-provider": "^3.1.12",
"@smithy/node-http-handler": "^3.3.2",
"@smithy/protocol-http": "^4.1.8",
"@smithy/smithy-client": "^3.5.1",
"@smithy/types": "^3.7.2",
"@smithy/url-parser": "^3.0.11",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.31",
"@smithy/util-defaults-mode-node": "^3.0.31",
"@smithy/util-endpoints": "^2.1.7",
"@smithy/util-middleware": "^3.0.11",
"@smithy/util-retry": "^3.0.11",
"@smithy/util-utf8": "^3.0.0",
tslib: "^2.6.2"
},
devDependencies: {
"@tsconfig/node16": "16.1.3",
"@types/node": "^16.18.96",
concurrently: "7.0.0",
"downlevel-dts": "0.10.1",
rimraf: "3.0.2",
typescript: "~4.9.5"
},
engines: {
node: ">=16.0.0"
},
typesVersions: {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
files: [
"dist-*/**"
],
author: {
name: "AWS SDK for JavaScript Team",
url: "https://aws.amazon.com/javascript/"
},
license: "Apache-2.0",
peerDependencies: {
"@aws-sdk/client-sts": "^3.721.0"
},
browser: {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
},
"react-native": {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
},
homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso-oidc",
repository: {
type: "git",
url: "https://github.com/aws/aws-sdk-js-v3.git",
directory: "clients/client-sso-oidc"
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js
var crtAvailability;
var init_crt_availability = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js"() {
init_import_meta_url();
crtAvailability = {
isCrtAvailable: false
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js
var isCrtAvailable;
var init_is_crt_available = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js"() {
init_import_meta_url();
init_crt_availability();
isCrtAvailable = /* @__PURE__ */ __name(() => {
if (crtAvailability.isCrtAvailable) {
return ["md/crt-avail"];
}
return null;
}, "isCrtAvailable");
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js
var import_os6, import_process4, createDefaultUserAgentProvider;
var init_defaultUserAgent = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js"() {
init_import_meta_url();
import_os6 = require("os");
import_process4 = require("process");
init_is_crt_available();
init_crt_availability();
createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => {
return async (config) => {
const sections = [
["aws-sdk-js", clientVersion],
["ua", "2.1"],
[`os/${(0, import_os6.platform)()}`, (0, import_os6.release)()],
["lang/js"],
["md/nodejs", `${import_process4.versions.node}`]
];
const crtAvailable = isCrtAvailable();
if (crtAvailable) {
sections.push(crtAvailable);
}
if (serviceId) {
sections.push([`api/${serviceId}`, clientVersion]);
}
if (import_process4.env.AWS_EXECUTION_ENV) {
sections.push([`exec-env/${import_process4.env.AWS_EXECUTION_ENV}`]);
}
const appId = await config?.userAgentAppId?.();
const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
return resolvedUserAgent;
};
}, "createDefaultUserAgentProvider");
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js
var UA_APP_ID_ENV_NAME, UA_APP_ID_INI_NAME, UA_APP_ID_INI_NAME_DEPRECATED, NODE_APP_ID_CONFIG_OPTIONS;
var init_nodeAppIdConfigOptions = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js"() {
init_import_meta_url();
init_dist_es34();
UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
UA_APP_ID_INI_NAME = "sdk_ua_app_id";
UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
NODE_APP_ID_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => env6[UA_APP_ID_ENV_NAME], "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"),
default: DEFAULT_UA_APP_ID
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js
var init_dist_es51 = __esm({
"../../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.721.0/node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js"() {
init_import_meta_url();
init_defaultUserAgent();
init_nodeAppIdConfigOptions();
}
});
// ../../node_modules/.pnpm/@smithy+hash-node@3.0.11/node_modules/@smithy/hash-node/dist-es/index.js
function castSourceData(toCast, encoding) {
if (import_buffer4.Buffer.isBuffer(toCast)) {
return toCast;
}
if (typeof toCast === "string") {
return fromString(toCast, encoding);
}
if (ArrayBuffer.isView(toCast)) {
return fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength);
}
return fromArrayBuffer(toCast);
}
var import_buffer4, import_crypto6, Hash;
var init_dist_es52 = __esm({
"../../node_modules/.pnpm/@smithy+hash-node@3.0.11/node_modules/@smithy/hash-node/dist-es/index.js"() {
init_import_meta_url();
init_dist_es7();
init_dist_es8();
import_buffer4 = require("buffer");
import_crypto6 = require("crypto");
Hash = class {
static {
__name(this, "Hash");
}
constructor(algorithmIdentifier, secret) {
this.algorithmIdentifier = algorithmIdentifier;
this.secret = secret;
this.reset();
}
update(toHash, encoding) {
this.hash.update(toUint8Array(castSourceData(toHash, encoding)));
}
digest() {
return Promise.resolve(this.hash.digest());
}
reset() {
this.hash = this.secret ? (0, import_crypto6.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto6.createHash)(this.algorithmIdentifier);
}
};
__name(castSourceData, "castSourceData");
}
});
// ../../node_modules/.pnpm/@smithy+util-body-length-node@3.0.0/node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js
var import_fs20, calculateBodyLength;
var init_calculateBodyLength = __esm({
"../../node_modules/.pnpm/@smithy+util-body-length-node@3.0.0/node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js"() {
init_import_meta_url();
import_fs20 = require("fs");
calculateBodyLength = /* @__PURE__ */ __name((body) => {
if (!body) {
return 0;
}
if (typeof body === "string") {
return Buffer.byteLength(body);
} else if (typeof body.byteLength === "number") {
return body.byteLength;
} else if (typeof body.size === "number") {
return body.size;
} else if (typeof body.start === "number" && typeof body.end === "number") {
return body.end + 1 - body.start;
} else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) {
return (0, import_fs20.lstatSync)(body.path).size;
} else if (typeof body.fd === "number") {
return (0, import_fs20.fstatSync)(body.fd).size;
}
throw new Error(`Body Length computation failed for ${body}`);
}, "calculateBodyLength");
}
});
// ../../node_modules/.pnpm/@smithy+util-body-length-node@3.0.0/node_modules/@smithy/util-body-length-node/dist-es/index.js
var init_dist_es53 = __esm({
"../../node_modules/.pnpm/@smithy+util-body-length-node@3.0.0/node_modules/@smithy/util-body-length-node/dist-es/index.js"() {
init_import_meta_url();
init_calculateBodyLength();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/endpoint/ruleset.js
var u2, v3, w3, x3, a2, b3, c3, d3, e3, f3, g3, h3, i2, j3, k3, l3, m3, n2, o2, p3, q3, r3, s2, t3, _data2, ruleSet2;
var init_ruleset2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/endpoint/ruleset.js"() {
init_import_meta_url();
u2 = "required";
v3 = "fn";
w3 = "argv";
x3 = "ref";
a2 = true;
b3 = "isSet";
c3 = "booleanEquals";
d3 = "error";
e3 = "endpoint";
f3 = "tree";
g3 = "PartitionResult";
h3 = "getAttr";
i2 = { [u2]: false, "type": "String" };
j3 = { [u2]: true, "default": false, "type": "Boolean" };
k3 = { [x3]: "Endpoint" };
l3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, true] };
m3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, true] };
n2 = {};
o2 = { [v3]: h3, [w3]: [{ [x3]: g3 }, "supportsFIPS"] };
p3 = { [x3]: g3 };
q3 = { [v3]: c3, [w3]: [true, { [v3]: h3, [w3]: [p3, "supportsDualStack"] }] };
r3 = [l3];
s2 = [m3];
t3 = [{ [x3]: "Region" }];
_data2 = { version: "1.0", parameters: { Region: i2, UseDualStack: j3, UseFIPS: j3, Endpoint: i2 }, rules: [{ conditions: [{ [v3]: b3, [w3]: [k3] }], rules: [{ conditions: r3, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d3 }, { endpoint: { url: k3, properties: n2, headers: n2 }, type: e3 }], type: f3 }, { conditions: [{ [v3]: b3, [w3]: t3 }], rules: [{ conditions: [{ [v3]: "aws.partition", [w3]: t3, assign: g3 }], rules: [{ conditions: [l3, m3], rules: [{ conditions: [{ [v3]: c3, [w3]: [a2, o2] }, q3], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d3 }], type: f3 }, { conditions: r3, rules: [{ conditions: [{ [v3]: c3, [w3]: [o2, a2] }], rules: [{ conditions: [{ [v3]: "stringEquals", [w3]: [{ [v3]: h3, [w3]: [p3, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n2, headers: n2 }, type: e3 }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f3 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d3 }], type: f3 }, { conditions: s2, rules: [{ conditions: [q3], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f3 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d3 }], type: f3 }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, type: e3 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d3 }] };
ruleSet2 = _data2;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/endpoint/endpointResolver.js
var cache3, defaultEndpointResolver2;
var init_endpointResolver2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/endpoint/endpointResolver.js"() {
init_import_meta_url();
init_dist_es33();
init_dist_es32();
init_ruleset2();
cache3 = new EndpointCache({
size: 50,
params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
});
defaultEndpointResolver2 = /* @__PURE__ */ __name((endpointParams, context2 = {}) => {
return cache3.get(endpointParams, () => resolveEndpoint(ruleSet2, {
endpointParams,
logger: context2.logger
}));
}, "defaultEndpointResolver");
customEndpointFunctions.aws = awsEndpointFunctions;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/runtimeConfig.shared.js
var getRuntimeConfig;
var init_runtimeConfig_shared = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/runtimeConfig.shared.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es16();
init_dist_es20();
init_dist_es41();
init_dist_es9();
init_dist_es8();
init_httpAuthSchemeProvider2();
init_endpointResolver2();
getRuntimeConfig = /* @__PURE__ */ __name((config) => {
return {
apiVersion: "2019-06-10",
base64Decoder: config?.base64Decoder ?? fromBase64,
base64Encoder: config?.base64Encoder ?? toBase64,
disableHostPrefix: config?.disableHostPrefix ?? false,
endpointProvider: config?.endpointProvider ?? defaultEndpointResolver2,
extensions: config?.extensions ?? [],
httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), "identityProvider"),
signer: new AwsSdkSigV4Signer()
},
{
schemeId: "smithy.api#noAuth",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), "identityProvider"),
signer: new NoAuthSigner()
}
],
logger: config?.logger ?? new NoOpLogger(),
serviceId: config?.serviceId ?? "SSO OIDC",
urlParser: config?.urlParser ?? parseUrl,
utf8Decoder: config?.utf8Decoder ?? fromUtf8,
utf8Encoder: config?.utf8Encoder ?? toUtf8
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js
var AWS_EXECUTION_ENV, AWS_REGION_ENV, AWS_DEFAULT_REGION_ENV, ENV_IMDS_DISABLED2, DEFAULTS_MODE_OPTIONS, IMDS_REGION_PATH;
var init_constants15 = __esm({
"../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js"() {
init_import_meta_url();
AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
AWS_REGION_ENV = "AWS_REGION";
AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
ENV_IMDS_DISABLED2 = "AWS_EC2_METADATA_DISABLED";
DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
IMDS_REGION_PATH = "/latest/meta-data/placement/region";
}
});
// ../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js
var AWS_DEFAULTS_MODE_ENV, AWS_DEFAULTS_MODE_CONFIG, NODE_DEFAULTS_MODE_CONFIG_OPTIONS;
var init_defaultsModeConfig = __esm({
"../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js"() {
init_import_meta_url();
AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => {
return env6[AWS_DEFAULTS_MODE_ENV];
}, "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => {
return profile[AWS_DEFAULTS_MODE_CONFIG];
}, "configFileSelector"),
default: "legacy"
};
}
});
// ../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js
var resolveDefaultsModeConfig, resolveNodeDefaultsModeAuto, inferPhysicalRegion;
var init_resolveDefaultsModeConfig = __esm({
"../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js"() {
init_import_meta_url();
init_dist_es35();
init_dist_es39();
init_dist_es17();
init_constants15();
init_defaultsModeConfig();
resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ region = loadConfig(NODE_REGION_CONFIG_OPTIONS), defaultsMode = loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => memoize(async () => {
const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
switch (mode?.toLowerCase()) {
case "auto":
return resolveNodeDefaultsModeAuto(region);
case "in-region":
case "cross-region":
case "mobile":
case "standard":
case "legacy":
return Promise.resolve(mode?.toLocaleLowerCase());
case void 0:
return Promise.resolve("legacy");
default:
throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`);
}
}), "resolveDefaultsModeConfig");
resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => {
if (clientRegion) {
const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
const inferredRegion = await inferPhysicalRegion();
if (!inferredRegion) {
return "standard";
}
if (resolvedRegion === inferredRegion) {
return "in-region";
} else {
return "cross-region";
}
}
return "standard";
}, "resolveNodeDefaultsModeAuto");
inferPhysicalRegion = /* @__PURE__ */ __name(async () => {
if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {
return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];
}
if (!process.env[ENV_IMDS_DISABLED2]) {
try {
const { getInstanceMetadataEndpoint: getInstanceMetadataEndpoint2, httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_dist_es49(), dist_es_exports2));
const endpoint = await getInstanceMetadataEndpoint2();
return (await httpRequest2({ ...endpoint, path: IMDS_REGION_PATH })).toString();
} catch (e7) {
}
}
}, "inferPhysicalRegion");
}
});
// ../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/index.js
var init_dist_es54 = __esm({
"../../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.34/node_modules/@smithy/util-defaults-mode-node/dist-es/index.js"() {
init_import_meta_url();
init_resolveDefaultsModeConfig();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/runtimeConfig.js
var getRuntimeConfig2;
var init_runtimeConfig = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/runtimeConfig.js"() {
init_import_meta_url();
init_package3();
init_dist_es21();
init_dist_es64();
init_dist_es51();
init_dist_es35();
init_dist_es52();
init_dist_es45();
init_dist_es39();
init_dist_es12();
init_dist_es53();
init_dist_es44();
init_runtimeConfig_shared();
init_dist_es20();
init_dist_es54();
init_dist_es20();
getRuntimeConfig2 = /* @__PURE__ */ __name((config) => {
emitWarningIfUnsupportedVersion2(process.version);
const defaultsMode = resolveDefaultsModeConfig(config);
const defaultConfigProvider = /* @__PURE__ */ __name(() => defaultsMode().then(loadConfigsForDefaultMode), "defaultConfigProvider");
const clientSharedValues = getRuntimeConfig(config);
emitWarningIfUnsupportedVersion(process.version);
const profileConfig = { profile: config?.profile };
return {
...clientSharedValues,
...config,
runtime: "node",
defaultsMode,
bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider,
defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...profileConfig }),
requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
retryMode: config?.retryMode ?? loadConfig({
...NODE_RETRY_MODE_CONFIG_OPTIONS,
default: /* @__PURE__ */ __name(async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, "default")
}, config),
sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
streamCollector: config?.streamCollector ?? streamCollector,
useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, profileConfig),
useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, profileConfig),
userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, profileConfig)
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js
var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration;
var init_extensions4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() {
init_import_meta_url();
getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
let runtimeConfigRegion = /* @__PURE__ */ __name(async () => {
if (runtimeConfig.region === void 0) {
throw new Error("Region is missing from runtimeConfig");
}
const region = runtimeConfig.region;
if (typeof region === "string") {
return region;
}
return region();
}, "runtimeConfigRegion");
return {
setRegion(region) {
runtimeConfigRegion = region;
},
region() {
return runtimeConfigRegion;
}
};
}, "getAwsRegionExtensionConfiguration");
resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => {
return {
region: awsRegionExtensionConfiguration.region()
};
}, "resolveAwsRegionExtensionConfiguration");
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js
var init_config7 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js
var init_isFipsRegion2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js
var init_getRealRegion2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js"() {
init_import_meta_url();
init_isFipsRegion2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js
var init_resolveRegionConfig2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
init_import_meta_url();
init_getRealRegion2();
init_isFipsRegion2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js
var init_regionConfig2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js"() {
init_import_meta_url();
init_config7();
init_resolveRegionConfig2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js
var init_dist_es55 = __esm({
"../../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.714.0/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() {
init_import_meta_url();
init_extensions4();
init_regionConfig2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig;
var init_httpAuthExtensionConfiguration = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/auth/httpAuthExtensionConfiguration.js"() {
init_import_meta_url();
getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
let _credentials = runtimeConfig.credentials;
return {
setHttpAuthScheme(httpAuthScheme) {
const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
if (index === -1) {
_httpAuthSchemes.push(httpAuthScheme);
} else {
_httpAuthSchemes.splice(index, 1, httpAuthScheme);
}
},
httpAuthSchemes() {
return _httpAuthSchemes;
},
setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
_httpAuthSchemeProvider = httpAuthSchemeProvider;
},
httpAuthSchemeProvider() {
return _httpAuthSchemeProvider;
},
setCredentials(credentials) {
_credentials = credentials;
},
credentials() {
return _credentials;
}
};
}, "getHttpAuthExtensionConfiguration");
resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => {
return {
httpAuthSchemes: config.httpAuthSchemes(),
httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
credentials: config.credentials()
};
}, "resolveHttpAuthRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/runtimeExtensions.js
var asPartial, resolveRuntimeExtensions;
var init_runtimeExtensions = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/runtimeExtensions.js"() {
init_import_meta_url();
init_dist_es55();
init_dist_es2();
init_dist_es20();
init_httpAuthExtensionConfiguration();
asPartial = /* @__PURE__ */ __name((t7) => t7, "asPartial");
resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
const extensionConfiguration = {
...asPartial(getAwsRegionExtensionConfiguration(runtimeConfig)),
...asPartial(getDefaultExtensionConfiguration(runtimeConfig)),
...asPartial(getHttpHandlerExtensionConfiguration(runtimeConfig)),
...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))
};
extensions.forEach((extension) => extension.configure(extensionConfiguration));
return {
...runtimeConfig,
...resolveAwsRegionExtensionConfiguration(extensionConfiguration),
...resolveDefaultRuntimeConfig(extensionConfiguration),
...resolveHttpHandlerRuntimeConfig(extensionConfiguration),
...resolveHttpAuthRuntimeConfig(extensionConfiguration)
};
}, "resolveRuntimeExtensions");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/SSOOIDCClient.js
var SSOOIDCClient;
var init_SSOOIDCClient = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/SSOOIDCClient.js"() {
init_import_meta_url();
init_dist_es26();
init_dist_es27();
init_dist_es28();
init_dist_es34();
init_dist_es35();
init_dist_es16();
init_dist_es37();
init_dist_es42();
init_dist_es45();
init_dist_es20();
init_httpAuthSchemeProvider2();
init_EndpointParameters2();
init_runtimeConfig();
init_runtimeExtensions();
SSOOIDCClient = class extends Client {
static {
__name(this, "SSOOIDCClient");
}
constructor(...[configuration]) {
const _config_0 = getRuntimeConfig2(configuration || {});
const _config_1 = resolveClientEndpointParameters2(_config_0);
const _config_2 = resolveUserAgentConfig(_config_1);
const _config_3 = resolveRetryConfig(_config_2);
const _config_4 = resolveRegionConfig(_config_3);
const _config_5 = resolveHostHeaderConfig(_config_4);
const _config_6 = resolveEndpointConfig(_config_5);
const _config_7 = resolveHttpAuthSchemeConfig2(_config_6);
const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);
super(_config_8);
this.config = _config_8;
this.middlewareStack.use(getUserAgentPlugin(this.config));
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,
identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new DefaultIdentityProviderConfig({
"aws.auth#sigv4": config.credentials
}), "identityProviderConfigProvider")
}));
this.middlewareStack.use(getHttpSigningPlugin(this.config));
}
destroy() {
super.destroy();
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/models/SSOOIDCServiceException.js
var SSOOIDCServiceException;
var init_SSOOIDCServiceException = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/models/SSOOIDCServiceException.js"() {
init_import_meta_url();
init_dist_es20();
SSOOIDCServiceException = class _SSOOIDCServiceException extends ServiceException {
static {
__name(this, "SSOOIDCServiceException");
}
constructor(options) {
super(options);
Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/models/models_0.js
var AccessDeniedException, AuthorizationPendingException, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException, InvalidRequestRegionException, InvalidClientMetadataException, InvalidRedirectUriException, CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog, CreateTokenWithIAMRequestFilterSensitiveLog, CreateTokenWithIAMResponseFilterSensitiveLog, RegisterClientResponseFilterSensitiveLog, StartDeviceAuthorizationRequestFilterSensitiveLog;
var init_models_02 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/models/models_0.js"() {
init_import_meta_url();
init_dist_es20();
init_SSOOIDCServiceException();
AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException {
static {
__name(this, "AccessDeniedException");
}
constructor(opts) {
super({
name: "AccessDeniedException",
$fault: "client",
...opts
});
this.name = "AccessDeniedException";
this.$fault = "client";
Object.setPrototypeOf(this, _AccessDeniedException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException {
static {
__name(this, "AuthorizationPendingException");
}
constructor(opts) {
super({
name: "AuthorizationPendingException",
$fault: "client",
...opts
});
this.name = "AuthorizationPendingException";
this.$fault = "client";
Object.setPrototypeOf(this, _AuthorizationPendingException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException {
static {
__name(this, "ExpiredTokenException");
}
constructor(opts) {
super({
name: "ExpiredTokenException",
$fault: "client",
...opts
});
this.name = "ExpiredTokenException";
this.$fault = "client";
Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InternalServerException = class _InternalServerException extends SSOOIDCServiceException {
static {
__name(this, "InternalServerException");
}
constructor(opts) {
super({
name: "InternalServerException",
$fault: "server",
...opts
});
this.name = "InternalServerException";
this.$fault = "server";
Object.setPrototypeOf(this, _InternalServerException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException {
static {
__name(this, "InvalidClientException");
}
constructor(opts) {
super({
name: "InvalidClientException",
$fault: "client",
...opts
});
this.name = "InvalidClientException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidClientException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException {
static {
__name(this, "InvalidGrantException");
}
constructor(opts) {
super({
name: "InvalidGrantException",
$fault: "client",
...opts
});
this.name = "InvalidGrantException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidGrantException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException {
static {
__name(this, "InvalidRequestException");
}
constructor(opts) {
super({
name: "InvalidRequestException",
$fault: "client",
...opts
});
this.name = "InvalidRequestException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidRequestException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException {
static {
__name(this, "InvalidScopeException");
}
constructor(opts) {
super({
name: "InvalidScopeException",
$fault: "client",
...opts
});
this.name = "InvalidScopeException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidScopeException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
SlowDownException = class _SlowDownException extends SSOOIDCServiceException {
static {
__name(this, "SlowDownException");
}
constructor(opts) {
super({
name: "SlowDownException",
$fault: "client",
...opts
});
this.name = "SlowDownException";
this.$fault = "client";
Object.setPrototypeOf(this, _SlowDownException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException {
static {
__name(this, "UnauthorizedClientException");
}
constructor(opts) {
super({
name: "UnauthorizedClientException",
$fault: "client",
...opts
});
this.name = "UnauthorizedClientException";
this.$fault = "client";
Object.setPrototypeOf(this, _UnauthorizedClientException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException {
static {
__name(this, "UnsupportedGrantTypeException");
}
constructor(opts) {
super({
name: "UnsupportedGrantTypeException",
$fault: "client",
...opts
});
this.name = "UnsupportedGrantTypeException";
this.$fault = "client";
Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InvalidRequestRegionException = class _InvalidRequestRegionException extends SSOOIDCServiceException {
static {
__name(this, "InvalidRequestRegionException");
}
constructor(opts) {
super({
name: "InvalidRequestRegionException",
$fault: "client",
...opts
});
this.name = "InvalidRequestRegionException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidRequestRegionException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
this.endpoint = opts.endpoint;
this.region = opts.region;
}
};
InvalidClientMetadataException = class _InvalidClientMetadataException extends SSOOIDCServiceException {
static {
__name(this, "InvalidClientMetadataException");
}
constructor(opts) {
super({
name: "InvalidClientMetadataException",
$fault: "client",
...opts
});
this.name = "InvalidClientMetadataException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidClientMetadataException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
InvalidRedirectUriException = class _InvalidRedirectUriException extends SSOOIDCServiceException {
static {
__name(this, "InvalidRedirectUriException");
}
constructor(opts) {
super({
name: "InvalidRedirectUriException",
$fault: "client",
...opts
});
this.name = "InvalidRedirectUriException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidRedirectUriException.prototype);
this.error = opts.error;
this.error_description = opts.error_description;
}
};
CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.clientSecret && { clientSecret: SENSITIVE_STRING },
...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
...obj.codeVerifier && { codeVerifier: SENSITIVE_STRING }
}), "CreateTokenRequestFilterSensitiveLog");
CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.accessToken && { accessToken: SENSITIVE_STRING },
...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
...obj.idToken && { idToken: SENSITIVE_STRING }
}), "CreateTokenResponseFilterSensitiveLog");
CreateTokenWithIAMRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
...obj.assertion && { assertion: SENSITIVE_STRING },
...obj.subjectToken && { subjectToken: SENSITIVE_STRING },
...obj.codeVerifier && { codeVerifier: SENSITIVE_STRING }
}), "CreateTokenWithIAMRequestFilterSensitiveLog");
CreateTokenWithIAMResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.accessToken && { accessToken: SENSITIVE_STRING },
...obj.refreshToken && { refreshToken: SENSITIVE_STRING },
...obj.idToken && { idToken: SENSITIVE_STRING }
}), "CreateTokenWithIAMResponseFilterSensitiveLog");
RegisterClientResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.clientSecret && { clientSecret: SENSITIVE_STRING }
}), "RegisterClientResponseFilterSensitiveLog");
StartDeviceAuthorizationRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.clientSecret && { clientSecret: SENSITIVE_STRING }
}), "StartDeviceAuthorizationRequestFilterSensitiveLog");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/protocols/Aws_restJson1.js
var se_CreateTokenCommand, se_CreateTokenWithIAMCommand, se_RegisterClientCommand, se_StartDeviceAuthorizationCommand, de_CreateTokenCommand, de_CreateTokenWithIAMCommand, de_RegisterClientCommand, de_StartDeviceAuthorizationCommand, de_CommandError2, throwDefaultError3, de_AccessDeniedExceptionRes, de_AuthorizationPendingExceptionRes, de_ExpiredTokenExceptionRes, de_InternalServerExceptionRes, de_InvalidClientExceptionRes, de_InvalidClientMetadataExceptionRes, de_InvalidGrantExceptionRes, de_InvalidRedirectUriExceptionRes, de_InvalidRequestExceptionRes, de_InvalidRequestRegionExceptionRes, de_InvalidScopeExceptionRes, de_SlowDownExceptionRes, de_UnauthorizedClientExceptionRes, de_UnsupportedGrantTypeExceptionRes, deserializeMetadata3, _ai;
var init_Aws_restJson1 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/protocols/Aws_restJson1.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es16();
init_dist_es20();
init_models_02();
init_SSOOIDCServiceException();
se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {
"content-type": "application/json"
};
b6.bp("/token");
let body;
body = JSON.stringify(take(input, {
clientId: [],
clientSecret: [],
code: [],
codeVerifier: [],
deviceCode: [],
grantType: [],
redirectUri: [],
refreshToken: [],
scope: /* @__PURE__ */ __name((_4) => _json(_4), "scope")
}));
b6.m("POST").h(headers).b(body);
return b6.build();
}, "se_CreateTokenCommand");
se_CreateTokenWithIAMCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {
"content-type": "application/json"
};
b6.bp("/token");
const query = map({
[_ai]: [, "t"]
});
let body;
body = JSON.stringify(take(input, {
assertion: [],
clientId: [],
code: [],
codeVerifier: [],
grantType: [],
redirectUri: [],
refreshToken: [],
requestedTokenType: [],
scope: /* @__PURE__ */ __name((_4) => _json(_4), "scope"),
subjectToken: [],
subjectTokenType: []
}));
b6.m("POST").h(headers).q(query).b(body);
return b6.build();
}, "se_CreateTokenWithIAMCommand");
se_RegisterClientCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {
"content-type": "application/json"
};
b6.bp("/client/register");
let body;
body = JSON.stringify(take(input, {
clientName: [],
clientType: [],
entitledApplicationArn: [],
grantTypes: /* @__PURE__ */ __name((_4) => _json(_4), "grantTypes"),
issuerUrl: [],
redirectUris: /* @__PURE__ */ __name((_4) => _json(_4), "redirectUris"),
scopes: /* @__PURE__ */ __name((_4) => _json(_4), "scopes")
}));
b6.m("POST").h(headers).b(body);
return b6.build();
}, "se_RegisterClientCommand");
se_StartDeviceAuthorizationCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = {
"content-type": "application/json"
};
b6.bp("/device_authorization");
let body;
body = JSON.stringify(take(input, {
clientId: [],
clientSecret: [],
startUrl: []
}));
b6.m("POST").h(headers).b(body);
return b6.build();
}, "se_StartDeviceAuthorizationCommand");
de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError2(output, context2);
}
const contents = map({
$metadata: deserializeMetadata3(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
accessToken: expectString,
expiresIn: expectInt32,
idToken: expectString,
refreshToken: expectString,
tokenType: expectString
});
Object.assign(contents, doc);
return contents;
}, "de_CreateTokenCommand");
de_CreateTokenWithIAMCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError2(output, context2);
}
const contents = map({
$metadata: deserializeMetadata3(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
accessToken: expectString,
expiresIn: expectInt32,
idToken: expectString,
issuedTokenType: expectString,
refreshToken: expectString,
scope: _json,
tokenType: expectString
});
Object.assign(contents, doc);
return contents;
}, "de_CreateTokenWithIAMCommand");
de_RegisterClientCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError2(output, context2);
}
const contents = map({
$metadata: deserializeMetadata3(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
authorizationEndpoint: expectString,
clientId: expectString,
clientIdIssuedAt: expectLong,
clientSecret: expectString,
clientSecretExpiresAt: expectLong,
tokenEndpoint: expectString
});
Object.assign(contents, doc);
return contents;
}, "de_RegisterClientCommand");
de_StartDeviceAuthorizationCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError2(output, context2);
}
const contents = map({
$metadata: deserializeMetadata3(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
deviceCode: expectString,
expiresIn: expectInt32,
interval: expectInt32,
userCode: expectString,
verificationUri: expectString,
verificationUriComplete: expectString
});
Object.assign(contents, doc);
return contents;
}, "de_StartDeviceAuthorizationCommand");
de_CommandError2 = /* @__PURE__ */ __name(async (output, context2) => {
const parsedOutput = {
...output,
body: await parseJsonErrorBody(output.body, context2)
};
const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
switch (errorCode) {
case "AccessDeniedException":
case "com.amazonaws.ssooidc#AccessDeniedException":
throw await de_AccessDeniedExceptionRes(parsedOutput, context2);
case "AuthorizationPendingException":
case "com.amazonaws.ssooidc#AuthorizationPendingException":
throw await de_AuthorizationPendingExceptionRes(parsedOutput, context2);
case "ExpiredTokenException":
case "com.amazonaws.ssooidc#ExpiredTokenException":
throw await de_ExpiredTokenExceptionRes(parsedOutput, context2);
case "InternalServerException":
case "com.amazonaws.ssooidc#InternalServerException":
throw await de_InternalServerExceptionRes(parsedOutput, context2);
case "InvalidClientException":
case "com.amazonaws.ssooidc#InvalidClientException":
throw await de_InvalidClientExceptionRes(parsedOutput, context2);
case "InvalidGrantException":
case "com.amazonaws.ssooidc#InvalidGrantException":
throw await de_InvalidGrantExceptionRes(parsedOutput, context2);
case "InvalidRequestException":
case "com.amazonaws.ssooidc#InvalidRequestException":
throw await de_InvalidRequestExceptionRes(parsedOutput, context2);
case "InvalidScopeException":
case "com.amazonaws.ssooidc#InvalidScopeException":
throw await de_InvalidScopeExceptionRes(parsedOutput, context2);
case "SlowDownException":
case "com.amazonaws.ssooidc#SlowDownException":
throw await de_SlowDownExceptionRes(parsedOutput, context2);
case "UnauthorizedClientException":
case "com.amazonaws.ssooidc#UnauthorizedClientException":
throw await de_UnauthorizedClientExceptionRes(parsedOutput, context2);
case "UnsupportedGrantTypeException":
case "com.amazonaws.ssooidc#UnsupportedGrantTypeException":
throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context2);
case "InvalidRequestRegionException":
case "com.amazonaws.ssooidc#InvalidRequestRegionException":
throw await de_InvalidRequestRegionExceptionRes(parsedOutput, context2);
case "InvalidClientMetadataException":
case "com.amazonaws.ssooidc#InvalidClientMetadataException":
throw await de_InvalidClientMetadataExceptionRes(parsedOutput, context2);
case "InvalidRedirectUriException":
case "com.amazonaws.ssooidc#InvalidRedirectUriException":
throw await de_InvalidRedirectUriExceptionRes(parsedOutput, context2);
default:
const parsedBody = parsedOutput.body;
return throwDefaultError3({
output,
parsedBody,
errorCode
});
}
}, "de_CommandError");
throwDefaultError3 = withBaseException(SSOOIDCServiceException);
de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new AccessDeniedException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_AccessDeniedExceptionRes");
de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new AuthorizationPendingException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_AuthorizationPendingExceptionRes");
de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new ExpiredTokenException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_ExpiredTokenExceptionRes");
de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InternalServerException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InternalServerExceptionRes");
de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InvalidClientException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidClientExceptionRes");
de_InvalidClientMetadataExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InvalidClientMetadataException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidClientMetadataExceptionRes");
de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InvalidGrantException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidGrantExceptionRes");
de_InvalidRedirectUriExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InvalidRedirectUriException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidRedirectUriExceptionRes");
de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InvalidRequestException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidRequestExceptionRes");
de_InvalidRequestRegionExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
endpoint: expectString,
error: expectString,
error_description: expectString,
region: expectString
});
Object.assign(contents, doc);
const exception = new InvalidRequestRegionException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidRequestRegionExceptionRes");
de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new InvalidScopeException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidScopeExceptionRes");
de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new SlowDownException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_SlowDownExceptionRes");
de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new UnauthorizedClientException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_UnauthorizedClientExceptionRes");
de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
error: expectString,
error_description: expectString
});
Object.assign(contents, doc);
const exception = new UnsupportedGrantTypeException({
$metadata: deserializeMetadata3(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_UnsupportedGrantTypeExceptionRes");
deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"]
}), "deserializeMetadata");
_ai = "aws_iam";
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/CreateTokenCommand.js
var CreateTokenCommand;
var init_CreateTokenCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/CreateTokenCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters2();
init_models_02();
init_Aws_restJson1();
CreateTokenCommand = class extends Command.classBuilder().ep(commonParams2).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
static {
__name(this, "CreateTokenCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/CreateTokenWithIAMCommand.js
var CreateTokenWithIAMCommand;
var init_CreateTokenWithIAMCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/CreateTokenWithIAMCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters2();
init_models_02();
init_Aws_restJson1();
CreateTokenWithIAMCommand = class extends Command.classBuilder().ep(commonParams2).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSSOOIDCService", "CreateTokenWithIAM", {}).n("SSOOIDCClient", "CreateTokenWithIAMCommand").f(CreateTokenWithIAMRequestFilterSensitiveLog, CreateTokenWithIAMResponseFilterSensitiveLog).ser(se_CreateTokenWithIAMCommand).de(de_CreateTokenWithIAMCommand).build() {
static {
__name(this, "CreateTokenWithIAMCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/RegisterClientCommand.js
var RegisterClientCommand;
var init_RegisterClientCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/RegisterClientCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters2();
init_models_02();
init_Aws_restJson1();
RegisterClientCommand = class extends Command.classBuilder().ep(commonParams2).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSSOOIDCService", "RegisterClient", {}).n("SSOOIDCClient", "RegisterClientCommand").f(void 0, RegisterClientResponseFilterSensitiveLog).ser(se_RegisterClientCommand).de(de_RegisterClientCommand).build() {
static {
__name(this, "RegisterClientCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/StartDeviceAuthorizationCommand.js
var StartDeviceAuthorizationCommand;
var init_StartDeviceAuthorizationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/StartDeviceAuthorizationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters2();
init_models_02();
init_Aws_restJson1();
StartDeviceAuthorizationCommand = class extends Command.classBuilder().ep(commonParams2).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSSOOIDCService", "StartDeviceAuthorization", {}).n("SSOOIDCClient", "StartDeviceAuthorizationCommand").f(StartDeviceAuthorizationRequestFilterSensitiveLog, void 0).ser(se_StartDeviceAuthorizationCommand).de(de_StartDeviceAuthorizationCommand).build() {
static {
__name(this, "StartDeviceAuthorizationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/SSOOIDC.js
var commands, SSOOIDC;
var init_SSOOIDC = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/SSOOIDC.js"() {
init_import_meta_url();
init_dist_es20();
init_CreateTokenCommand();
init_CreateTokenWithIAMCommand();
init_RegisterClientCommand();
init_StartDeviceAuthorizationCommand();
init_SSOOIDCClient();
commands = {
CreateTokenCommand,
CreateTokenWithIAMCommand,
RegisterClientCommand,
StartDeviceAuthorizationCommand
};
SSOOIDC = class extends SSOOIDCClient {
static {
__name(this, "SSOOIDC");
}
};
createAggregatedClient(commands, SSOOIDC);
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/index.js
var init_commands2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/commands/index.js"() {
init_import_meta_url();
init_CreateTokenCommand();
init_CreateTokenWithIAMCommand();
init_RegisterClientCommand();
init_StartDeviceAuthorizationCommand();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/models/index.js
var init_models = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/models/index.js"() {
init_import_meta_url();
init_models_02();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/index.js
var dist_es_exports4 = {};
__export(dist_es_exports4, {
$Command: () => Command,
AccessDeniedException: () => AccessDeniedException,
AuthorizationPendingException: () => AuthorizationPendingException,
CreateTokenCommand: () => CreateTokenCommand,
CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
CreateTokenWithIAMCommand: () => CreateTokenWithIAMCommand,
CreateTokenWithIAMRequestFilterSensitiveLog: () => CreateTokenWithIAMRequestFilterSensitiveLog,
CreateTokenWithIAMResponseFilterSensitiveLog: () => CreateTokenWithIAMResponseFilterSensitiveLog,
ExpiredTokenException: () => ExpiredTokenException,
InternalServerException: () => InternalServerException,
InvalidClientException: () => InvalidClientException,
InvalidClientMetadataException: () => InvalidClientMetadataException,
InvalidGrantException: () => InvalidGrantException,
InvalidRedirectUriException: () => InvalidRedirectUriException,
InvalidRequestException: () => InvalidRequestException,
InvalidRequestRegionException: () => InvalidRequestRegionException,
InvalidScopeException: () => InvalidScopeException,
RegisterClientCommand: () => RegisterClientCommand,
RegisterClientResponseFilterSensitiveLog: () => RegisterClientResponseFilterSensitiveLog,
SSOOIDC: () => SSOOIDC,
SSOOIDCClient: () => SSOOIDCClient,
SSOOIDCServiceException: () => SSOOIDCServiceException,
SlowDownException: () => SlowDownException,
StartDeviceAuthorizationCommand: () => StartDeviceAuthorizationCommand,
StartDeviceAuthorizationRequestFilterSensitiveLog: () => StartDeviceAuthorizationRequestFilterSensitiveLog,
UnauthorizedClientException: () => UnauthorizedClientException,
UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
__Client: () => Client
});
var init_dist_es56 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sso-oidc/dist-es/index.js"() {
init_import_meta_url();
init_SSOOIDCClient();
init_SSOOIDC();
init_commands2();
init_models();
init_SSOOIDCServiceException();
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js
var getSsoOidcClient;
var init_getSsoOidcClient = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js"() {
init_import_meta_url();
getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init3 = {}) => {
const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_dist_es56(), dist_es_exports4));
const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init3.clientConfig ?? {}, {
region: ssoRegion ?? init3.clientConfig?.region,
logger: init3.clientConfig?.logger ?? init3.parentClientConfig?.logger
}));
return ssoOidcClient;
}, "getSsoOidcClient");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js
var getNewSsoOidcToken;
var init_getNewSsoOidcToken = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js"() {
init_import_meta_url();
init_getSsoOidcClient();
getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init3 = {}) => {
const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => (init_dist_es56(), dist_es_exports4));
const ssoOidcClient = await getSsoOidcClient(ssoRegion, init3);
return ssoOidcClient.send(new CreateTokenCommand2({
clientId: ssoToken.clientId,
clientSecret: ssoToken.clientSecret,
refreshToken: ssoToken.refreshToken,
grantType: "refresh_token"
}));
}, "getNewSsoOidcToken");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js
var validateTokenExpiry;
var init_validateTokenExpiry = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js"() {
init_import_meta_url();
init_dist_es17();
init_constants14();
validateTokenExpiry = /* @__PURE__ */ __name((token) => {
if (token.expiration && token.expiration.getTime() < Date.now()) {
throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
}
}, "validateTokenExpiry");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js
var validateTokenKey;
var init_validateTokenKey = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js"() {
init_import_meta_url();
init_dist_es17();
init_constants14();
validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => {
if (typeof value === "undefined") {
throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
}
}, "validateTokenKey");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js
var import_fs21, writeFile7, writeSSOTokenToFile;
var init_writeSSOTokenToFile = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js"() {
init_import_meta_url();
init_dist_es38();
import_fs21 = require("fs");
({ writeFile: writeFile7 } = import_fs21.promises);
writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => {
const tokenFilepath = getSSOTokenFilepath(id);
const tokenString = JSON.stringify(ssoToken, null, 2);
return writeFile7(tokenFilepath, tokenString);
}, "writeSSOTokenToFile");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js
var lastRefreshAttemptTime, fromSso;
var init_fromSso = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js"() {
init_import_meta_url();
init_dist_es17();
init_dist_es38();
init_constants14();
init_getNewSsoOidcToken();
init_validateTokenExpiry();
init_validateTokenKey();
init_writeSSOTokenToFile();
lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => {
const init3 = {
..._init,
parentClientConfig: {
...callerClientConfig,
..._init.parentClientConfig
}
};
init3.logger?.debug("@aws-sdk/token-providers - fromSso");
const profiles = await parseKnownFiles(init3);
const profileName = getProfileName({
profile: init3.profile ?? callerClientConfig?.profile
});
const profile = profiles[profileName];
if (!profile) {
throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
} else if (!profile["sso_session"]) {
throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
}
const ssoSessionName = profile["sso_session"];
const ssoSessions = await loadSsoSessionData(init3);
const ssoSession = ssoSessions[ssoSessionName];
if (!ssoSession) {
throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);
}
for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
if (!ssoSession[ssoSessionRequiredKey]) {
throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);
}
}
const ssoStartUrl = ssoSession["sso_start_url"];
const ssoRegion = ssoSession["sso_region"];
let ssoToken;
try {
ssoToken = await getSSOTokenFromFile(ssoSessionName);
} catch (e7) {
throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);
}
validateTokenKey("accessToken", ssoToken.accessToken);
validateTokenKey("expiresAt", ssoToken.expiresAt);
const { accessToken, expiresAt } = ssoToken;
const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
return existingToken;
}
if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) {
validateTokenExpiry(existingToken);
return existingToken;
}
validateTokenKey("clientId", ssoToken.clientId, true);
validateTokenKey("clientSecret", ssoToken.clientSecret, true);
validateTokenKey("refreshToken", ssoToken.refreshToken, true);
try {
lastRefreshAttemptTime.setTime(Date.now());
const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init3);
validateTokenKey("accessToken", newSsoOidcToken.accessToken);
validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3);
try {
await writeSSOTokenToFile(ssoSessionName, {
...ssoToken,
accessToken: newSsoOidcToken.accessToken,
expiresAt: newTokenExpiration.toISOString(),
refreshToken: newSsoOidcToken.refreshToken
});
} catch (error2) {
}
return {
token: newSsoOidcToken.accessToken,
expiration: newTokenExpiration
};
} catch (error2) {
validateTokenExpiry(existingToken);
return existingToken;
}
}, "fromSso");
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js
var init_fromStatic3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js"() {
init_import_meta_url();
init_dist_es17();
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js
var init_nodeProvider = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js"() {
init_import_meta_url();
init_dist_es17();
}
});
// ../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/index.js
var init_dist_es57 = __esm({
"../../node_modules/.pnpm/@aws-sdk+token-providers@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/token-providers/dist-es/index.js"() {
init_import_meta_url();
init_fromSso();
init_fromStatic3();
init_nodeProvider();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption3(authParameters) {
return {
schemeId: "aws.auth#sigv4",
signingProperties: {
name: "awsssoportal",
region: authParameters.region
},
propertiesExtractor: /* @__PURE__ */ __name((config, context2) => ({
signingProperties: {
config,
context: context2
}
}), "propertiesExtractor")
};
}
function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
return {
schemeId: "smithy.api#noAuth"
};
}
var defaultSSOHttpAuthSchemeParametersProvider, defaultSSOHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig3;
var init_httpAuthSchemeProvider3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthSchemeProvider.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es4();
defaultSSOHttpAuthSchemeParametersProvider = /* @__PURE__ */ __name(async (config, context2, input) => {
return {
operation: getSmithyContext(context2).operation,
region: await normalizeProvider(config.region)() || (() => {
throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
})()
};
}, "defaultSSOHttpAuthSchemeParametersProvider");
__name(createAwsAuthSigv4HttpAuthOption3, "createAwsAuthSigv4HttpAuthOption");
__name(createSmithyApiNoAuthHttpAuthOption2, "createSmithyApiNoAuthHttpAuthOption");
defaultSSOHttpAuthSchemeProvider = /* @__PURE__ */ __name((authParameters) => {
const options = [];
switch (authParameters.operation) {
case "GetRoleCredentials": {
options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
break;
}
case "ListAccountRoles": {
options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
break;
}
case "ListAccounts": {
options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
break;
}
case "Logout": {
options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
break;
}
default: {
options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
}
}
return options;
}, "defaultSSOHttpAuthSchemeProvider");
resolveHttpAuthSchemeConfig3 = /* @__PURE__ */ __name((config) => {
const config_0 = resolveAwsSdkSigV4Config(config);
return {
...config_0
};
}, "resolveHttpAuthSchemeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters3, commonParams3;
var init_EndpointParameters3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/EndpointParameters.js"() {
init_import_meta_url();
resolveClientEndpointParameters3 = /* @__PURE__ */ __name((options) => {
return {
...options,
useDualstackEndpoint: options.useDualstackEndpoint ?? false,
useFipsEndpoint: options.useFipsEndpoint ?? false,
defaultSigningName: "awsssoportal"
};
}, "resolveClientEndpointParameters");
commonParams3 = {
UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
Endpoint: { type: "builtInParams", name: "endpoint" },
Region: { type: "builtInParams", name: "region" },
UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/package.json
var package_default3;
var init_package4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/package.json"() {
package_default3 = {
name: "@aws-sdk/client-sso",
description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
version: "3.721.0",
scripts: {
build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
"build:cjs": "node ../../scripts/compilation/inline client-sso",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
"build:types": "tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
"extract:docs": "api-extractor run --local",
"generate:client": "node ../../scripts/generate-clients/single-service --solo sso"
},
main: "./dist-cjs/index.js",
types: "./dist-types/index.d.ts",
module: "./dist-es/index.js",
sideEffects: false,
dependencies: {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/core": "3.716.0",
"@aws-sdk/middleware-host-header": "3.714.0",
"@aws-sdk/middleware-logger": "3.714.0",
"@aws-sdk/middleware-recursion-detection": "3.714.0",
"@aws-sdk/middleware-user-agent": "3.721.0",
"@aws-sdk/region-config-resolver": "3.714.0",
"@aws-sdk/types": "3.714.0",
"@aws-sdk/util-endpoints": "3.714.0",
"@aws-sdk/util-user-agent-browser": "3.714.0",
"@aws-sdk/util-user-agent-node": "3.721.0",
"@smithy/config-resolver": "^3.0.13",
"@smithy/core": "^2.5.5",
"@smithy/fetch-http-handler": "^4.1.2",
"@smithy/hash-node": "^3.0.11",
"@smithy/invalid-dependency": "^3.0.11",
"@smithy/middleware-content-length": "^3.0.13",
"@smithy/middleware-endpoint": "^3.2.6",
"@smithy/middleware-retry": "^3.0.31",
"@smithy/middleware-serde": "^3.0.11",
"@smithy/middleware-stack": "^3.0.11",
"@smithy/node-config-provider": "^3.1.12",
"@smithy/node-http-handler": "^3.3.2",
"@smithy/protocol-http": "^4.1.8",
"@smithy/smithy-client": "^3.5.1",
"@smithy/types": "^3.7.2",
"@smithy/url-parser": "^3.0.11",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.31",
"@smithy/util-defaults-mode-node": "^3.0.31",
"@smithy/util-endpoints": "^2.1.7",
"@smithy/util-middleware": "^3.0.11",
"@smithy/util-retry": "^3.0.11",
"@smithy/util-utf8": "^3.0.0",
tslib: "^2.6.2"
},
devDependencies: {
"@tsconfig/node16": "16.1.3",
"@types/node": "^16.18.96",
concurrently: "7.0.0",
"downlevel-dts": "0.10.1",
rimraf: "3.0.2",
typescript: "~4.9.5"
},
engines: {
node: ">=16.0.0"
},
typesVersions: {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
files: [
"dist-*/**"
],
author: {
name: "AWS SDK for JavaScript Team",
url: "https://aws.amazon.com/javascript/"
},
license: "Apache-2.0",
browser: {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
},
"react-native": {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
},
homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso",
repository: {
type: "git",
url: "https://github.com/aws/aws-sdk-js-v3.git",
directory: "clients/client-sso"
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js
var u3, v5, w4, x4, a3, b4, c4, d4, e4, f4, g4, h4, i3, j4, k4, l4, m4, n3, o3, p4, q4, r4, s3, t4, _data3, ruleSet3;
var init_ruleset3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js"() {
init_import_meta_url();
u3 = "required";
v5 = "fn";
w4 = "argv";
x4 = "ref";
a3 = true;
b4 = "isSet";
c4 = "booleanEquals";
d4 = "error";
e4 = "endpoint";
f4 = "tree";
g4 = "PartitionResult";
h4 = "getAttr";
i3 = { [u3]: false, "type": "String" };
j4 = { [u3]: true, "default": false, "type": "Boolean" };
k4 = { [x4]: "Endpoint" };
l4 = { [v5]: c4, [w4]: [{ [x4]: "UseFIPS" }, true] };
m4 = { [v5]: c4, [w4]: [{ [x4]: "UseDualStack" }, true] };
n3 = {};
o3 = { [v5]: h4, [w4]: [{ [x4]: g4 }, "supportsFIPS"] };
p4 = { [x4]: g4 };
q4 = { [v5]: c4, [w4]: [true, { [v5]: h4, [w4]: [p4, "supportsDualStack"] }] };
r4 = [l4];
s3 = [m4];
t4 = [{ [x4]: "Region" }];
_data3 = { version: "1.0", parameters: { Region: i3, UseDualStack: j4, UseFIPS: j4, Endpoint: i3 }, rules: [{ conditions: [{ [v5]: b4, [w4]: [k4] }], rules: [{ conditions: r4, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d4 }, { conditions: s3, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d4 }, { endpoint: { url: k4, properties: n3, headers: n3 }, type: e4 }], type: f4 }, { conditions: [{ [v5]: b4, [w4]: t4 }], rules: [{ conditions: [{ [v5]: "aws.partition", [w4]: t4, assign: g4 }], rules: [{ conditions: [l4, m4], rules: [{ conditions: [{ [v5]: c4, [w4]: [a3, o3] }, q4], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f4 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d4 }], type: f4 }, { conditions: r4, rules: [{ conditions: [{ [v5]: c4, [w4]: [o3, a3] }], rules: [{ conditions: [{ [v5]: "stringEquals", [w4]: [{ [v5]: h4, [w4]: [p4, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n3, headers: n3 }, type: e4 }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f4 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d4 }], type: f4 }, { conditions: s3, rules: [{ conditions: [q4], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f4 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d4 }], type: f4 }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f4 }], type: f4 }, { error: "Invalid Configuration: Missing Region", type: d4 }] };
ruleSet3 = _data3;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js
var cache4, defaultEndpointResolver3;
var init_endpointResolver3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js"() {
init_import_meta_url();
init_dist_es33();
init_dist_es32();
init_ruleset3();
cache4 = new EndpointCache({
size: 50,
params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
});
defaultEndpointResolver3 = /* @__PURE__ */ __name((endpointParams, context2 = {}) => {
return cache4.get(endpointParams, () => resolveEndpoint(ruleSet3, {
endpointParams,
logger: context2.logger
}));
}, "defaultEndpointResolver");
customEndpointFunctions.aws = awsEndpointFunctions;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js
var getRuntimeConfig3;
var init_runtimeConfig_shared2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es16();
init_dist_es20();
init_dist_es41();
init_dist_es9();
init_dist_es8();
init_httpAuthSchemeProvider3();
init_endpointResolver3();
getRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
return {
apiVersion: "2019-06-10",
base64Decoder: config?.base64Decoder ?? fromBase64,
base64Encoder: config?.base64Encoder ?? toBase64,
disableHostPrefix: config?.disableHostPrefix ?? false,
endpointProvider: config?.endpointProvider ?? defaultEndpointResolver3,
extensions: config?.extensions ?? [],
httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), "identityProvider"),
signer: new AwsSdkSigV4Signer()
},
{
schemeId: "smithy.api#noAuth",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), "identityProvider"),
signer: new NoAuthSigner()
}
],
logger: config?.logger ?? new NoOpLogger(),
serviceId: config?.serviceId ?? "SSO",
urlParser: config?.urlParser ?? parseUrl,
utf8Decoder: config?.utf8Decoder ?? fromUtf8,
utf8Encoder: config?.utf8Encoder ?? toUtf8
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js
var getRuntimeConfig4;
var init_runtimeConfig2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js"() {
init_import_meta_url();
init_package4();
init_dist_es21();
init_dist_es51();
init_dist_es35();
init_dist_es52();
init_dist_es45();
init_dist_es39();
init_dist_es12();
init_dist_es53();
init_dist_es44();
init_runtimeConfig_shared2();
init_dist_es20();
init_dist_es54();
init_dist_es20();
getRuntimeConfig4 = /* @__PURE__ */ __name((config) => {
emitWarningIfUnsupportedVersion2(process.version);
const defaultsMode = resolveDefaultsModeConfig(config);
const defaultConfigProvider = /* @__PURE__ */ __name(() => defaultsMode().then(loadConfigsForDefaultMode), "defaultConfigProvider");
const clientSharedValues = getRuntimeConfig3(config);
emitWarningIfUnsupportedVersion(process.version);
const profileConfig = { profile: config?.profile };
return {
...clientSharedValues,
...config,
runtime: "node",
defaultsMode,
bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default3.version }),
maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...profileConfig }),
requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
retryMode: config?.retryMode ?? loadConfig({
...NODE_RETRY_MODE_CONFIG_OPTIONS,
default: /* @__PURE__ */ __name(async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, "default")
}, config),
sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
streamCollector: config?.streamCollector ?? streamCollector,
useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, profileConfig),
useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, profileConfig),
userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, profileConfig)
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2;
var init_httpAuthExtensionConfiguration2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js"() {
init_import_meta_url();
getHttpAuthExtensionConfiguration2 = /* @__PURE__ */ __name((runtimeConfig) => {
const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
let _credentials = runtimeConfig.credentials;
return {
setHttpAuthScheme(httpAuthScheme) {
const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
if (index === -1) {
_httpAuthSchemes.push(httpAuthScheme);
} else {
_httpAuthSchemes.splice(index, 1, httpAuthScheme);
}
},
httpAuthSchemes() {
return _httpAuthSchemes;
},
setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
_httpAuthSchemeProvider = httpAuthSchemeProvider;
},
httpAuthSchemeProvider() {
return _httpAuthSchemeProvider;
},
setCredentials(credentials) {
_credentials = credentials;
},
credentials() {
return _credentials;
}
};
}, "getHttpAuthExtensionConfiguration");
resolveHttpAuthRuntimeConfig2 = /* @__PURE__ */ __name((config) => {
return {
httpAuthSchemes: config.httpAuthSchemes(),
httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
credentials: config.credentials()
};
}, "resolveHttpAuthRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js
var asPartial2, resolveRuntimeExtensions2;
var init_runtimeExtensions2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js"() {
init_import_meta_url();
init_dist_es55();
init_dist_es2();
init_dist_es20();
init_httpAuthExtensionConfiguration2();
asPartial2 = /* @__PURE__ */ __name((t7) => t7, "asPartial");
resolveRuntimeExtensions2 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
const extensionConfiguration = {
...asPartial2(getAwsRegionExtensionConfiguration(runtimeConfig)),
...asPartial2(getDefaultExtensionConfiguration(runtimeConfig)),
...asPartial2(getHttpHandlerExtensionConfiguration(runtimeConfig)),
...asPartial2(getHttpAuthExtensionConfiguration2(runtimeConfig))
};
extensions.forEach((extension) => extension.configure(extensionConfiguration));
return {
...runtimeConfig,
...resolveAwsRegionExtensionConfiguration(extensionConfiguration),
...resolveDefaultRuntimeConfig(extensionConfiguration),
...resolveHttpHandlerRuntimeConfig(extensionConfiguration),
...resolveHttpAuthRuntimeConfig2(extensionConfiguration)
};
}, "resolveRuntimeExtensions");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js
var SSOClient;
var init_SSOClient = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js"() {
init_import_meta_url();
init_dist_es26();
init_dist_es27();
init_dist_es28();
init_dist_es34();
init_dist_es35();
init_dist_es16();
init_dist_es37();
init_dist_es42();
init_dist_es45();
init_dist_es20();
init_httpAuthSchemeProvider3();
init_EndpointParameters3();
init_runtimeConfig2();
init_runtimeExtensions2();
SSOClient = class extends Client {
static {
__name(this, "SSOClient");
}
constructor(...[configuration]) {
const _config_0 = getRuntimeConfig4(configuration || {});
const _config_1 = resolveClientEndpointParameters3(_config_0);
const _config_2 = resolveUserAgentConfig(_config_1);
const _config_3 = resolveRetryConfig(_config_2);
const _config_4 = resolveRegionConfig(_config_3);
const _config_5 = resolveHostHeaderConfig(_config_4);
const _config_6 = resolveEndpointConfig(_config_5);
const _config_7 = resolveHttpAuthSchemeConfig3(_config_6);
const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []);
super(_config_8);
this.config = _config_8;
this.middlewareStack.use(getUserAgentPlugin(this.config));
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,
identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new DefaultIdentityProviderConfig({
"aws.auth#sigv4": config.credentials
}), "identityProviderConfigProvider")
}));
this.middlewareStack.use(getHttpSigningPlugin(this.config));
}
destroy() {
super.destroy();
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/models/SSOServiceException.js
var SSOServiceException;
var init_SSOServiceException = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/models/SSOServiceException.js"() {
init_import_meta_url();
init_dist_es20();
SSOServiceException = class _SSOServiceException extends ServiceException {
static {
__name(this, "SSOServiceException");
}
constructor(options) {
super(options);
Object.setPrototypeOf(this, _SSOServiceException.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/models/models_0.js
var InvalidRequestException2, ResourceNotFoundException, TooManyRequestsException, UnauthorizedException, GetRoleCredentialsRequestFilterSensitiveLog, RoleCredentialsFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog, ListAccountRolesRequestFilterSensitiveLog, ListAccountsRequestFilterSensitiveLog, LogoutRequestFilterSensitiveLog;
var init_models_03 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/models/models_0.js"() {
init_import_meta_url();
init_dist_es20();
init_SSOServiceException();
InvalidRequestException2 = class _InvalidRequestException extends SSOServiceException {
static {
__name(this, "InvalidRequestException");
}
constructor(opts) {
super({
name: "InvalidRequestException",
$fault: "client",
...opts
});
this.name = "InvalidRequestException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidRequestException.prototype);
}
};
ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException {
static {
__name(this, "ResourceNotFoundException");
}
constructor(opts) {
super({
name: "ResourceNotFoundException",
$fault: "client",
...opts
});
this.name = "ResourceNotFoundException";
this.$fault = "client";
Object.setPrototypeOf(this, _ResourceNotFoundException.prototype);
}
};
TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException {
static {
__name(this, "TooManyRequestsException");
}
constructor(opts) {
super({
name: "TooManyRequestsException",
$fault: "client",
...opts
});
this.name = "TooManyRequestsException";
this.$fault = "client";
Object.setPrototypeOf(this, _TooManyRequestsException.prototype);
}
};
UnauthorizedException = class _UnauthorizedException extends SSOServiceException {
static {
__name(this, "UnauthorizedException");
}
constructor(opts) {
super({
name: "UnauthorizedException",
$fault: "client",
...opts
});
this.name = "UnauthorizedException";
this.$fault = "client";
Object.setPrototypeOf(this, _UnauthorizedException.prototype);
}
};
GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.accessToken && { accessToken: SENSITIVE_STRING }
}), "GetRoleCredentialsRequestFilterSensitiveLog");
RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.secretAccessKey && { secretAccessKey: SENSITIVE_STRING },
...obj.sessionToken && { sessionToken: SENSITIVE_STRING }
}), "RoleCredentialsFilterSensitiveLog");
GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }
}), "GetRoleCredentialsResponseFilterSensitiveLog");
ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.accessToken && { accessToken: SENSITIVE_STRING }
}), "ListAccountRolesRequestFilterSensitiveLog");
ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.accessToken && { accessToken: SENSITIVE_STRING }
}), "ListAccountsRequestFilterSensitiveLog");
LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.accessToken && { accessToken: SENSITIVE_STRING }
}), "LogoutRequestFilterSensitiveLog");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/protocols/Aws_restJson1.js
var se_GetRoleCredentialsCommand, se_ListAccountRolesCommand, se_ListAccountsCommand, se_LogoutCommand, de_GetRoleCredentialsCommand, de_ListAccountRolesCommand, de_ListAccountsCommand, de_LogoutCommand, de_CommandError3, throwDefaultError4, de_InvalidRequestExceptionRes2, de_ResourceNotFoundExceptionRes, de_TooManyRequestsExceptionRes, de_UnauthorizedExceptionRes, deserializeMetadata4, _aI, _aT, _ai2, _mR, _mr, _nT, _nt, _rN, _rn, _xasbt;
var init_Aws_restJson12 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/protocols/Aws_restJson1.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es16();
init_dist_es20();
init_models_03();
init_SSOServiceException();
se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xasbt]: input[_aT]
});
b6.bp("/federation/credentials");
const query = map({
[_rn]: [, expectNonNull(input[_rN], `roleName`)],
[_ai2]: [, expectNonNull(input[_aI], `accountId`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_GetRoleCredentialsCommand");
se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xasbt]: input[_aT]
});
b6.bp("/assignment/roles");
const query = map({
[_nt]: [, input[_nT]],
[_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
[_ai2]: [, expectNonNull(input[_aI], `accountId`)]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListAccountRolesCommand");
se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xasbt]: input[_aT]
});
b6.bp("/assignment/accounts");
const query = map({
[_nt]: [, input[_nT]],
[_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()]
});
let body;
b6.m("GET").h(headers).q(query).b(body);
return b6.build();
}, "se_ListAccountsCommand");
se_LogoutCommand = /* @__PURE__ */ __name(async (input, context2) => {
const b6 = requestBuilder(input, context2);
const headers = map({}, isSerializableHeaderValue, {
[_xasbt]: input[_aT]
});
b6.bp("/logout");
let body;
b6.m("POST").h(headers).b(body);
return b6.build();
}, "se_LogoutCommand");
de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError3(output, context2);
}
const contents = map({
$metadata: deserializeMetadata4(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
roleCredentials: _json
});
Object.assign(contents, doc);
return contents;
}, "de_GetRoleCredentialsCommand");
de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError3(output, context2);
}
const contents = map({
$metadata: deserializeMetadata4(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
nextToken: expectString,
roleList: _json
});
Object.assign(contents, doc);
return contents;
}, "de_ListAccountRolesCommand");
de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError3(output, context2);
}
const contents = map({
$metadata: deserializeMetadata4(output)
});
const data = expectNonNull(expectObject(await parseJsonBody(output.body, context2)), "body");
const doc = take(data, {
accountList: _json,
nextToken: expectString
});
Object.assign(contents, doc);
return contents;
}, "de_ListAccountsCommand");
de_LogoutCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode !== 200 && output.statusCode >= 300) {
return de_CommandError3(output, context2);
}
const contents = map({
$metadata: deserializeMetadata4(output)
});
await collectBody(output.body, context2);
return contents;
}, "de_LogoutCommand");
de_CommandError3 = /* @__PURE__ */ __name(async (output, context2) => {
const parsedOutput = {
...output,
body: await parseJsonErrorBody(output.body, context2)
};
const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
switch (errorCode) {
case "InvalidRequestException":
case "com.amazonaws.sso#InvalidRequestException":
throw await de_InvalidRequestExceptionRes2(parsedOutput, context2);
case "ResourceNotFoundException":
case "com.amazonaws.sso#ResourceNotFoundException":
throw await de_ResourceNotFoundExceptionRes(parsedOutput, context2);
case "TooManyRequestsException":
case "com.amazonaws.sso#TooManyRequestsException":
throw await de_TooManyRequestsExceptionRes(parsedOutput, context2);
case "UnauthorizedException":
case "com.amazonaws.sso#UnauthorizedException":
throw await de_UnauthorizedExceptionRes(parsedOutput, context2);
default:
const parsedBody = parsedOutput.body;
return throwDefaultError4({
output,
parsedBody,
errorCode
});
}
}, "de_CommandError");
throwDefaultError4 = withBaseException(SSOServiceException);
de_InvalidRequestExceptionRes2 = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
message: expectString
});
Object.assign(contents, doc);
const exception = new InvalidRequestException2({
$metadata: deserializeMetadata4(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_InvalidRequestExceptionRes");
de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
message: expectString
});
Object.assign(contents, doc);
const exception = new ResourceNotFoundException({
$metadata: deserializeMetadata4(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_ResourceNotFoundExceptionRes");
de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
message: expectString
});
Object.assign(contents, doc);
const exception = new TooManyRequestsException({
$metadata: deserializeMetadata4(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_TooManyRequestsExceptionRes");
de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const contents = map({});
const data = parsedOutput.body;
const doc = take(data, {
message: expectString
});
Object.assign(contents, doc);
const exception = new UnauthorizedException({
$metadata: deserializeMetadata4(parsedOutput),
...contents
});
return decorateServiceException(exception, parsedOutput.body);
}, "de_UnauthorizedExceptionRes");
deserializeMetadata4 = /* @__PURE__ */ __name((output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"]
}), "deserializeMetadata");
_aI = "accountId";
_aT = "accessToken";
_ai2 = "account_id";
_mR = "maxResults";
_mr = "max_result";
_nT = "nextToken";
_nt = "next_token";
_rN = "roleName";
_rn = "role_name";
_xasbt = "x-amz-sso_bearer_token";
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js
var GetRoleCredentialsCommand;
var init_GetRoleCredentialsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters3();
init_models_03();
init_Aws_restJson12();
GetRoleCredentialsCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() {
static {
__name(this, "GetRoleCredentialsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountRolesCommand.js
var ListAccountRolesCommand;
var init_ListAccountRolesCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountRolesCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters3();
init_models_03();
init_Aws_restJson12();
ListAccountRolesCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() {
static {
__name(this, "ListAccountRolesCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountsCommand.js
var ListAccountsCommand;
var init_ListAccountsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/ListAccountsCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters3();
init_models_03();
init_Aws_restJson12();
ListAccountsCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() {
static {
__name(this, "ListAccountsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/LogoutCommand.js
var LogoutCommand;
var init_LogoutCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/LogoutCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters3();
init_models_03();
init_Aws_restJson12();
LogoutCommand = class extends Command.classBuilder().ep(commonParams3).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() {
static {
__name(this, "LogoutCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/SSO.js
var commands2, SSO;
var init_SSO = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/SSO.js"() {
init_import_meta_url();
init_dist_es20();
init_GetRoleCredentialsCommand();
init_ListAccountRolesCommand();
init_ListAccountsCommand();
init_LogoutCommand();
init_SSOClient();
commands2 = {
GetRoleCredentialsCommand,
ListAccountRolesCommand,
ListAccountsCommand,
LogoutCommand
};
SSO = class extends SSOClient {
static {
__name(this, "SSO");
}
};
createAggregatedClient(commands2, SSO);
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/index.js
var init_commands3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/commands/index.js"() {
init_import_meta_url();
init_GetRoleCredentialsCommand();
init_ListAccountRolesCommand();
init_ListAccountsCommand();
init_LogoutCommand();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/Interfaces.js
var init_Interfaces = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/Interfaces.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js
var paginateListAccountRoles;
var init_ListAccountRolesPaginator = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js"() {
init_import_meta_url();
init_dist_es16();
init_ListAccountRolesCommand();
init_SSOClient();
paginateListAccountRoles = createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js
var paginateListAccounts;
var init_ListAccountsPaginator = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js"() {
init_import_meta_url();
init_dist_es16();
init_ListAccountsCommand();
init_SSOClient();
paginateListAccounts = createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js
var init_pagination2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js"() {
init_import_meta_url();
init_Interfaces();
init_ListAccountRolesPaginator();
init_ListAccountsPaginator();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/models/index.js
var init_models2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/models/index.js"() {
init_import_meta_url();
init_models_03();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/index.js
var init_dist_es58 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sso@3.721.0/node_modules/@aws-sdk/client-sso/dist-es/index.js"() {
init_import_meta_url();
init_SSOClient();
init_SSO();
init_commands3();
init_pagination2();
init_models2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js
var loadSso_exports = {};
__export(loadSso_exports, {
GetRoleCredentialsCommand: () => GetRoleCredentialsCommand,
SSOClient: () => SSOClient
});
var init_loadSso = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js"() {
init_import_meta_url();
init_dist_es58();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js
var SHOULD_FAIL_CREDENTIAL_CHAIN, resolveSSOCredentials;
var init_resolveSSOCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js"() {
init_import_meta_url();
init_client5();
init_dist_es57();
init_dist_es17();
init_dist_es38();
SHOULD_FAIL_CREDENTIAL_CHAIN = false;
resolveSSOCredentials = /* @__PURE__ */ __name(async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, profile, logger: logger4 }) => {
let token;
const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
if (ssoSession) {
try {
const _token = await fromSso({ profile })();
token = {
accessToken: _token.token,
expiresAt: new Date(_token.expiration).toISOString()
};
} catch (e7) {
throw new CredentialsProviderError(e7.message, {
tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
logger: logger4
});
}
} else {
try {
token = await getSSOTokenFromFile(ssoStartUrl);
} catch (e7) {
throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
logger: logger4
});
}
}
if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
logger: logger4
});
}
const { accessToken } = token;
const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
const sso = ssoClient || new SSOClient2(Object.assign({}, clientConfig ?? {}, {
logger: clientConfig?.logger ?? parentClientConfig?.logger,
region: clientConfig?.region ?? ssoRegion
}));
let ssoResp;
try {
ssoResp = await sso.send(new GetRoleCredentialsCommand2({
accountId: ssoAccountId,
roleName: ssoRoleName,
accessToken
}));
} catch (e7) {
throw new CredentialsProviderError(e7, {
tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
logger: logger4
});
}
const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp;
if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
throw new CredentialsProviderError("SSO returns an invalid temporary credential.", {
tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
logger: logger4
});
}
const credentials = {
accessKeyId,
secretAccessKey,
sessionToken,
expiration: new Date(expiration),
...credentialScope && { credentialScope },
...accountId && { accountId }
};
if (ssoSession) {
setCredentialFeature(credentials, "CREDENTIALS_SSO", "s");
} else {
setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u");
}
return credentials;
}, "resolveSSOCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js
var validateSsoProfile;
var init_validateSsoProfile = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"() {
init_import_meta_url();
init_dist_es17();
validateSsoProfile = /* @__PURE__ */ __name((profile, logger4) => {
const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;
if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger4 });
}
return profile;
}, "validateSsoProfile");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js
var fromSSO;
var init_fromSSO = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js"() {
init_import_meta_url();
init_dist_es17();
init_dist_es38();
init_isSsoProfile();
init_resolveSSOCredentials();
init_validateSsoProfile();
fromSSO = /* @__PURE__ */ __name((init3 = {}) => async ({ callerClientConfig } = {}) => {
init3.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");
const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init3;
const { ssoClient } = init3;
const profileName = getProfileName({
profile: init3.profile ?? callerClientConfig?.profile
});
if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
const profiles = await parseKnownFiles(init3);
const profile = profiles[profileName];
if (!profile) {
throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init3.logger });
}
if (!isSsoProfile(profile)) {
throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {
logger: init3.logger
});
}
if (profile?.sso_session) {
const ssoSessions = await loadSsoSessionData(init3);
const session = ssoSessions[profile.sso_session];
const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;
if (ssoRegion && ssoRegion !== session.sso_region) {
throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {
tryNextLink: false,
logger: init3.logger
});
}
if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {
tryNextLink: false,
logger: init3.logger
});
}
profile.sso_region = session.sso_region;
profile.sso_start_url = session.sso_start_url;
}
const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init3.logger);
return resolveSSOCredentials({
ssoStartUrl: sso_start_url,
ssoSession: sso_session,
ssoAccountId: sso_account_id,
ssoRegion: sso_region,
ssoRoleName: sso_role_name,
ssoClient,
clientConfig: init3.clientConfig,
parentClientConfig: init3.parentClientConfig,
profile: profileName
});
} else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
throw new CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init3.logger });
} else {
return resolveSSOCredentials({
ssoStartUrl,
ssoSession,
ssoAccountId,
ssoRegion,
ssoRoleName,
ssoClient,
clientConfig: init3.clientConfig,
parentClientConfig: init3.parentClientConfig,
profile: profileName
});
}
}, "fromSSO");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js
var init_types13 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js
var dist_es_exports5 = {};
__export(dist_es_exports5, {
fromSSO: () => fromSSO,
isSsoProfile: () => isSsoProfile,
validateSsoProfile: () => validateSsoProfile
});
var init_dist_es59 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts@3.721.0_/node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js"() {
init_import_meta_url();
init_fromSSO();
init_isSsoProfile();
init_types13();
init_validateSsoProfile();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js
var resolveCredentialSource, setNamedProvider;
var init_resolveCredentialSource = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js"() {
init_import_meta_url();
init_client5();
init_dist_es17();
resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger4) => {
const sourceProvidersMap = {
EcsContainer: /* @__PURE__ */ __name(async (options) => {
const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es50(), dist_es_exports3));
const { fromContainerMetadata: fromContainerMetadata2 } = await Promise.resolve().then(() => (init_dist_es49(), dist_es_exports2));
logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
return async () => chain(fromHttp2(options ?? {}), fromContainerMetadata2(options))().then(setNamedProvider);
}, "EcsContainer"),
Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => {
logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
const { fromInstanceMetadata: fromInstanceMetadata2 } = await Promise.resolve().then(() => (init_dist_es49(), dist_es_exports2));
return async () => fromInstanceMetadata2(options)().then(setNamedProvider);
}, "Ec2InstanceMetadata"),
Environment: /* @__PURE__ */ __name(async (options) => {
logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
const { fromEnv: fromEnv3 } = await Promise.resolve().then(() => (init_dist_es48(), dist_es_exports));
return async () => fromEnv3(options)().then(setNamedProvider);
}, "Environment")
};
if (credentialSource in sourceProvidersMap) {
return sourceProvidersMap[credentialSource];
} else {
throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger4 });
}
}, "resolveCredentialSource");
setNamedProvider = /* @__PURE__ */ __name((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption4(authParameters) {
return {
schemeId: "aws.auth#sigv4",
signingProperties: {
name: "sts",
region: authParameters.region
},
propertiesExtractor: /* @__PURE__ */ __name((config, context2) => ({
signingProperties: {
config,
context: context2
}
}), "propertiesExtractor")
};
}
function createSmithyApiNoAuthHttpAuthOption3(authParameters) {
return {
schemeId: "smithy.api#noAuth"
};
}
var defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig4;
var init_httpAuthSchemeProvider4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthSchemeProvider.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es4();
init_STSClient();
defaultSTSHttpAuthSchemeParametersProvider = /* @__PURE__ */ __name(async (config, context2, input) => {
return {
operation: getSmithyContext(context2).operation,
region: await normalizeProvider(config.region)() || (() => {
throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
})()
};
}, "defaultSTSHttpAuthSchemeParametersProvider");
__name(createAwsAuthSigv4HttpAuthOption4, "createAwsAuthSigv4HttpAuthOption");
__name(createSmithyApiNoAuthHttpAuthOption3, "createSmithyApiNoAuthHttpAuthOption");
defaultSTSHttpAuthSchemeProvider = /* @__PURE__ */ __name((authParameters) => {
const options = [];
switch (authParameters.operation) {
case "AssumeRoleWithSAML": {
options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
break;
}
case "AssumeRoleWithWebIdentity": {
options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
break;
}
default: {
options.push(createAwsAuthSigv4HttpAuthOption4(authParameters));
}
}
return options;
}, "defaultSTSHttpAuthSchemeProvider");
resolveStsAuthConfig = /* @__PURE__ */ __name((input) => ({
...input,
stsClientCtor: STSClient
}), "resolveStsAuthConfig");
resolveHttpAuthSchemeConfig4 = /* @__PURE__ */ __name((config) => {
const config_0 = resolveStsAuthConfig(config);
const config_1 = resolveAwsSdkSigV4Config(config_0);
return {
...config_1
};
}, "resolveHttpAuthSchemeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters4, commonParams4;
var init_EndpointParameters4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/endpoint/EndpointParameters.js"() {
init_import_meta_url();
resolveClientEndpointParameters4 = /* @__PURE__ */ __name((options) => {
return {
...options,
useDualstackEndpoint: options.useDualstackEndpoint ?? false,
useFipsEndpoint: options.useFipsEndpoint ?? false,
useGlobalEndpoint: options.useGlobalEndpoint ?? false,
defaultSigningName: "sts"
};
}, "resolveClientEndpointParameters");
commonParams4 = {
UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
Endpoint: { type: "builtInParams", name: "endpoint" },
Region: { type: "builtInParams", name: "region" },
UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/package.json
var package_default4;
var init_package5 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/package.json"() {
package_default4 = {
name: "@aws-sdk/client-sts",
description: "AWS SDK for JavaScript Sts Client for Node.js, Browser and React Native",
version: "3.721.0",
scripts: {
build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
"build:cjs": "node ../../scripts/compilation/inline client-sts",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
"build:types": "rimraf ./dist-types tsconfig.types.tsbuildinfo && tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
"extract:docs": "api-extractor run --local",
"generate:client": "node ../../scripts/generate-clients/single-service --solo sts",
test: "yarn g:vitest run",
"test:watch": "yarn g:vitest watch"
},
main: "./dist-cjs/index.js",
types: "./dist-types/index.d.ts",
module: "./dist-es/index.js",
sideEffects: false,
dependencies: {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/client-sso-oidc": "3.721.0",
"@aws-sdk/core": "3.716.0",
"@aws-sdk/credential-provider-node": "3.721.0",
"@aws-sdk/middleware-host-header": "3.714.0",
"@aws-sdk/middleware-logger": "3.714.0",
"@aws-sdk/middleware-recursion-detection": "3.714.0",
"@aws-sdk/middleware-user-agent": "3.721.0",
"@aws-sdk/region-config-resolver": "3.714.0",
"@aws-sdk/types": "3.714.0",
"@aws-sdk/util-endpoints": "3.714.0",
"@aws-sdk/util-user-agent-browser": "3.714.0",
"@aws-sdk/util-user-agent-node": "3.721.0",
"@smithy/config-resolver": "^3.0.13",
"@smithy/core": "^2.5.5",
"@smithy/fetch-http-handler": "^4.1.2",
"@smithy/hash-node": "^3.0.11",
"@smithy/invalid-dependency": "^3.0.11",
"@smithy/middleware-content-length": "^3.0.13",
"@smithy/middleware-endpoint": "^3.2.6",
"@smithy/middleware-retry": "^3.0.31",
"@smithy/middleware-serde": "^3.0.11",
"@smithy/middleware-stack": "^3.0.11",
"@smithy/node-config-provider": "^3.1.12",
"@smithy/node-http-handler": "^3.3.2",
"@smithy/protocol-http": "^4.1.8",
"@smithy/smithy-client": "^3.5.1",
"@smithy/types": "^3.7.2",
"@smithy/url-parser": "^3.0.11",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.31",
"@smithy/util-defaults-mode-node": "^3.0.31",
"@smithy/util-endpoints": "^2.1.7",
"@smithy/util-middleware": "^3.0.11",
"@smithy/util-retry": "^3.0.11",
"@smithy/util-utf8": "^3.0.0",
tslib: "^2.6.2"
},
devDependencies: {
"@tsconfig/node16": "16.1.3",
"@types/node": "^16.18.96",
concurrently: "7.0.0",
"downlevel-dts": "0.10.1",
rimraf: "3.0.2",
typescript: "~4.9.5"
},
engines: {
node: ">=16.0.0"
},
typesVersions: {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
files: [
"dist-*/**"
],
author: {
name: "AWS SDK for JavaScript Team",
url: "https://aws.amazon.com/javascript/"
},
license: "Apache-2.0",
browser: {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
},
"react-native": {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
},
homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sts",
repository: {
type: "git",
url: "https://github.com/aws/aws-sdk-js-v3.git",
directory: "clients/client-sts"
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/endpoint/ruleset.js
var F2, G3, H3, I3, J3, a4, b5, c5, d5, e5, f5, g5, h5, i4, j5, k5, l5, m5, n4, o4, p5, q5, r5, s4, t5, u4, v6, w5, x5, y3, z4, A2, B2, C2, D2, E2, _data4, ruleSet4;
var init_ruleset4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/endpoint/ruleset.js"() {
init_import_meta_url();
F2 = "required";
G3 = "type";
H3 = "fn";
I3 = "argv";
J3 = "ref";
a4 = false;
b5 = true;
c5 = "booleanEquals";
d5 = "stringEquals";
e5 = "sigv4";
f5 = "sts";
g5 = "us-east-1";
h5 = "endpoint";
i4 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
j5 = "tree";
k5 = "error";
l5 = "getAttr";
m5 = { [F2]: false, [G3]: "String" };
n4 = { [F2]: true, "default": false, [G3]: "Boolean" };
o4 = { [J3]: "Endpoint" };
p5 = { [H3]: "isSet", [I3]: [{ [J3]: "Region" }] };
q5 = { [J3]: "Region" };
r5 = { [H3]: "aws.partition", [I3]: [q5], "assign": "PartitionResult" };
s4 = { [J3]: "UseFIPS" };
t5 = { [J3]: "UseDualStack" };
u4 = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e5, "signingName": f5, "signingRegion": g5 }] }, "headers": {} };
v6 = {};
w5 = { "conditions": [{ [H3]: d5, [I3]: [q5, "aws-global"] }], [h5]: u4, [G3]: h5 };
x5 = { [H3]: c5, [I3]: [s4, true] };
y3 = { [H3]: c5, [I3]: [t5, true] };
z4 = { [H3]: l5, [I3]: [{ [J3]: "PartitionResult" }, "supportsFIPS"] };
A2 = { [J3]: "PartitionResult" };
B2 = { [H3]: c5, [I3]: [true, { [H3]: l5, [I3]: [A2, "supportsDualStack"] }] };
C2 = [{ [H3]: "isSet", [I3]: [o4] }];
D2 = [x5];
E2 = [y3];
_data4 = { version: "1.0", parameters: { Region: m5, UseDualStack: n4, UseFIPS: n4, Endpoint: m5, UseGlobalEndpoint: n4 }, rules: [{ conditions: [{ [H3]: c5, [I3]: [{ [J3]: "UseGlobalEndpoint" }, b5] }, { [H3]: "not", [I3]: C2 }, p5, r5, { [H3]: c5, [I3]: [s4, a4] }, { [H3]: c5, [I3]: [t5, a4] }], rules: [{ conditions: [{ [H3]: d5, [I3]: [q5, "ap-northeast-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "ap-south-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "ap-southeast-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "ap-southeast-2"] }], endpoint: u4, [G3]: h5 }, w5, { conditions: [{ [H3]: d5, [I3]: [q5, "ca-central-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "eu-central-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "eu-north-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "eu-west-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "eu-west-2"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "eu-west-3"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "sa-east-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, g5] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "us-east-2"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "us-west-1"] }], endpoint: u4, [G3]: h5 }, { conditions: [{ [H3]: d5, [I3]: [q5, "us-west-2"] }], endpoint: u4, [G3]: h5 }, { endpoint: { url: i4, properties: { authSchemes: [{ name: e5, signingName: f5, signingRegion: "{Region}" }] }, headers: v6 }, [G3]: h5 }], [G3]: j5 }, { conditions: C2, rules: [{ conditions: D2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G3]: k5 }, { conditions: E2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G3]: k5 }, { endpoint: { url: o4, properties: v6, headers: v6 }, [G3]: h5 }], [G3]: j5 }, { conditions: [p5], rules: [{ conditions: [r5], rules: [{ conditions: [x5, y3], rules: [{ conditions: [{ [H3]: c5, [I3]: [b5, z4] }, B2], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v6, headers: v6 }, [G3]: h5 }], [G3]: j5 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G3]: k5 }], [G3]: j5 }, { conditions: D2, rules: [{ conditions: [{ [H3]: c5, [I3]: [z4, b5] }], rules: [{ conditions: [{ [H3]: d5, [I3]: [{ [H3]: l5, [I3]: [A2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v6, headers: v6 }, [G3]: h5 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v6, headers: v6 }, [G3]: h5 }], [G3]: j5 }, { error: "FIPS is enabled but this partition does not support FIPS", [G3]: k5 }], [G3]: j5 }, { conditions: E2, rules: [{ conditions: [B2], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v6, headers: v6 }, [G3]: h5 }], [G3]: j5 }, { error: "DualStack is enabled but this partition does not support DualStack", [G3]: k5 }], [G3]: j5 }, w5, { endpoint: { url: i4, properties: v6, headers: v6 }, [G3]: h5 }], [G3]: j5 }], [G3]: j5 }, { error: "Invalid Configuration: Missing Region", [G3]: k5 }] };
ruleSet4 = _data4;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/endpoint/endpointResolver.js
var cache5, defaultEndpointResolver4;
var init_endpointResolver4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/endpoint/endpointResolver.js"() {
init_import_meta_url();
init_dist_es33();
init_dist_es32();
init_ruleset4();
cache5 = new EndpointCache({
size: 50,
params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
});
defaultEndpointResolver4 = /* @__PURE__ */ __name((endpointParams, context2 = {}) => {
return cache5.get(endpointParams, () => resolveEndpoint(ruleSet4, {
endpointParams,
logger: context2.logger
}));
}, "defaultEndpointResolver");
customEndpointFunctions.aws = awsEndpointFunctions;
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.shared.js
var getRuntimeConfig5;
var init_runtimeConfig_shared3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.shared.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es16();
init_dist_es20();
init_dist_es41();
init_dist_es9();
init_dist_es8();
init_httpAuthSchemeProvider4();
init_endpointResolver4();
getRuntimeConfig5 = /* @__PURE__ */ __name((config) => {
return {
apiVersion: "2011-06-15",
base64Decoder: config?.base64Decoder ?? fromBase64,
base64Encoder: config?.base64Encoder ?? toBase64,
disableHostPrefix: config?.disableHostPrefix ?? false,
endpointProvider: config?.endpointProvider ?? defaultEndpointResolver4,
extensions: config?.extensions ?? [],
httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider,
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), "identityProvider"),
signer: new AwsSdkSigV4Signer()
},
{
schemeId: "smithy.api#noAuth",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), "identityProvider"),
signer: new NoAuthSigner()
}
],
logger: config?.logger ?? new NoOpLogger(),
serviceId: config?.serviceId ?? "STS",
urlParser: config?.urlParser ?? parseUrl,
utf8Decoder: config?.utf8Decoder ?? fromUtf8,
utf8Encoder: config?.utf8Encoder ?? toUtf8
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.js
var getRuntimeConfig6;
var init_runtimeConfig3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.js"() {
init_import_meta_url();
init_package5();
init_dist_es21();
init_dist_es64();
init_dist_es51();
init_dist_es35();
init_dist_es16();
init_dist_es52();
init_dist_es45();
init_dist_es39();
init_dist_es12();
init_dist_es53();
init_dist_es44();
init_runtimeConfig_shared3();
init_dist_es20();
init_dist_es54();
init_dist_es20();
getRuntimeConfig6 = /* @__PURE__ */ __name((config) => {
emitWarningIfUnsupportedVersion2(process.version);
const defaultsMode = resolveDefaultsModeConfig(config);
const defaultConfigProvider = /* @__PURE__ */ __name(() => defaultsMode().then(loadConfigsForDefaultMode), "defaultConfigProvider");
const clientSharedValues = getRuntimeConfig5(config);
emitWarningIfUnsupportedVersion(process.version);
const profileConfig = { profile: config?.profile };
return {
...clientSharedValues,
...config,
runtime: "node",
defaultsMode,
bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider,
defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default4.version }),
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await defaultProvider(idProps?.__config || {})()), "identityProvider"),
signer: new AwsSdkSigV4Signer()
},
{
schemeId: "smithy.api#noAuth",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), "identityProvider"),
signer: new NoAuthSigner()
}
],
maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...profileConfig }),
requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
retryMode: config?.retryMode ?? loadConfig({
...NODE_RETRY_MODE_CONFIG_OPTIONS,
default: /* @__PURE__ */ __name(async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, "default")
}, config),
sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
streamCollector: config?.streamCollector ?? streamCollector,
useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, profileConfig),
useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, profileConfig),
userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, profileConfig)
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration3, resolveHttpAuthRuntimeConfig3;
var init_httpAuthExtensionConfiguration3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthExtensionConfiguration.js"() {
init_import_meta_url();
getHttpAuthExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
let _credentials = runtimeConfig.credentials;
return {
setHttpAuthScheme(httpAuthScheme) {
const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
if (index === -1) {
_httpAuthSchemes.push(httpAuthScheme);
} else {
_httpAuthSchemes.splice(index, 1, httpAuthScheme);
}
},
httpAuthSchemes() {
return _httpAuthSchemes;
},
setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
_httpAuthSchemeProvider = httpAuthSchemeProvider;
},
httpAuthSchemeProvider() {
return _httpAuthSchemeProvider;
},
setCredentials(credentials) {
_credentials = credentials;
},
credentials() {
return _credentials;
}
};
}, "getHttpAuthExtensionConfiguration");
resolveHttpAuthRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
return {
httpAuthSchemes: config.httpAuthSchemes(),
httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
credentials: config.credentials()
};
}, "resolveHttpAuthRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/runtimeExtensions.js
var asPartial3, resolveRuntimeExtensions3;
var init_runtimeExtensions3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/runtimeExtensions.js"() {
init_import_meta_url();
init_dist_es55();
init_dist_es2();
init_dist_es20();
init_httpAuthExtensionConfiguration3();
asPartial3 = /* @__PURE__ */ __name((t7) => t7, "asPartial");
resolveRuntimeExtensions3 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
const extensionConfiguration = {
...asPartial3(getAwsRegionExtensionConfiguration(runtimeConfig)),
...asPartial3(getDefaultExtensionConfiguration(runtimeConfig)),
...asPartial3(getHttpHandlerExtensionConfiguration(runtimeConfig)),
...asPartial3(getHttpAuthExtensionConfiguration3(runtimeConfig))
};
extensions.forEach((extension) => extension.configure(extensionConfiguration));
return {
...runtimeConfig,
...resolveAwsRegionExtensionConfiguration(extensionConfiguration),
...resolveDefaultRuntimeConfig(extensionConfiguration),
...resolveHttpHandlerRuntimeConfig(extensionConfiguration),
...resolveHttpAuthRuntimeConfig3(extensionConfiguration)
};
}, "resolveRuntimeExtensions");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/STSClient.js
var STSClient;
var init_STSClient = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/STSClient.js"() {
init_import_meta_url();
init_dist_es26();
init_dist_es27();
init_dist_es28();
init_dist_es34();
init_dist_es35();
init_dist_es16();
init_dist_es37();
init_dist_es42();
init_dist_es45();
init_dist_es20();
init_httpAuthSchemeProvider4();
init_EndpointParameters4();
init_runtimeConfig3();
init_runtimeExtensions3();
STSClient = class extends Client {
static {
__name(this, "STSClient");
}
constructor(...[configuration]) {
const _config_0 = getRuntimeConfig6(configuration || {});
const _config_1 = resolveClientEndpointParameters4(_config_0);
const _config_2 = resolveUserAgentConfig(_config_1);
const _config_3 = resolveRetryConfig(_config_2);
const _config_4 = resolveRegionConfig(_config_3);
const _config_5 = resolveHostHeaderConfig(_config_4);
const _config_6 = resolveEndpointConfig(_config_5);
const _config_7 = resolveHttpAuthSchemeConfig4(_config_6);
const _config_8 = resolveRuntimeExtensions3(_config_7, configuration?.extensions || []);
super(_config_8);
this.config = _config_8;
this.middlewareStack.use(getUserAgentPlugin(this.config));
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new DefaultIdentityProviderConfig({
"aws.auth#sigv4": config.credentials
}), "identityProviderConfigProvider")
}));
this.middlewareStack.use(getHttpSigningPlugin(this.config));
}
destroy() {
super.destroy();
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/models/STSServiceException.js
var STSServiceException;
var init_STSServiceException = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/models/STSServiceException.js"() {
init_import_meta_url();
init_dist_es20();
STSServiceException = class _STSServiceException extends ServiceException {
static {
__name(this, "STSServiceException");
}
constructor(options) {
super(options);
Object.setPrototypeOf(this, _STSServiceException.prototype);
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/models/models_0.js
var ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException, InvalidAuthorizationMessageException, CredentialsFilterSensitiveLog, AssumeRoleResponseFilterSensitiveLog, AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog, AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog, AssumeRootResponseFilterSensitiveLog, GetFederationTokenResponseFilterSensitiveLog, GetSessionTokenResponseFilterSensitiveLog;
var init_models_04 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/models/models_0.js"() {
init_import_meta_url();
init_dist_es20();
init_STSServiceException();
ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException {
static {
__name(this, "ExpiredTokenException");
}
constructor(opts) {
super({
name: "ExpiredTokenException",
$fault: "client",
...opts
});
this.name = "ExpiredTokenException";
this.$fault = "client";
Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
}
};
MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException {
static {
__name(this, "MalformedPolicyDocumentException");
}
constructor(opts) {
super({
name: "MalformedPolicyDocumentException",
$fault: "client",
...opts
});
this.name = "MalformedPolicyDocumentException";
this.$fault = "client";
Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype);
}
};
PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException {
static {
__name(this, "PackedPolicyTooLargeException");
}
constructor(opts) {
super({
name: "PackedPolicyTooLargeException",
$fault: "client",
...opts
});
this.name = "PackedPolicyTooLargeException";
this.$fault = "client";
Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype);
}
};
RegionDisabledException = class _RegionDisabledException extends STSServiceException {
static {
__name(this, "RegionDisabledException");
}
constructor(opts) {
super({
name: "RegionDisabledException",
$fault: "client",
...opts
});
this.name = "RegionDisabledException";
this.$fault = "client";
Object.setPrototypeOf(this, _RegionDisabledException.prototype);
}
};
IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException {
static {
__name(this, "IDPRejectedClaimException");
}
constructor(opts) {
super({
name: "IDPRejectedClaimException",
$fault: "client",
...opts
});
this.name = "IDPRejectedClaimException";
this.$fault = "client";
Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype);
}
};
InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException {
static {
__name(this, "InvalidIdentityTokenException");
}
constructor(opts) {
super({
name: "InvalidIdentityTokenException",
$fault: "client",
...opts
});
this.name = "InvalidIdentityTokenException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype);
}
};
IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException {
static {
__name(this, "IDPCommunicationErrorException");
}
constructor(opts) {
super({
name: "IDPCommunicationErrorException",
$fault: "client",
...opts
});
this.name = "IDPCommunicationErrorException";
this.$fault = "client";
Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype);
}
};
InvalidAuthorizationMessageException = class _InvalidAuthorizationMessageException extends STSServiceException {
static {
__name(this, "InvalidAuthorizationMessageException");
}
constructor(opts) {
super({
name: "InvalidAuthorizationMessageException",
$fault: "client",
...opts
});
this.name = "InvalidAuthorizationMessageException";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidAuthorizationMessageException.prototype);
}
};
CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SecretAccessKey && { SecretAccessKey: SENSITIVE_STRING }
}), "CredentialsFilterSensitiveLog");
AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
}), "AssumeRoleResponseFilterSensitiveLog");
AssumeRoleWithSAMLRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.SAMLAssertion && { SAMLAssertion: SENSITIVE_STRING }
}), "AssumeRoleWithSAMLRequestFilterSensitiveLog");
AssumeRoleWithSAMLResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
}), "AssumeRoleWithSAMLResponseFilterSensitiveLog");
AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.WebIdentityToken && { WebIdentityToken: SENSITIVE_STRING }
}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog");
AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog");
AssumeRootResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
}), "AssumeRootResponseFilterSensitiveLog");
GetFederationTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
}), "GetFederationTokenResponseFilterSensitiveLog");
GetSessionTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
...obj,
...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
}), "GetSessionTokenResponseFilterSensitiveLog");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/protocols/Aws_query.js
var se_AssumeRoleCommand, se_AssumeRoleWithSAMLCommand, se_AssumeRoleWithWebIdentityCommand, se_AssumeRootCommand, se_DecodeAuthorizationMessageCommand, se_GetAccessKeyInfoCommand, se_GetCallerIdentityCommand, se_GetFederationTokenCommand, se_GetSessionTokenCommand, de_AssumeRoleCommand, de_AssumeRoleWithSAMLCommand, de_AssumeRoleWithWebIdentityCommand, de_AssumeRootCommand, de_DecodeAuthorizationMessageCommand, de_GetAccessKeyInfoCommand, de_GetCallerIdentityCommand, de_GetFederationTokenCommand, de_GetSessionTokenCommand, de_CommandError4, de_ExpiredTokenExceptionRes2, de_IDPCommunicationErrorExceptionRes, de_IDPRejectedClaimExceptionRes, de_InvalidAuthorizationMessageExceptionRes, de_InvalidIdentityTokenExceptionRes, de_MalformedPolicyDocumentExceptionRes, de_PackedPolicyTooLargeExceptionRes, de_RegionDisabledExceptionRes, se_AssumeRoleRequest, se_AssumeRoleWithSAMLRequest, se_AssumeRoleWithWebIdentityRequest, se_AssumeRootRequest, se_DecodeAuthorizationMessageRequest, se_GetAccessKeyInfoRequest, se_GetCallerIdentityRequest, se_GetFederationTokenRequest, se_GetSessionTokenRequest, se_policyDescriptorListType, se_PolicyDescriptorType, se_ProvidedContext, se_ProvidedContextsListType, se_Tag2, se_tagKeyListType, se_tagListType, de_AssumedRoleUser, de_AssumeRoleResponse, de_AssumeRoleWithSAMLResponse, de_AssumeRoleWithWebIdentityResponse, de_AssumeRootResponse, de_Credentials, de_DecodeAuthorizationMessageResponse, de_ExpiredTokenException, de_FederatedUser, de_GetAccessKeyInfoResponse, de_GetCallerIdentityResponse, de_GetFederationTokenResponse, de_GetSessionTokenResponse, de_IDPCommunicationErrorException, de_IDPRejectedClaimException, de_InvalidAuthorizationMessageException, de_InvalidIdentityTokenException, de_MalformedPolicyDocumentException, de_PackedPolicyTooLargeException, de_RegionDisabledException, deserializeMetadata5, throwDefaultError5, buildHttpRpcRequest, SHARED_HEADERS, _3, _A2, _AKI2, _AR2, _ARI2, _ARU, _ARWSAML, _ARWWI, _ARs, _Ac2, _Ar, _Au, _C2, _CA2, _DAM, _DM2, _DS, _E2, _EI, _EM2, _FU, _FUI, _GAKI, _GCI, _GFT, _GST, _I2, _K2, _N2, _NQ, _P2, _PA, _PAr, _PAro, _PC2, _PI2, _PPS, _Pr2, _RA, _RSN, _S2, _SAK2, _SAMLA, _SFWIT, _SI, _SN, _ST2, _STe, _T2, _TC2, _TP2, _TPA, _TTK, _UI2, _V2, _Va2, _WIT, _a3, _m2, buildFormUrlencodedString, loadQueryErrorCode;
var init_Aws_query = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/protocols/Aws_query.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es2();
init_dist_es20();
init_models_04();
init_STSServiceException();
se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_AssumeRoleRequest(input, context2),
[_A2]: _AR2,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_AssumeRoleCommand");
se_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_AssumeRoleWithSAMLRequest(input, context2),
[_A2]: _ARWSAML,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_AssumeRoleWithSAMLCommand");
se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_AssumeRoleWithWebIdentityRequest(input, context2),
[_A2]: _ARWWI,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_AssumeRoleWithWebIdentityCommand");
se_AssumeRootCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_AssumeRootRequest(input, context2),
[_A2]: _ARs,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_AssumeRootCommand");
se_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_DecodeAuthorizationMessageRequest(input, context2),
[_A2]: _DAM,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_DecodeAuthorizationMessageCommand");
se_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_GetAccessKeyInfoRequest(input, context2),
[_A2]: _GAKI,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_GetAccessKeyInfoCommand");
se_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_GetCallerIdentityRequest(input, context2),
[_A2]: _GCI,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_GetCallerIdentityCommand");
se_GetFederationTokenCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_GetFederationTokenRequest(input, context2),
[_A2]: _GFT,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_GetFederationTokenCommand");
se_GetSessionTokenCommand = /* @__PURE__ */ __name(async (input, context2) => {
const headers = SHARED_HEADERS;
let body;
body = buildFormUrlencodedString({
...se_GetSessionTokenRequest(input, context2),
[_A2]: _GST,
[_V2]: _3
});
return buildHttpRpcRequest(context2, headers, "/", void 0, body);
}, "se_GetSessionTokenCommand");
de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_AssumeRoleResponse(data.AssumeRoleResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_AssumeRoleCommand");
de_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_AssumeRoleWithSAMLResponse(data.AssumeRoleWithSAMLResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_AssumeRoleWithSAMLCommand");
de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_AssumeRoleWithWebIdentityCommand");
de_AssumeRootCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_AssumeRootResponse(data.AssumeRootResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_AssumeRootCommand");
de_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_DecodeAuthorizationMessageResponse(data.DecodeAuthorizationMessageResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_DecodeAuthorizationMessageCommand");
de_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_GetAccessKeyInfoResponse(data.GetAccessKeyInfoResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_GetAccessKeyInfoCommand");
de_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_GetCallerIdentityResponse(data.GetCallerIdentityResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_GetCallerIdentityCommand");
de_GetFederationTokenCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_GetFederationTokenResponse(data.GetFederationTokenResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_GetFederationTokenCommand");
de_GetSessionTokenCommand = /* @__PURE__ */ __name(async (output, context2) => {
if (output.statusCode >= 300) {
return de_CommandError4(output, context2);
}
const data = await parseXmlBody(output.body, context2);
let contents = {};
contents = de_GetSessionTokenResponse(data.GetSessionTokenResult, context2);
const response = {
$metadata: deserializeMetadata5(output),
...contents
};
return response;
}, "de_GetSessionTokenCommand");
de_CommandError4 = /* @__PURE__ */ __name(async (output, context2) => {
const parsedOutput = {
...output,
body: await parseXmlErrorBody(output.body, context2)
};
const errorCode = loadQueryErrorCode(output, parsedOutput.body);
switch (errorCode) {
case "ExpiredTokenException":
case "com.amazonaws.sts#ExpiredTokenException":
throw await de_ExpiredTokenExceptionRes2(parsedOutput, context2);
case "MalformedPolicyDocument":
case "com.amazonaws.sts#MalformedPolicyDocumentException":
throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context2);
case "PackedPolicyTooLarge":
case "com.amazonaws.sts#PackedPolicyTooLargeException":
throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context2);
case "RegionDisabledException":
case "com.amazonaws.sts#RegionDisabledException":
throw await de_RegionDisabledExceptionRes(parsedOutput, context2);
case "IDPRejectedClaim":
case "com.amazonaws.sts#IDPRejectedClaimException":
throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context2);
case "InvalidIdentityToken":
case "com.amazonaws.sts#InvalidIdentityTokenException":
throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context2);
case "IDPCommunicationError":
case "com.amazonaws.sts#IDPCommunicationErrorException":
throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context2);
case "InvalidAuthorizationMessageException":
case "com.amazonaws.sts#InvalidAuthorizationMessageException":
throw await de_InvalidAuthorizationMessageExceptionRes(parsedOutput, context2);
default:
const parsedBody = parsedOutput.body;
return throwDefaultError5({
output,
parsedBody: parsedBody.Error,
errorCode
});
}
}, "de_CommandError");
de_ExpiredTokenExceptionRes2 = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_ExpiredTokenException(body.Error, context2);
const exception = new ExpiredTokenException2({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_ExpiredTokenExceptionRes");
de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_IDPCommunicationErrorException(body.Error, context2);
const exception = new IDPCommunicationErrorException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_IDPCommunicationErrorExceptionRes");
de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_IDPRejectedClaimException(body.Error, context2);
const exception = new IDPRejectedClaimException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_IDPRejectedClaimExceptionRes");
de_InvalidAuthorizationMessageExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_InvalidAuthorizationMessageException(body.Error, context2);
const exception = new InvalidAuthorizationMessageException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_InvalidAuthorizationMessageExceptionRes");
de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_InvalidIdentityTokenException(body.Error, context2);
const exception = new InvalidIdentityTokenException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_InvalidIdentityTokenExceptionRes");
de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_MalformedPolicyDocumentException(body.Error, context2);
const exception = new MalformedPolicyDocumentException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_MalformedPolicyDocumentExceptionRes");
de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_PackedPolicyTooLargeException(body.Error, context2);
const exception = new PackedPolicyTooLargeException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_PackedPolicyTooLargeExceptionRes");
de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context2) => {
const body = parsedOutput.body;
const deserialized = de_RegionDisabledException(body.Error, context2);
const exception = new RegionDisabledException({
$metadata: deserializeMetadata5(parsedOutput),
...deserialized
});
return decorateServiceException(exception, body);
}, "de_RegionDisabledExceptionRes");
se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_RA] != null) {
entries[_RA] = input[_RA];
}
if (input[_RSN] != null) {
entries[_RSN] = input[_RSN];
}
if (input[_PA] != null) {
const memberEntries = se_policyDescriptorListType(input[_PA], context2);
if (input[_PA]?.length === 0) {
entries.PolicyArns = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `PolicyArns.${key}`;
entries[loc] = value;
});
}
if (input[_P2] != null) {
entries[_P2] = input[_P2];
}
if (input[_DS] != null) {
entries[_DS] = input[_DS];
}
if (input[_T2] != null) {
const memberEntries = se_tagListType(input[_T2], context2);
if (input[_T2]?.length === 0) {
entries.Tags = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `Tags.${key}`;
entries[loc] = value;
});
}
if (input[_TTK] != null) {
const memberEntries = se_tagKeyListType(input[_TTK], context2);
if (input[_TTK]?.length === 0) {
entries.TransitiveTagKeys = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `TransitiveTagKeys.${key}`;
entries[loc] = value;
});
}
if (input[_EI] != null) {
entries[_EI] = input[_EI];
}
if (input[_SN] != null) {
entries[_SN] = input[_SN];
}
if (input[_TC2] != null) {
entries[_TC2] = input[_TC2];
}
if (input[_SI] != null) {
entries[_SI] = input[_SI];
}
if (input[_PC2] != null) {
const memberEntries = se_ProvidedContextsListType(input[_PC2], context2);
if (input[_PC2]?.length === 0) {
entries.ProvidedContexts = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `ProvidedContexts.${key}`;
entries[loc] = value;
});
}
return entries;
}, "se_AssumeRoleRequest");
se_AssumeRoleWithSAMLRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_RA] != null) {
entries[_RA] = input[_RA];
}
if (input[_PAr] != null) {
entries[_PAr] = input[_PAr];
}
if (input[_SAMLA] != null) {
entries[_SAMLA] = input[_SAMLA];
}
if (input[_PA] != null) {
const memberEntries = se_policyDescriptorListType(input[_PA], context2);
if (input[_PA]?.length === 0) {
entries.PolicyArns = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `PolicyArns.${key}`;
entries[loc] = value;
});
}
if (input[_P2] != null) {
entries[_P2] = input[_P2];
}
if (input[_DS] != null) {
entries[_DS] = input[_DS];
}
return entries;
}, "se_AssumeRoleWithSAMLRequest");
se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_RA] != null) {
entries[_RA] = input[_RA];
}
if (input[_RSN] != null) {
entries[_RSN] = input[_RSN];
}
if (input[_WIT] != null) {
entries[_WIT] = input[_WIT];
}
if (input[_PI2] != null) {
entries[_PI2] = input[_PI2];
}
if (input[_PA] != null) {
const memberEntries = se_policyDescriptorListType(input[_PA], context2);
if (input[_PA]?.length === 0) {
entries.PolicyArns = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `PolicyArns.${key}`;
entries[loc] = value;
});
}
if (input[_P2] != null) {
entries[_P2] = input[_P2];
}
if (input[_DS] != null) {
entries[_DS] = input[_DS];
}
return entries;
}, "se_AssumeRoleWithWebIdentityRequest");
se_AssumeRootRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_TP2] != null) {
entries[_TP2] = input[_TP2];
}
if (input[_TPA] != null) {
const memberEntries = se_PolicyDescriptorType(input[_TPA], context2);
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `TaskPolicyArn.${key}`;
entries[loc] = value;
});
}
if (input[_DS] != null) {
entries[_DS] = input[_DS];
}
return entries;
}, "se_AssumeRootRequest");
se_DecodeAuthorizationMessageRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_EM2] != null) {
entries[_EM2] = input[_EM2];
}
return entries;
}, "se_DecodeAuthorizationMessageRequest");
se_GetAccessKeyInfoRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_AKI2] != null) {
entries[_AKI2] = input[_AKI2];
}
return entries;
}, "se_GetAccessKeyInfoRequest");
se_GetCallerIdentityRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
return entries;
}, "se_GetCallerIdentityRequest");
se_GetFederationTokenRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_N2] != null) {
entries[_N2] = input[_N2];
}
if (input[_P2] != null) {
entries[_P2] = input[_P2];
}
if (input[_PA] != null) {
const memberEntries = se_policyDescriptorListType(input[_PA], context2);
if (input[_PA]?.length === 0) {
entries.PolicyArns = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `PolicyArns.${key}`;
entries[loc] = value;
});
}
if (input[_DS] != null) {
entries[_DS] = input[_DS];
}
if (input[_T2] != null) {
const memberEntries = se_tagListType(input[_T2], context2);
if (input[_T2]?.length === 0) {
entries.Tags = [];
}
Object.entries(memberEntries).forEach(([key, value]) => {
const loc = `Tags.${key}`;
entries[loc] = value;
});
}
return entries;
}, "se_GetFederationTokenRequest");
se_GetSessionTokenRequest = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_DS] != null) {
entries[_DS] = input[_DS];
}
if (input[_SN] != null) {
entries[_SN] = input[_SN];
}
if (input[_TC2] != null) {
entries[_TC2] = input[_TC2];
}
return entries;
}, "se_GetSessionTokenRequest");
se_policyDescriptorListType = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
let counter = 1;
for (const entry of input) {
if (entry === null) {
continue;
}
const memberEntries = se_PolicyDescriptorType(entry, context2);
Object.entries(memberEntries).forEach(([key, value]) => {
entries[`member.${counter}.${key}`] = value;
});
counter++;
}
return entries;
}, "se_policyDescriptorListType");
se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_a3] != null) {
entries[_a3] = input[_a3];
}
return entries;
}, "se_PolicyDescriptorType");
se_ProvidedContext = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_PAro] != null) {
entries[_PAro] = input[_PAro];
}
if (input[_CA2] != null) {
entries[_CA2] = input[_CA2];
}
return entries;
}, "se_ProvidedContext");
se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
let counter = 1;
for (const entry of input) {
if (entry === null) {
continue;
}
const memberEntries = se_ProvidedContext(entry, context2);
Object.entries(memberEntries).forEach(([key, value]) => {
entries[`member.${counter}.${key}`] = value;
});
counter++;
}
return entries;
}, "se_ProvidedContextsListType");
se_Tag2 = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
if (input[_K2] != null) {
entries[_K2] = input[_K2];
}
if (input[_Va2] != null) {
entries[_Va2] = input[_Va2];
}
return entries;
}, "se_Tag");
se_tagKeyListType = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
let counter = 1;
for (const entry of input) {
if (entry === null) {
continue;
}
entries[`member.${counter}`] = entry;
counter++;
}
return entries;
}, "se_tagKeyListType");
se_tagListType = /* @__PURE__ */ __name((input, context2) => {
const entries = {};
let counter = 1;
for (const entry of input) {
if (entry === null) {
continue;
}
const memberEntries = se_Tag2(entry, context2);
Object.entries(memberEntries).forEach(([key, value]) => {
entries[`member.${counter}.${key}`] = value;
});
counter++;
}
return entries;
}, "se_tagListType");
de_AssumedRoleUser = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_ARI2] != null) {
contents[_ARI2] = expectString(output[_ARI2]);
}
if (output[_Ar] != null) {
contents[_Ar] = expectString(output[_Ar]);
}
return contents;
}, "de_AssumedRoleUser");
de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_C2] != null) {
contents[_C2] = de_Credentials(output[_C2], context2);
}
if (output[_ARU] != null) {
contents[_ARU] = de_AssumedRoleUser(output[_ARU], context2);
}
if (output[_PPS] != null) {
contents[_PPS] = strictParseInt32(output[_PPS]);
}
if (output[_SI] != null) {
contents[_SI] = expectString(output[_SI]);
}
return contents;
}, "de_AssumeRoleResponse");
de_AssumeRoleWithSAMLResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_C2] != null) {
contents[_C2] = de_Credentials(output[_C2], context2);
}
if (output[_ARU] != null) {
contents[_ARU] = de_AssumedRoleUser(output[_ARU], context2);
}
if (output[_PPS] != null) {
contents[_PPS] = strictParseInt32(output[_PPS]);
}
if (output[_S2] != null) {
contents[_S2] = expectString(output[_S2]);
}
if (output[_ST2] != null) {
contents[_ST2] = expectString(output[_ST2]);
}
if (output[_I2] != null) {
contents[_I2] = expectString(output[_I2]);
}
if (output[_Au] != null) {
contents[_Au] = expectString(output[_Au]);
}
if (output[_NQ] != null) {
contents[_NQ] = expectString(output[_NQ]);
}
if (output[_SI] != null) {
contents[_SI] = expectString(output[_SI]);
}
return contents;
}, "de_AssumeRoleWithSAMLResponse");
de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_C2] != null) {
contents[_C2] = de_Credentials(output[_C2], context2);
}
if (output[_SFWIT] != null) {
contents[_SFWIT] = expectString(output[_SFWIT]);
}
if (output[_ARU] != null) {
contents[_ARU] = de_AssumedRoleUser(output[_ARU], context2);
}
if (output[_PPS] != null) {
contents[_PPS] = strictParseInt32(output[_PPS]);
}
if (output[_Pr2] != null) {
contents[_Pr2] = expectString(output[_Pr2]);
}
if (output[_Au] != null) {
contents[_Au] = expectString(output[_Au]);
}
if (output[_SI] != null) {
contents[_SI] = expectString(output[_SI]);
}
return contents;
}, "de_AssumeRoleWithWebIdentityResponse");
de_AssumeRootResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_C2] != null) {
contents[_C2] = de_Credentials(output[_C2], context2);
}
if (output[_SI] != null) {
contents[_SI] = expectString(output[_SI]);
}
return contents;
}, "de_AssumeRootResponse");
de_Credentials = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_AKI2] != null) {
contents[_AKI2] = expectString(output[_AKI2]);
}
if (output[_SAK2] != null) {
contents[_SAK2] = expectString(output[_SAK2]);
}
if (output[_STe] != null) {
contents[_STe] = expectString(output[_STe]);
}
if (output[_E2] != null) {
contents[_E2] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_E2]));
}
return contents;
}, "de_Credentials");
de_DecodeAuthorizationMessageResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_DM2] != null) {
contents[_DM2] = expectString(output[_DM2]);
}
return contents;
}, "de_DecodeAuthorizationMessageResponse");
de_ExpiredTokenException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_ExpiredTokenException");
de_FederatedUser = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_FUI] != null) {
contents[_FUI] = expectString(output[_FUI]);
}
if (output[_Ar] != null) {
contents[_Ar] = expectString(output[_Ar]);
}
return contents;
}, "de_FederatedUser");
de_GetAccessKeyInfoResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_Ac2] != null) {
contents[_Ac2] = expectString(output[_Ac2]);
}
return contents;
}, "de_GetAccessKeyInfoResponse");
de_GetCallerIdentityResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_UI2] != null) {
contents[_UI2] = expectString(output[_UI2]);
}
if (output[_Ac2] != null) {
contents[_Ac2] = expectString(output[_Ac2]);
}
if (output[_Ar] != null) {
contents[_Ar] = expectString(output[_Ar]);
}
return contents;
}, "de_GetCallerIdentityResponse");
de_GetFederationTokenResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_C2] != null) {
contents[_C2] = de_Credentials(output[_C2], context2);
}
if (output[_FU] != null) {
contents[_FU] = de_FederatedUser(output[_FU], context2);
}
if (output[_PPS] != null) {
contents[_PPS] = strictParseInt32(output[_PPS]);
}
return contents;
}, "de_GetFederationTokenResponse");
de_GetSessionTokenResponse = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_C2] != null) {
contents[_C2] = de_Credentials(output[_C2], context2);
}
return contents;
}, "de_GetSessionTokenResponse");
de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_IDPCommunicationErrorException");
de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_IDPRejectedClaimException");
de_InvalidAuthorizationMessageException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_InvalidAuthorizationMessageException");
de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_InvalidIdentityTokenException");
de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_MalformedPolicyDocumentException");
de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_PackedPolicyTooLargeException");
de_RegionDisabledException = /* @__PURE__ */ __name((output, context2) => {
const contents = {};
if (output[_m2] != null) {
contents[_m2] = expectString(output[_m2]);
}
return contents;
}, "de_RegionDisabledException");
deserializeMetadata5 = /* @__PURE__ */ __name((output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"]
}), "deserializeMetadata");
throwDefaultError5 = withBaseException(STSServiceException);
buildHttpRpcRequest = /* @__PURE__ */ __name(async (context2, headers, path72, resolvedHostname, body) => {
const { hostname: hostname2, protocol = "https", port, path: basePath } = await context2.endpoint();
const contents = {
protocol,
hostname: hostname2,
port,
method: "POST",
path: basePath.endsWith("/") ? basePath.slice(0, -1) + path72 : basePath + path72,
headers
};
if (resolvedHostname !== void 0) {
contents.hostname = resolvedHostname;
}
if (body !== void 0) {
contents.body = body;
}
return new HttpRequest(contents);
}, "buildHttpRpcRequest");
SHARED_HEADERS = {
"content-type": "application/x-www-form-urlencoded"
};
_3 = "2011-06-15";
_A2 = "Action";
_AKI2 = "AccessKeyId";
_AR2 = "AssumeRole";
_ARI2 = "AssumedRoleId";
_ARU = "AssumedRoleUser";
_ARWSAML = "AssumeRoleWithSAML";
_ARWWI = "AssumeRoleWithWebIdentity";
_ARs = "AssumeRoot";
_Ac2 = "Account";
_Ar = "Arn";
_Au = "Audience";
_C2 = "Credentials";
_CA2 = "ContextAssertion";
_DAM = "DecodeAuthorizationMessage";
_DM2 = "DecodedMessage";
_DS = "DurationSeconds";
_E2 = "Expiration";
_EI = "ExternalId";
_EM2 = "EncodedMessage";
_FU = "FederatedUser";
_FUI = "FederatedUserId";
_GAKI = "GetAccessKeyInfo";
_GCI = "GetCallerIdentity";
_GFT = "GetFederationToken";
_GST = "GetSessionToken";
_I2 = "Issuer";
_K2 = "Key";
_N2 = "Name";
_NQ = "NameQualifier";
_P2 = "Policy";
_PA = "PolicyArns";
_PAr = "PrincipalArn";
_PAro = "ProviderArn";
_PC2 = "ProvidedContexts";
_PI2 = "ProviderId";
_PPS = "PackedPolicySize";
_Pr2 = "Provider";
_RA = "RoleArn";
_RSN = "RoleSessionName";
_S2 = "Subject";
_SAK2 = "SecretAccessKey";
_SAMLA = "SAMLAssertion";
_SFWIT = "SubjectFromWebIdentityToken";
_SI = "SourceIdentity";
_SN = "SerialNumber";
_ST2 = "SubjectType";
_STe = "SessionToken";
_T2 = "Tags";
_TC2 = "TokenCode";
_TP2 = "TargetPrincipal";
_TPA = "TaskPolicyArn";
_TTK = "TransitiveTagKeys";
_UI2 = "UserId";
_V2 = "Version";
_Va2 = "Value";
_WIT = "WebIdentityToken";
_a3 = "arn";
_m2 = "message";
buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => extendedEncodeURIComponent(key) + "=" + extendedEncodeURIComponent(value)).join("&"), "buildFormUrlencodedString");
loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => {
if (data.Error?.Code !== void 0) {
return data.Error.Code;
}
if (output.statusCode == 404) {
return "NotFound";
}
}, "loadQueryErrorCode");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleCommand.js
var AssumeRoleCommand;
var init_AssumeRoleCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_models_04();
init_Aws_query();
AssumeRoleCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
static {
__name(this, "AssumeRoleCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithSAMLCommand.js
var AssumeRoleWithSAMLCommand;
var init_AssumeRoleWithSAMLCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithSAMLCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_models_04();
init_Aws_query();
AssumeRoleWithSAMLCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}).n("STSClient", "AssumeRoleWithSAMLCommand").f(AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog).ser(se_AssumeRoleWithSAMLCommand).de(de_AssumeRoleWithSAMLCommand).build() {
static {
__name(this, "AssumeRoleWithSAMLCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithWebIdentityCommand.js
var AssumeRoleWithWebIdentityCommand;
var init_AssumeRoleWithWebIdentityCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithWebIdentityCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_models_04();
init_Aws_query();
AssumeRoleWithWebIdentityCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
static {
__name(this, "AssumeRoleWithWebIdentityCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRootCommand.js
var AssumeRootCommand;
var init_AssumeRootCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRootCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_models_04();
init_Aws_query();
AssumeRootCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "AssumeRoot", {}).n("STSClient", "AssumeRootCommand").f(void 0, AssumeRootResponseFilterSensitiveLog).ser(se_AssumeRootCommand).de(de_AssumeRootCommand).build() {
static {
__name(this, "AssumeRootCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/DecodeAuthorizationMessageCommand.js
var DecodeAuthorizationMessageCommand;
var init_DecodeAuthorizationMessageCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/DecodeAuthorizationMessageCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_Aws_query();
DecodeAuthorizationMessageCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}).n("STSClient", "DecodeAuthorizationMessageCommand").f(void 0, void 0).ser(se_DecodeAuthorizationMessageCommand).de(de_DecodeAuthorizationMessageCommand).build() {
static {
__name(this, "DecodeAuthorizationMessageCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetAccessKeyInfoCommand.js
var GetAccessKeyInfoCommand;
var init_GetAccessKeyInfoCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetAccessKeyInfoCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_Aws_query();
GetAccessKeyInfoCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}).n("STSClient", "GetAccessKeyInfoCommand").f(void 0, void 0).ser(se_GetAccessKeyInfoCommand).de(de_GetAccessKeyInfoCommand).build() {
static {
__name(this, "GetAccessKeyInfoCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetCallerIdentityCommand.js
var GetCallerIdentityCommand;
var init_GetCallerIdentityCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetCallerIdentityCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_Aws_query();
GetCallerIdentityCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}).n("STSClient", "GetCallerIdentityCommand").f(void 0, void 0).ser(se_GetCallerIdentityCommand).de(de_GetCallerIdentityCommand).build() {
static {
__name(this, "GetCallerIdentityCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetFederationTokenCommand.js
var GetFederationTokenCommand;
var init_GetFederationTokenCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetFederationTokenCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_models_04();
init_Aws_query();
GetFederationTokenCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}).n("STSClient", "GetFederationTokenCommand").f(void 0, GetFederationTokenResponseFilterSensitiveLog).ser(se_GetFederationTokenCommand).de(de_GetFederationTokenCommand).build() {
static {
__name(this, "GetFederationTokenCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetSessionTokenCommand.js
var GetSessionTokenCommand;
var init_GetSessionTokenCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/GetSessionTokenCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters4();
init_models_04();
init_Aws_query();
GetSessionTokenCommand = class extends Command.classBuilder().ep(commonParams4).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}).n("STSClient", "GetSessionTokenCommand").f(void 0, GetSessionTokenResponseFilterSensitiveLog).ser(se_GetSessionTokenCommand).de(de_GetSessionTokenCommand).build() {
static {
__name(this, "GetSessionTokenCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/STS.js
var commands3, STS;
var init_STS = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/STS.js"() {
init_import_meta_url();
init_dist_es20();
init_AssumeRoleCommand();
init_AssumeRoleWithSAMLCommand();
init_AssumeRoleWithWebIdentityCommand();
init_AssumeRootCommand();
init_DecodeAuthorizationMessageCommand();
init_GetAccessKeyInfoCommand();
init_GetCallerIdentityCommand();
init_GetFederationTokenCommand();
init_GetSessionTokenCommand();
init_STSClient();
commands3 = {
AssumeRoleCommand,
AssumeRoleWithSAMLCommand,
AssumeRoleWithWebIdentityCommand,
AssumeRootCommand,
DecodeAuthorizationMessageCommand,
GetAccessKeyInfoCommand,
GetCallerIdentityCommand,
GetFederationTokenCommand,
GetSessionTokenCommand
};
STS = class extends STSClient {
static {
__name(this, "STS");
}
};
createAggregatedClient(commands3, STS);
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/index.js
var init_commands4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/commands/index.js"() {
init_import_meta_url();
init_AssumeRoleCommand();
init_AssumeRoleWithSAMLCommand();
init_AssumeRoleWithWebIdentityCommand();
init_AssumeRootCommand();
init_DecodeAuthorizationMessageCommand();
init_GetAccessKeyInfoCommand();
init_GetCallerIdentityCommand();
init_GetFederationTokenCommand();
init_GetSessionTokenCommand();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/models/index.js
var init_models3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/models/index.js"() {
init_import_meta_url();
init_models_04();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/defaultStsRoleAssumers.js
var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
var init_defaultStsRoleAssumers = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/defaultStsRoleAssumers.js"() {
init_import_meta_url();
init_client5();
init_AssumeRoleCommand();
init_AssumeRoleWithWebIdentityCommand();
ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => {
if (typeof assumedRoleUser?.Arn === "string") {
const arnComponents = assumedRoleUser.Arn.split(":");
if (arnComponents.length > 4 && arnComponents[4] !== "") {
return arnComponents[4];
}
}
return void 0;
}, "getAccountIdFromAssumedRoleUser");
resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => {
const region = typeof _region === "function" ? await _region() : _region;
const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
}, "resolveRegion");
getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, stsClientCtor) => {
let stsClient;
let closureSourceCreds;
return async (sourceCreds, params) => {
closureSourceCreds = sourceCreds;
if (!stsClient) {
const { logger: logger4 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
const isCompatibleRequestHandler = !isH2(requestHandler);
stsClient = new stsClientCtor({
credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"),
region: resolvedRegion,
requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
logger: logger4
});
}
const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
}
const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
const credentials = {
accessKeyId: Credentials.AccessKeyId,
secretAccessKey: Credentials.SecretAccessKey,
sessionToken: Credentials.SessionToken,
expiration: Credentials.Expiration,
...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
...accountId && { accountId }
};
setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i");
return credentials;
};
}, "getDefaultRoleAssumer");
getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, stsClientCtor) => {
let stsClient;
return async (params) => {
if (!stsClient) {
const { logger: logger4 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
const isCompatibleRequestHandler = !isH2(requestHandler);
stsClient = new stsClientCtor({
region: resolvedRegion,
requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
logger: logger4
});
}
const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
}
const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
const credentials = {
accessKeyId: Credentials.AccessKeyId,
secretAccessKey: Credentials.SecretAccessKey,
sessionToken: Credentials.SessionToken,
expiration: Credentials.Expiration,
...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
...accountId && { accountId }
};
if (accountId) {
setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T");
}
setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
return credentials;
};
}, "getDefaultRoleAssumerWithWebIdentity");
isH2 = /* @__PURE__ */ __name((requestHandler) => {
return requestHandler?.metadata?.handlerProtocol === "h2";
}, "isH2");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/defaultRoleAssumers.js
var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider;
var init_defaultRoleAssumers = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/defaultRoleAssumers.js"() {
init_import_meta_url();
init_defaultStsRoleAssumers();
init_STSClient();
getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => {
if (!customizations)
return baseCtor;
else
return class CustomizableSTSClient extends baseCtor {
static {
__name(this, "CustomizableSTSClient");
}
constructor(config) {
super(config);
for (const customization of customizations) {
this.middlewareStack.use(customization);
}
}
};
}, "getCustomizableStsClientCtor");
getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)), "getDefaultRoleAssumer");
getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity");
decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({
roleAssumer: getDefaultRoleAssumer2(input),
roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
...input
}), "decorateDefaultCredentialProvider");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/index.js
var dist_es_exports6 = {};
__export(dist_es_exports6, {
$Command: () => Command,
AssumeRoleCommand: () => AssumeRoleCommand,
AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
AssumeRoleWithSAMLCommand: () => AssumeRoleWithSAMLCommand,
AssumeRoleWithSAMLRequestFilterSensitiveLog: () => AssumeRoleWithSAMLRequestFilterSensitiveLog,
AssumeRoleWithSAMLResponseFilterSensitiveLog: () => AssumeRoleWithSAMLResponseFilterSensitiveLog,
AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
AssumeRootCommand: () => AssumeRootCommand,
AssumeRootResponseFilterSensitiveLog: () => AssumeRootResponseFilterSensitiveLog,
CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
DecodeAuthorizationMessageCommand: () => DecodeAuthorizationMessageCommand,
ExpiredTokenException: () => ExpiredTokenException2,
GetAccessKeyInfoCommand: () => GetAccessKeyInfoCommand,
GetCallerIdentityCommand: () => GetCallerIdentityCommand,
GetFederationTokenCommand: () => GetFederationTokenCommand,
GetFederationTokenResponseFilterSensitiveLog: () => GetFederationTokenResponseFilterSensitiveLog,
GetSessionTokenCommand: () => GetSessionTokenCommand,
GetSessionTokenResponseFilterSensitiveLog: () => GetSessionTokenResponseFilterSensitiveLog,
IDPCommunicationErrorException: () => IDPCommunicationErrorException,
IDPRejectedClaimException: () => IDPRejectedClaimException,
InvalidAuthorizationMessageException: () => InvalidAuthorizationMessageException,
InvalidIdentityTokenException: () => InvalidIdentityTokenException,
MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
RegionDisabledException: () => RegionDisabledException,
STS: () => STS,
STSClient: () => STSClient,
STSServiceException: () => STSServiceException,
__Client: () => Client,
decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
});
var init_dist_es60 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/client-sts/dist-es/index.js"() {
init_import_meta_url();
init_STSClient();
init_STS();
init_commands4();
init_models3();
init_defaultRoleAssumers();
init_STSServiceException();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js
var isAssumeRoleProfile, isAssumeRoleWithSourceProfile, isCredentialSourceProfile, resolveAssumeRoleCredentials, isCredentialSourceWithoutRoleArn;
var init_resolveAssumeRoleCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js"() {
init_import_meta_url();
init_client5();
init_dist_es17();
init_dist_es38();
init_resolveCredentialSource();
init_resolveProfileData();
isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger: logger4 } = {}) => {
return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger4 }) || isCredentialSourceProfile(arg, { profile, logger: logger4 }));
}, "isAssumeRoleProfile");
isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger4 }) => {
const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
if (withSourceProfile) {
logger4?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
}
return withSourceProfile;
}, "isAssumeRoleWithSourceProfile");
isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger4 }) => {
const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
if (withProviderProfile) {
logger4?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
}
return withProviderProfile;
}, "isCredentialSourceProfile");
resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");
const profileData = profiles[profileName];
const { source_profile, region } = profileData;
if (!options.roleAssumer) {
const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => (init_dist_es60(), dist_es_exports6));
options.roleAssumer = getDefaultRoleAssumer3({
...options.clientConfig,
credentialProviderLogger: options.logger,
parentClientConfig: {
...options?.parentClientConfig,
region: region ?? options?.parentClientConfig?.region
}
}, options.clientPlugins);
}
if (source_profile && source_profile in visitedProfiles) {
throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${getProfileName(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), { logger: options.logger });
}
options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);
const sourceCredsProvider = source_profile ? resolveProfileData(source_profile, profiles, options, {
...visitedProfiles,
[source_profile]: true
}, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();
if (isCredentialSourceWithoutRoleArn(profileData)) {
return sourceCredsProvider.then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
} else {
const params = {
RoleArn: profileData.role_arn,
RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,
ExternalId: profileData.external_id,
DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10)
};
const { mfa_serial } = profileData;
if (mfa_serial) {
if (!options.mfaCodeProvider) {
throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });
}
params.SerialNumber = mfa_serial;
params.TokenCode = await options.mfaCodeProvider(mfa_serial);
}
const sourceCreds = await sourceCredsProvider;
return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
}
}, "resolveAssumeRoleCredentials");
isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => {
return !section.role_arn && !!section.credential_source;
}, "isCredentialSourceWithoutRoleArn");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js
var getValidatedProcessCredentials;
var init_getValidatedProcessCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"() {
init_import_meta_url();
init_client5();
getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => {
if (data.Version !== 1) {
throw Error(`Profile ${profileName} credential_process did not return Version 1.`);
}
if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) {
throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);
}
if (data.Expiration) {
const currentTime = /* @__PURE__ */ new Date();
const expireTime = new Date(data.Expiration);
if (expireTime < currentTime) {
throw Error(`Profile ${profileName} credential_process returned expired credentials.`);
}
}
let accountId = data.AccountId;
if (!accountId && profiles?.[profileName]?.aws_account_id) {
accountId = profiles[profileName].aws_account_id;
}
const credentials = {
accessKeyId: data.AccessKeyId,
secretAccessKey: data.SecretAccessKey,
...data.SessionToken && { sessionToken: data.SessionToken },
...data.Expiration && { expiration: new Date(data.Expiration) },
...data.CredentialScope && { credentialScope: data.CredentialScope },
...accountId && { accountId }
};
setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w");
return credentials;
}, "getValidatedProcessCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js
var import_child_process5, import_util14, resolveProcessCredentials;
var init_resolveProcessCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js"() {
init_import_meta_url();
init_dist_es17();
import_child_process5 = require("child_process");
import_util14 = require("util");
init_getValidatedProcessCredentials();
resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger4) => {
const profile = profiles[profileName];
if (profiles[profileName]) {
const credentialProcess = profile["credential_process"];
if (credentialProcess !== void 0) {
const execPromise = (0, import_util14.promisify)(import_child_process5.exec);
try {
const { stdout: stdout2 } = await execPromise(credentialProcess);
let data;
try {
data = JSON.parse(stdout2.trim());
} catch {
throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);
}
return getValidatedProcessCredentials(profileName, data, profiles);
} catch (error2) {
throw new CredentialsProviderError(error2.message, { logger: logger4 });
}
} else {
throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger4 });
}
} else {
throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {
logger: logger4
});
}
}, "resolveProcessCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js
var fromProcess;
var init_fromProcess = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js"() {
init_import_meta_url();
init_dist_es38();
init_resolveProcessCredentials();
fromProcess = /* @__PURE__ */ __name((init3 = {}) => async ({ callerClientConfig } = {}) => {
init3.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");
const profiles = await parseKnownFiles(init3);
return resolveProcessCredentials(getProfileName({
profile: init3.profile ?? callerClientConfig?.profile
}), profiles, init3.logger);
}, "fromProcess");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/index.js
var dist_es_exports7 = {};
__export(dist_es_exports7, {
fromProcess: () => fromProcess
});
var init_dist_es61 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.716.0/node_modules/@aws-sdk/credential-provider-process/dist-es/index.js"() {
init_import_meta_url();
init_fromProcess();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js
var isProcessProfile, resolveProcessCredentials2;
var init_resolveProcessCredentials2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js"() {
init_import_meta_url();
init_client5();
isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile");
resolveProcessCredentials2 = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => (init_dist_es61(), dist_es_exports7)).then(({ fromProcess: fromProcess2 }) => fromProcess2({
...options,
profile
})().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))), "resolveProcessCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js
var resolveSsoCredentials, isSsoProfile2;
var init_resolveSsoCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js"() {
init_import_meta_url();
init_client5();
resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => {
const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es59(), dist_es_exports5));
return fromSSO2({
profile,
logger: options.logger,
parentClientConfig: options.parentClientConfig,
clientConfig: options.clientConfig
})().then((creds) => {
if (profileData.sso_session) {
return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r");
} else {
return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t");
}
});
}, "resolveSsoCredentials");
isSsoProfile2 = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js
var isStaticCredsProfile, resolveStaticCredentials;
var init_resolveStaticCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js"() {
init_import_meta_url();
init_client5();
isStaticCredsProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile");
resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => {
options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");
const credentials = {
accessKeyId: profile.aws_access_key_id,
secretAccessKey: profile.aws_secret_access_key,
sessionToken: profile.aws_session_token,
...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope },
...profile.aws_account_id && { accountId: profile.aws_account_id }
};
return setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n");
}, "resolveStaticCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.716.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js
var fromWebToken;
var init_fromWebToken = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.716.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"() {
init_import_meta_url();
fromWebToken = /* @__PURE__ */ __name((init3) => async (awsIdentityProperties) => {
init3.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init3;
let { roleAssumerWithWebIdentity } = init3;
if (!roleAssumerWithWebIdentity) {
const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => (init_dist_es60(), dist_es_exports6));
roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
...init3.clientConfig,
credentialProviderLogger: init3.logger,
parentClientConfig: {
...awsIdentityProperties?.callerClientConfig,
...init3.parentClientConfig
}
}, init3.clientPlugins);
}
return roleAssumerWithWebIdentity({
RoleArn: roleArn,
RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
WebIdentityToken: webIdentityToken,
ProviderId: providerId,
PolicyArns: policyArns,
Policy: policy,
DurationSeconds: durationSeconds
});
}, "fromWebToken");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.716.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js
var import_fs22, ENV_TOKEN_FILE, ENV_ROLE_ARN, ENV_ROLE_SESSION_NAME, fromTokenFile;
var init_fromTokenFile = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.716.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js"() {
init_import_meta_url();
init_client5();
init_dist_es17();
import_fs22 = require("fs");
init_fromWebToken();
ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
ENV_ROLE_ARN = "AWS_ROLE_ARN";
ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
fromTokenFile = /* @__PURE__ */ __name((init3 = {}) => async () => {
init3.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
const webIdentityTokenFile = init3?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];
const roleArn = init3?.roleArn ?? process.env[ENV_ROLE_ARN];
const roleSessionName = init3?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];
if (!webIdentityTokenFile || !roleArn) {
throw new CredentialsProviderError("Web identity configuration not specified", {
logger: init3.logger
});
}
const credentials = await fromWebToken({
...init3,
webIdentityToken: (0, import_fs22.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
roleArn,
roleSessionName
})();
if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
}
return credentials;
}, "fromTokenFile");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.716.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js
var dist_es_exports8 = {};
__export(dist_es_exports8, {
fromTokenFile: () => fromTokenFile,
fromWebToken: () => fromWebToken
});
var init_dist_es62 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.716.0_@aws-sdk+client-sts@3.721.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js"() {
init_import_meta_url();
init_fromTokenFile();
init_fromWebToken();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js
var isWebIdentityProfile, resolveWebIdentityCredentials;
var init_resolveWebIdentityCredentials = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"() {
init_import_meta_url();
init_client5();
isWebIdentityProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, "isWebIdentityProfile");
resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => (init_dist_es62(), dist_es_exports8)).then(({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({
webIdentityTokenFile: profile.web_identity_token_file,
roleArn: profile.role_arn,
roleSessionName: profile.role_session_name,
roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,
logger: options.logger,
parentClientConfig: options.parentClientConfig
})().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))), "resolveWebIdentityCredentials");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js
var resolveProfileData;
var init_resolveProfileData = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js"() {
init_import_meta_url();
init_dist_es17();
init_resolveAssumeRoleCredentials();
init_resolveProcessCredentials2();
init_resolveSsoCredentials();
init_resolveStaticCredentials();
init_resolveWebIdentityCredentials();
resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {
const data = profiles[profileName];
if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
return resolveStaticCredentials(data, options);
}
if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {
return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
}
if (isStaticCredsProfile(data)) {
return resolveStaticCredentials(data, options);
}
if (isWebIdentityProfile(data)) {
return resolveWebIdentityCredentials(data, options);
}
if (isProcessProfile(data)) {
return resolveProcessCredentials2(options, profileName);
}
if (isSsoProfile2(data)) {
return await resolveSsoCredentials(profileName, data, options);
}
throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });
}, "resolveProfileData");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js
var fromIni;
var init_fromIni = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js"() {
init_import_meta_url();
init_dist_es38();
init_resolveProfileData();
fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => {
const init3 = {
..._init,
parentClientConfig: {
...callerClientConfig,
..._init.parentClientConfig
}
};
init3.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");
const profiles = await parseKnownFiles(init3);
return resolveProfileData(getProfileName({
profile: _init.profile ?? callerClientConfig?.profile
}), profiles, init3);
}, "fromIni");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js
var dist_es_exports9 = {};
__export(dist_es_exports9, {
fromIni: () => fromIni
});
var init_dist_es63 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-sts_i6jy2uxuokszxcyf4p6ncee4ju/node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js"() {
init_import_meta_url();
init_fromIni();
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-st_nxdfcqjud2svw42kuw6i2zwn6q/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js
var multipleCredentialSourceWarningEmitted, defaultProvider, credentialsWillNeedRefresh, credentialsTreatedAsExpired;
var init_defaultProvider = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-st_nxdfcqjud2svw42kuw6i2zwn6q/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js"() {
init_import_meta_url();
init_dist_es48();
init_dist_es17();
init_dist_es38();
init_remoteProvider();
multipleCredentialSourceWarningEmitted = false;
defaultProvider = /* @__PURE__ */ __name((init3 = {}) => memoize(chain(async () => {
const profile = init3.profile ?? process.env[ENV_PROFILE];
if (profile) {
const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];
if (envStaticCredentialsAreSet) {
if (!multipleCredentialSourceWarningEmitted) {
const warnFn = init3.logger?.warn && init3.logger?.constructor?.name !== "NoOpLogger" ? init3.logger.warn : console.warn;
warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
Multiple credential sources detected:
Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
This SDK will proceed with the AWS_PROFILE value.
However, a future version may change this behavior to prefer the ENV static credentials.
Please ensure that your environment only sets either the AWS_PROFILE or the
AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
`);
multipleCredentialSourceWarningEmitted = true;
}
}
throw new CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
logger: init3.logger,
tryNextLink: true
});
}
init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
return fromEnv2(init3)();
}, async () => {
init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init3;
if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
throw new CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init3.logger });
}
const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es59(), dist_es_exports5));
return fromSSO2(init3)();
}, async () => {
init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
const { fromIni: fromIni2 } = await Promise.resolve().then(() => (init_dist_es63(), dist_es_exports9));
return fromIni2(init3)();
}, async () => {
init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
const { fromProcess: fromProcess2 } = await Promise.resolve().then(() => (init_dist_es61(), dist_es_exports7));
return fromProcess2(init3)();
}, async () => {
init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => (init_dist_es62(), dist_es_exports8));
return fromTokenFile2(init3)();
}, async () => {
init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
return (await remoteProvider(init3))();
}, async () => {
throw new CredentialsProviderError("Could not load credentials from any providers", {
tryNextLink: false,
logger: init3.logger
});
}), credentialsTreatedAsExpired, credentialsWillNeedRefresh), "defaultProvider");
credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh");
credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired");
}
});
// ../../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-st_nxdfcqjud2svw42kuw6i2zwn6q/node_modules/@aws-sdk/credential-provider-node/dist-es/index.js
var init_dist_es64 = __esm({
"../../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.721.0_@aws-sdk+client-sso-oidc@3.721.0_@aws-sdk+client-st_nxdfcqjud2svw42kuw6i2zwn6q/node_modules/@aws-sdk/credential-provider-node/dist-es/index.js"() {
init_import_meta_url();
init_defaultProvider();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/NodeDisableMultiregionAccessPointConfigOptions.js
var init_NodeDisableMultiregionAccessPointConfigOptions = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/NodeDisableMultiregionAccessPointConfigOptions.js"() {
init_import_meta_url();
init_dist_es29();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/NodeUseArnRegionConfigOptions.js
var NODE_USE_ARN_REGION_ENV_NAME, NODE_USE_ARN_REGION_INI_NAME, NODE_USE_ARN_REGION_CONFIG_OPTIONS;
var init_NodeUseArnRegionConfigOptions = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/NodeUseArnRegionConfigOptions.js"() {
init_import_meta_url();
init_dist_es29();
NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION";
NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region";
NODE_USE_ARN_REGION_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env6) => booleanSelector(env6, NODE_USE_ARN_REGION_ENV_NAME, SelectorType2.ENV), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => booleanSelector(profile, NODE_USE_ARN_REGION_INI_NAME, SelectorType2.CONFIG), "configFileSelector"),
default: false
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/bucketHostnameUtils.js
var init_bucketHostnameUtils = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/bucketHostnameUtils.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/bucketHostname.js
var init_bucketHostname = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/bucketHostname.js"() {
init_import_meta_url();
init_bucketHostnameUtils();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/bucketEndpointMiddleware.js
var init_bucketEndpointMiddleware = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/bucketEndpointMiddleware.js"() {
init_import_meta_url();
init_dist_es30();
init_dist_es2();
init_bucketHostname();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/configurations.js
var init_configurations3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/configurations.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/index.js
var init_dist_es65 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.721.0/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/index.js"() {
init_import_meta_url();
init_NodeDisableMultiregionAccessPointConfigOptions();
init_NodeUseArnRegionConfigOptions();
init_bucketEndpointMiddleware();
init_bucketHostname();
init_configurations3();
init_bucketHostnameUtils();
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/Int64.js
function negate2(bytes) {
for (let i5 = 0; i5 < 8; i5++) {
bytes[i5] ^= 255;
}
for (let i5 = 7; i5 > -1; i5--) {
bytes[i5]++;
if (bytes[i5] !== 0)
break;
}
}
var Int642;
var init_Int64 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/Int64.js"() {
init_import_meta_url();
init_dist_es14();
Int642 = class _Int64 {
static {
__name(this, "Int64");
}
constructor(bytes) {
this.bytes = bytes;
if (bytes.byteLength !== 8) {
throw new Error("Int64 buffers must be exactly 8 bytes");
}
}
static fromNumber(number) {
if (number > 9223372036854776e3 || number < -9223372036854776e3) {
throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
}
const bytes = new Uint8Array(8);
for (let i5 = 7, remaining = Math.abs(Math.round(number)); i5 > -1 && remaining > 0; i5--, remaining /= 256) {
bytes[i5] = remaining;
}
if (number < 0) {
negate2(bytes);
}
return new _Int64(bytes);
}
valueOf() {
const bytes = this.bytes.slice(0);
const negative = bytes[0] & 128;
if (negative) {
negate2(bytes);
}
return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
}
toString() {
return String(this.valueOf());
}
};
__name(negate2, "negate");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js
var HeaderMarshaller, HEADER_VALUE_TYPE2, BOOLEAN_TAG, BYTE_TAG, SHORT_TAG, INT_TAG, LONG_TAG, BINARY_TAG, STRING_TAG, TIMESTAMP_TAG, UUID_TAG, UUID_PATTERN2;
var init_HeaderMarshaller = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js"() {
init_import_meta_url();
init_dist_es14();
init_Int64();
HeaderMarshaller = class {
static {
__name(this, "HeaderMarshaller");
}
constructor(toUtf82, fromUtf84) {
this.toUtf8 = toUtf82;
this.fromUtf8 = fromUtf84;
}
format(headers) {
const chunks = [];
for (const headerName of Object.keys(headers)) {
const bytes = this.fromUtf8(headerName);
chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
}
const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
let position = 0;
for (const chunk of chunks) {
out.set(chunk, position);
position += chunk.byteLength;
}
return out;
}
formatHeaderValue(header) {
switch (header.type) {
case "boolean":
return Uint8Array.from([header.value ? 0 : 1]);
case "byte":
return Uint8Array.from([2, header.value]);
case "short":
const shortView = new DataView(new ArrayBuffer(3));
shortView.setUint8(0, 3);
shortView.setInt16(1, header.value, false);
return new Uint8Array(shortView.buffer);
case "integer":
const intView = new DataView(new ArrayBuffer(5));
intView.setUint8(0, 4);
intView.setInt32(1, header.value, false);
return new Uint8Array(intView.buffer);
case "long":
const longBytes = new Uint8Array(9);
longBytes[0] = 5;
longBytes.set(header.value.bytes, 1);
return longBytes;
case "binary":
const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
binView.setUint8(0, 6);
binView.setUint16(1, header.value.byteLength, false);
const binBytes = new Uint8Array(binView.buffer);
binBytes.set(header.value, 3);
return binBytes;
case "string":
const utf8Bytes = this.fromUtf8(header.value);
const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
strView.setUint8(0, 7);
strView.setUint16(1, utf8Bytes.byteLength, false);
const strBytes = new Uint8Array(strView.buffer);
strBytes.set(utf8Bytes, 3);
return strBytes;
case "timestamp":
const tsBytes = new Uint8Array(9);
tsBytes[0] = 8;
tsBytes.set(Int642.fromNumber(header.value.valueOf()).bytes, 1);
return tsBytes;
case "uuid":
if (!UUID_PATTERN2.test(header.value)) {
throw new Error(`Invalid UUID received: ${header.value}`);
}
const uuidBytes = new Uint8Array(17);
uuidBytes[0] = 9;
uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
return uuidBytes;
}
}
parse(headers) {
const out = {};
let position = 0;
while (position < headers.byteLength) {
const nameLength = headers.getUint8(position++);
const name2 = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength));
position += nameLength;
switch (headers.getUint8(position++)) {
case 0:
out[name2] = {
type: BOOLEAN_TAG,
value: true
};
break;
case 1:
out[name2] = {
type: BOOLEAN_TAG,
value: false
};
break;
case 2:
out[name2] = {
type: BYTE_TAG,
value: headers.getInt8(position++)
};
break;
case 3:
out[name2] = {
type: SHORT_TAG,
value: headers.getInt16(position, false)
};
position += 2;
break;
case 4:
out[name2] = {
type: INT_TAG,
value: headers.getInt32(position, false)
};
position += 4;
break;
case 5:
out[name2] = {
type: LONG_TAG,
value: new Int642(new Uint8Array(headers.buffer, headers.byteOffset + position, 8))
};
position += 8;
break;
case 6:
const binaryLength = headers.getUint16(position, false);
position += 2;
out[name2] = {
type: BINARY_TAG,
value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength)
};
position += binaryLength;
break;
case 7:
const stringLength = headers.getUint16(position, false);
position += 2;
out[name2] = {
type: STRING_TAG,
value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength))
};
position += stringLength;
break;
case 8:
out[name2] = {
type: TIMESTAMP_TAG,
value: new Date(new Int642(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf())
};
position += 8;
break;
case 9:
const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16);
position += 16;
out[name2] = {
type: UUID_TAG,
value: `${toHex(uuidBytes.subarray(0, 4))}-${toHex(uuidBytes.subarray(4, 6))}-${toHex(uuidBytes.subarray(6, 8))}-${toHex(uuidBytes.subarray(8, 10))}-${toHex(uuidBytes.subarray(10))}`
};
break;
default:
throw new Error(`Unrecognized header type tag`);
}
}
return out;
}
};
(function(HEADER_VALUE_TYPE3) {
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp";
HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid";
})(HEADER_VALUE_TYPE2 || (HEADER_VALUE_TYPE2 = {}));
BOOLEAN_TAG = "boolean";
BYTE_TAG = "byte";
SHORT_TAG = "short";
INT_TAG = "integer";
LONG_TAG = "long";
BINARY_TAG = "binary";
STRING_TAG = "string";
TIMESTAMP_TAG = "timestamp";
UUID_TAG = "uuid";
UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js
function splitMessage({ byteLength, byteOffset, buffer }) {
if (byteLength < MINIMUM_MESSAGE_LENGTH) {
throw new Error("Provided message too short to accommodate event stream message overhead");
}
const view = new DataView(buffer, byteOffset, byteLength);
const messageLength = view.getUint32(0, false);
if (byteLength !== messageLength) {
throw new Error("Reported message length does not match received message length");
}
const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false);
const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false);
const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false);
const checksummer = new Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH));
if (expectedPreludeChecksum !== checksummer.digest()) {
throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);
}
checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)));
if (expectedMessageChecksum !== checksummer.digest()) {
throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);
}
return {
headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength),
body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH))
};
}
var PRELUDE_MEMBER_LENGTH, PRELUDE_LENGTH, CHECKSUM_LENGTH, MINIMUM_MESSAGE_LENGTH;
var init_splitMessage = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js"() {
init_import_meta_url();
init_module3();
PRELUDE_MEMBER_LENGTH = 4;
PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2;
CHECKSUM_LENGTH = 4;
MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2;
__name(splitMessage, "splitMessage");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js
var EventStreamCodec;
var init_EventStreamCodec = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js"() {
init_import_meta_url();
init_module3();
init_HeaderMarshaller();
init_splitMessage();
EventStreamCodec = class {
static {
__name(this, "EventStreamCodec");
}
constructor(toUtf82, fromUtf84) {
this.headerMarshaller = new HeaderMarshaller(toUtf82, fromUtf84);
this.messageBuffer = [];
this.isEndOfStream = false;
}
feed(message) {
this.messageBuffer.push(this.decode(message));
}
endOfStream() {
this.isEndOfStream = true;
}
getMessage() {
const message = this.messageBuffer.pop();
const isEndOfStream = this.isEndOfStream;
return {
getMessage() {
return message;
},
isEndOfStream() {
return isEndOfStream;
}
};
}
getAvailableMessages() {
const messages = this.messageBuffer;
this.messageBuffer = [];
const isEndOfStream = this.isEndOfStream;
return {
getMessages() {
return messages;
},
isEndOfStream() {
return isEndOfStream;
}
};
}
encode({ headers: rawHeaders, body }) {
const headers = this.headerMarshaller.format(rawHeaders);
const length = headers.byteLength + body.byteLength + 16;
const out = new Uint8Array(length);
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
const checksum = new Crc32();
view.setUint32(0, length, false);
view.setUint32(4, headers.byteLength, false);
view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false);
out.set(headers, 12);
out.set(body, headers.byteLength + 12);
view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false);
return out;
}
decode(message) {
const { headers, body } = splitMessage(message);
return { headers: this.headerMarshaller.parse(headers), body };
}
formatHeaders(rawHeaders) {
return this.headerMarshaller.format(rawHeaders);
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/Message.js
var init_Message = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/Message.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js
var MessageDecoderStream;
var init_MessageDecoderStream = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js"() {
init_import_meta_url();
MessageDecoderStream = class {
static {
__name(this, "MessageDecoderStream");
}
constructor(options) {
this.options = options;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async *asyncIterator() {
for await (const bytes of this.options.inputStream) {
const decoded = this.options.decoder.decode(bytes);
yield decoded;
}
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js
var MessageEncoderStream;
var init_MessageEncoderStream = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js"() {
init_import_meta_url();
MessageEncoderStream = class {
static {
__name(this, "MessageEncoderStream");
}
constructor(options) {
this.options = options;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async *asyncIterator() {
for await (const msg of this.options.messageStream) {
const encoded = this.options.encoder.encode(msg);
yield encoded;
}
if (this.options.includeEndFrame) {
yield new Uint8Array(0);
}
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js
var SmithyMessageDecoderStream;
var init_SmithyMessageDecoderStream = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js"() {
init_import_meta_url();
SmithyMessageDecoderStream = class {
static {
__name(this, "SmithyMessageDecoderStream");
}
constructor(options) {
this.options = options;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async *asyncIterator() {
for await (const message of this.options.messageStream) {
const deserialized = await this.options.deserializer(message);
if (deserialized === void 0)
continue;
yield deserialized;
}
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js
var SmithyMessageEncoderStream;
var init_SmithyMessageEncoderStream = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js"() {
init_import_meta_url();
SmithyMessageEncoderStream = class {
static {
__name(this, "SmithyMessageEncoderStream");
}
constructor(options) {
this.options = options;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async *asyncIterator() {
for await (const chunk of this.options.inputStream) {
const payloadBuf = this.options.serializer(chunk);
yield payloadBuf;
}
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/index.js
var init_dist_es66 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-codec@3.1.10/node_modules/@smithy/eventstream-codec/dist-es/index.js"() {
init_import_meta_url();
init_EventStreamCodec();
init_HeaderMarshaller();
init_Int64();
init_Message();
init_MessageDecoderStream();
init_MessageEncoderStream();
init_SmithyMessageDecoderStream();
init_SmithyMessageEncoderStream();
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js
function getChunkedStream(source) {
let currentMessageTotalLength = 0;
let currentMessagePendingLength = 0;
let currentMessage = null;
let messageLengthBuffer = null;
const allocateMessage = /* @__PURE__ */ __name((size) => {
if (typeof size !== "number") {
throw new Error("Attempted to allocate an event message where size was not a number: " + size);
}
currentMessageTotalLength = size;
currentMessagePendingLength = 4;
currentMessage = new Uint8Array(size);
const currentMessageView = new DataView(currentMessage.buffer);
currentMessageView.setUint32(0, size, false);
}, "allocateMessage");
const iterator = /* @__PURE__ */ __name(async function* () {
const sourceIterator = source[Symbol.asyncIterator]();
while (true) {
const { value, done } = await sourceIterator.next();
if (done) {
if (!currentMessageTotalLength) {
return;
} else if (currentMessageTotalLength === currentMessagePendingLength) {
yield currentMessage;
} else {
throw new Error("Truncated event message received.");
}
return;
}
const chunkLength = value.length;
let currentOffset = 0;
while (currentOffset < chunkLength) {
if (!currentMessage) {
const bytesRemaining = chunkLength - currentOffset;
if (!messageLengthBuffer) {
messageLengthBuffer = new Uint8Array(4);
}
const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining);
messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength);
currentMessagePendingLength += numBytesForTotal;
currentOffset += numBytesForTotal;
if (currentMessagePendingLength < 4) {
break;
}
allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false));
messageLengthBuffer = null;
}
const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset);
currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength);
currentMessagePendingLength += numBytesToWrite;
currentOffset += numBytesToWrite;
if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) {
yield currentMessage;
currentMessage = null;
currentMessageTotalLength = 0;
currentMessagePendingLength = 0;
}
}
}
}, "iterator");
return {
[Symbol.asyncIterator]: iterator
};
}
var init_getChunkedStream = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js"() {
init_import_meta_url();
__name(getChunkedStream, "getChunkedStream");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js
function getMessageUnmarshaller(deserializer, toUtf82) {
return async function(message) {
const { value: messageType } = message.headers[":message-type"];
if (messageType === "error") {
const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
unmodeledError.name = message.headers[":error-code"].value;
throw unmodeledError;
} else if (messageType === "exception") {
const code = message.headers[":exception-type"].value;
const exception = { [code]: message };
const deserializedException = await deserializer(exception);
if (deserializedException.$unknown) {
const error2 = new Error(toUtf82(message.body));
error2.name = code;
throw error2;
}
throw deserializedException[code];
} else if (messageType === "event") {
const event = {
[message.headers[":event-type"].value]: message
};
const deserialized = await deserializer(event);
if (deserialized.$unknown)
return;
return deserialized;
} else {
throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`);
}
};
}
var init_getUnmarshalledStream = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js"() {
init_import_meta_url();
__name(getMessageUnmarshaller, "getMessageUnmarshaller");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js
var EventStreamMarshaller;
var init_EventStreamMarshaller = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js"() {
init_import_meta_url();
init_dist_es66();
init_getChunkedStream();
init_getUnmarshalledStream();
EventStreamMarshaller = class {
static {
__name(this, "EventStreamMarshaller");
}
constructor({ utf8Encoder, utf8Decoder }) {
this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder);
this.utfEncoder = utf8Encoder;
}
deserialize(body, deserializer) {
const inputStream = getChunkedStream(body);
return new SmithyMessageDecoderStream({
messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }),
deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder)
});
}
serialize(inputStream, serializer) {
return new MessageEncoderStream({
messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }),
encoder: this.eventStreamCodec,
includeEndFrame: true
});
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/provider.js
var init_provider = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/provider.js"() {
init_import_meta_url();
init_EventStreamMarshaller();
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/index.js
var init_dist_es67 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-universal@3.0.13/node_modules/@smithy/eventstream-serde-universal/dist-es/index.js"() {
init_import_meta_url();
init_EventStreamMarshaller();
init_provider();
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/utils.js
async function* readabletoIterable(readStream) {
let streamEnded = false;
let generationEnded = false;
const records = new Array();
readStream.on("error", (err) => {
if (!streamEnded) {
streamEnded = true;
}
if (err) {
throw err;
}
});
readStream.on("data", (data) => {
records.push(data);
});
readStream.on("end", () => {
streamEnded = true;
});
while (!generationEnded) {
const value = await new Promise((resolve25) => setTimeout(() => resolve25(records.shift()), 0));
if (value) {
yield value;
}
generationEnded = streamEnded && records.length === 0;
}
}
var init_utils9 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/utils.js"() {
init_import_meta_url();
__name(readabletoIterable, "readabletoIterable");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js
var import_stream13, EventStreamMarshaller2;
var init_EventStreamMarshaller2 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js"() {
init_import_meta_url();
init_dist_es67();
import_stream13 = require("stream");
init_utils9();
EventStreamMarshaller2 = class {
static {
__name(this, "EventStreamMarshaller");
}
constructor({ utf8Encoder, utf8Decoder }) {
this.universalMarshaller = new EventStreamMarshaller({
utf8Decoder,
utf8Encoder
});
}
deserialize(body, deserializer) {
const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body);
return this.universalMarshaller.deserialize(bodyIterable, deserializer);
}
serialize(input, serializer) {
return import_stream13.Readable.from(this.universalMarshaller.serialize(input, serializer));
}
};
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/provider.js
var eventStreamSerdeProvider;
var init_provider2 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/provider.js"() {
init_import_meta_url();
init_EventStreamMarshaller2();
eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller2(options), "eventStreamSerdeProvider");
}
});
// ../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/index.js
var init_dist_es68 = __esm({
"../../node_modules/.pnpm/@smithy+eventstream-serde-node@3.0.13/node_modules/@smithy/eventstream-serde-node/dist-es/index.js"() {
init_import_meta_url();
init_EventStreamMarshaller2();
init_provider2();
}
});
// ../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/HashCalculator.js
var import_stream14, HashCalculator;
var init_HashCalculator = __esm({
"../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/HashCalculator.js"() {
init_import_meta_url();
init_dist_es8();
import_stream14 = require("stream");
HashCalculator = class extends import_stream14.Writable {
static {
__name(this, "HashCalculator");
}
constructor(hash, options) {
super(options);
this.hash = hash;
}
_write(chunk, encoding, callback) {
try {
this.hash.update(toUint8Array(chunk));
} catch (err) {
return callback(err);
}
callback();
}
};
}
});
// ../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/fileStreamHasher.js
var init_fileStreamHasher = __esm({
"../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/fileStreamHasher.js"() {
init_import_meta_url();
init_HashCalculator();
}
});
// ../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/readableStreamHasher.js
var readableStreamHasher;
var init_readableStreamHasher = __esm({
"../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/readableStreamHasher.js"() {
init_import_meta_url();
init_HashCalculator();
readableStreamHasher = /* @__PURE__ */ __name((hashCtor, readableStream) => {
if (readableStream.readableFlowing !== null) {
throw new Error("Unable to calculate hash for flowing readable stream");
}
const hash = new hashCtor();
const hashCalculator = new HashCalculator(hash);
readableStream.pipe(hashCalculator);
return new Promise((resolve25, reject) => {
readableStream.on("error", (err) => {
hashCalculator.end();
reject(err);
});
hashCalculator.on("error", reject);
hashCalculator.on("finish", () => {
hash.digest().then(resolve25).catch(reject);
});
});
}, "readableStreamHasher");
}
});
// ../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/index.js
var init_dist_es69 = __esm({
"../../node_modules/.pnpm/@smithy+hash-stream-node@3.1.10/node_modules/@smithy/hash-stream-node/dist-es/index.js"() {
init_import_meta_url();
init_fileStreamHasher();
init_readableStreamHasher();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.shared.js
var getRuntimeConfig7;
var init_runtimeConfig_shared4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.shared.js"() {
init_import_meta_url();
init_dist_es21();
init_dist_es46();
init_dist_es20();
init_dist_es41();
init_dist_es9();
init_dist_es15();
init_dist_es8();
init_httpAuthSchemeProvider();
init_endpointResolver();
getRuntimeConfig7 = /* @__PURE__ */ __name((config) => {
return {
apiVersion: "2006-03-01",
base64Decoder: config?.base64Decoder ?? fromBase64,
base64Encoder: config?.base64Encoder ?? toBase64,
disableHostPrefix: config?.disableHostPrefix ?? false,
endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,
extensions: config?.extensions ?? [],
getAwsChunkedEncodingStream: config?.getAwsChunkedEncodingStream ?? getAwsChunkedEncodingStream,
httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultS3HttpAuthSchemeProvider,
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), "identityProvider"),
signer: new AwsSdkSigV4Signer()
},
{
schemeId: "aws.auth#sigv4a",
identityProvider: /* @__PURE__ */ __name((ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), "identityProvider"),
signer: new AwsSdkSigV4ASigner()
}
],
logger: config?.logger ?? new NoOpLogger(),
sdkStreamMixin: config?.sdkStreamMixin ?? sdkStreamMixin2,
serviceId: config?.serviceId ?? "S3",
signerConstructor: config?.signerConstructor ?? SignatureV4MultiRegion,
signingEscapePath: config?.signingEscapePath ?? false,
urlParser: config?.urlParser ?? parseUrl,
useArnRegion: config?.useArnRegion ?? false,
utf8Decoder: config?.utf8Decoder ?? fromUtf8,
utf8Encoder: config?.utf8Encoder ?? toUtf8
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js
var getRuntimeConfig8;
var init_runtimeConfig4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js"() {
init_import_meta_url();
init_package2();
init_dist_es21();
init_dist_es64();
init_dist_es65();
init_dist_es25();
init_dist_es31();
init_dist_es51();
init_dist_es35();
init_dist_es68();
init_dist_es52();
init_dist_es69();
init_dist_es45();
init_dist_es39();
init_dist_es12();
init_dist_es53();
init_dist_es44();
init_runtimeConfig_shared4();
init_dist_es20();
init_dist_es54();
init_dist_es20();
getRuntimeConfig8 = /* @__PURE__ */ __name((config) => {
emitWarningIfUnsupportedVersion2(process.version);
const defaultsMode = resolveDefaultsModeConfig(config);
const defaultConfigProvider = /* @__PURE__ */ __name(() => defaultsMode().then(loadConfigsForDefaultMode), "defaultConfigProvider");
const clientSharedValues = getRuntimeConfig7(config);
emitWarningIfUnsupportedVersion(process.version);
const profileConfig = { profile: config?.profile };
return {
...clientSharedValues,
...config,
runtime: "node",
defaultsMode,
bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider,
defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
disableS3ExpressSessionAuth: config?.disableS3ExpressSessionAuth ?? loadConfig(NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, profileConfig),
eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider,
maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
md5: config?.md5 ?? Hash.bind(null, "md5"),
region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...profileConfig }),
requestChecksumCalculation: config?.requestChecksumCalculation ?? loadConfig(NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, profileConfig),
requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
responseChecksumValidation: config?.responseChecksumValidation ?? loadConfig(NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, profileConfig),
retryMode: config?.retryMode ?? loadConfig({
...NODE_RETRY_MODE_CONFIG_OPTIONS,
default: /* @__PURE__ */ __name(async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, "default")
}, config),
sha1: config?.sha1 ?? Hash.bind(null, "sha1"),
sha256: config?.sha256 ?? Hash.bind(null, "sha256"),
sigv4aSigningRegionSet: config?.sigv4aSigningRegionSet ?? loadConfig(NODE_SIGV4A_CONFIG_OPTIONS, profileConfig),
streamCollector: config?.streamCollector ?? streamCollector,
streamHasher: config?.streamHasher ?? readableStreamHasher,
useArnRegion: config?.useArnRegion ?? loadConfig(NODE_USE_ARN_REGION_CONFIG_OPTIONS, profileConfig),
useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, profileConfig),
useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, profileConfig),
userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, profileConfig)
};
}, "getRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration4, resolveHttpAuthRuntimeConfig4;
var init_httpAuthExtensionConfiguration4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthExtensionConfiguration.js"() {
init_import_meta_url();
getHttpAuthExtensionConfiguration4 = /* @__PURE__ */ __name((runtimeConfig) => {
const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
let _credentials = runtimeConfig.credentials;
return {
setHttpAuthScheme(httpAuthScheme) {
const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
if (index === -1) {
_httpAuthSchemes.push(httpAuthScheme);
} else {
_httpAuthSchemes.splice(index, 1, httpAuthScheme);
}
},
httpAuthSchemes() {
return _httpAuthSchemes;
},
setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
_httpAuthSchemeProvider = httpAuthSchemeProvider;
},
httpAuthSchemeProvider() {
return _httpAuthSchemeProvider;
},
setCredentials(credentials) {
_credentials = credentials;
},
credentials() {
return _credentials;
}
};
}, "getHttpAuthExtensionConfiguration");
resolveHttpAuthRuntimeConfig4 = /* @__PURE__ */ __name((config) => {
return {
httpAuthSchemes: config.httpAuthSchemes(),
httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
credentials: config.credentials()
};
}, "resolveHttpAuthRuntimeConfig");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js
var asPartial4, resolveRuntimeExtensions4;
var init_runtimeExtensions4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js"() {
init_import_meta_url();
init_dist_es55();
init_dist_es2();
init_dist_es20();
init_httpAuthExtensionConfiguration4();
asPartial4 = /* @__PURE__ */ __name((t7) => t7, "asPartial");
resolveRuntimeExtensions4 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
const extensionConfiguration = {
...asPartial4(getAwsRegionExtensionConfiguration(runtimeConfig)),
...asPartial4(getDefaultExtensionConfiguration(runtimeConfig)),
...asPartial4(getHttpHandlerExtensionConfiguration(runtimeConfig)),
...asPartial4(getHttpAuthExtensionConfiguration4(runtimeConfig))
};
extensions.forEach((extension) => extension.configure(extensionConfiguration));
return {
...runtimeConfig,
...resolveAwsRegionExtensionConfiguration(extensionConfiguration),
...resolveDefaultRuntimeConfig(extensionConfiguration),
...resolveHttpHandlerRuntimeConfig(extensionConfiguration),
...resolveHttpAuthRuntimeConfig4(extensionConfiguration)
};
}, "resolveRuntimeExtensions");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/S3Client.js
var S3Client;
var init_S3Client = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/S3Client.js"() {
init_import_meta_url();
init_dist_es3();
init_dist_es25();
init_dist_es26();
init_dist_es27();
init_dist_es28();
init_dist_es31();
init_dist_es34();
init_dist_es35();
init_dist_es16();
init_dist_es36();
init_dist_es37();
init_dist_es42();
init_dist_es45();
init_dist_es20();
init_httpAuthSchemeProvider();
init_CreateSessionCommand();
init_EndpointParameters();
init_runtimeConfig4();
init_runtimeExtensions4();
S3Client = class extends Client {
static {
__name(this, "S3Client");
}
constructor(...[configuration]) {
const _config_0 = getRuntimeConfig8(configuration || {});
const _config_1 = resolveClientEndpointParameters(_config_0);
const _config_2 = resolveUserAgentConfig(_config_1);
const _config_3 = resolveFlexibleChecksumsConfig(_config_2);
const _config_4 = resolveRetryConfig(_config_3);
const _config_5 = resolveRegionConfig(_config_4);
const _config_6 = resolveHostHeaderConfig(_config_5);
const _config_7 = resolveEndpointConfig(_config_6);
const _config_8 = resolveEventStreamSerdeConfig(_config_7);
const _config_9 = resolveHttpAuthSchemeConfig(_config_8);
const _config_10 = resolveS3Config(_config_9, { session: [() => this, CreateSessionCommand] });
const _config_11 = resolveRuntimeExtensions4(_config_10, configuration?.extensions || []);
super(_config_11);
this.config = _config_11;
this.middlewareStack.use(getUserAgentPlugin(this.config));
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
httpAuthSchemeParametersProvider: defaultS3HttpAuthSchemeParametersProvider,
identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new DefaultIdentityProviderConfig({
"aws.auth#sigv4": config.credentials,
"aws.auth#sigv4a": config.credentials
}), "identityProviderConfigProvider")
}));
this.middlewareStack.use(getHttpSigningPlugin(this.config));
this.middlewareStack.use(getValidateBucketNamePlugin(this.config));
this.middlewareStack.use(getAddExpectContinuePlugin(this.config));
this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config));
this.middlewareStack.use(getS3ExpressPlugin(this.config));
this.middlewareStack.use(getS3ExpressHttpSigningPlugin(this.config));
}
destroy() {
super.destroy();
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/AbortMultipartUploadCommand.js
var AbortMultipartUploadCommand;
var init_AbortMultipartUploadCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/AbortMultipartUploadCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
AbortMultipartUploadCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "AbortMultipartUpload", {}).n("S3Client", "AbortMultipartUploadCommand").f(void 0, void 0).ser(se_AbortMultipartUploadCommand).de(de_AbortMultipartUploadCommand).build() {
static {
__name(this, "AbortMultipartUploadCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-ssec@3.714.0/node_modules/@aws-sdk/middleware-ssec/dist-es/index.js
function ssecMiddleware(options) {
return (next) => async (args) => {
const input = { ...args.input };
const properties = [
{
target: "SSECustomerKey",
hash: "SSECustomerKeyMD5"
},
{
target: "CopySourceSSECustomerKey",
hash: "CopySourceSSECustomerKeyMD5"
}
];
for (const prop of properties) {
const value = input[prop.target];
if (value) {
let valueForHash;
if (typeof value === "string") {
if (isValidBase64EncodedSSECustomerKey(value, options)) {
valueForHash = options.base64Decoder(value);
} else {
valueForHash = options.utf8Decoder(value);
input[prop.target] = options.base64Encoder(valueForHash);
}
} else {
valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value);
input[prop.target] = options.base64Encoder(valueForHash);
}
const hash = new options.md5();
hash.update(valueForHash);
input[prop.hash] = options.base64Encoder(await hash.digest());
}
}
return next({
...args,
input
});
};
}
function isValidBase64EncodedSSECustomerKey(str, options) {
const base64Regex = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
if (!base64Regex.test(str))
return false;
try {
const decodedBytes = options.base64Decoder(str);
return decodedBytes.length === 32;
} catch {
return false;
}
}
var ssecMiddlewareOptions, getSsecPlugin;
var init_dist_es70 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-ssec@3.714.0/node_modules/@aws-sdk/middleware-ssec/dist-es/index.js"() {
init_import_meta_url();
__name(ssecMiddleware, "ssecMiddleware");
ssecMiddlewareOptions = {
name: "ssecMiddleware",
step: "initialize",
tags: ["SSE"],
override: true
};
getSsecPlugin = /* @__PURE__ */ __name((config) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(ssecMiddleware(config), ssecMiddlewareOptions);
}, "applyToStack")
}), "getSsecPlugin");
__name(isValidBase64EncodedSSECustomerKey, "isValidBase64EncodedSSECustomerKey");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CompleteMultipartUploadCommand.js
var CompleteMultipartUploadCommand;
var init_CompleteMultipartUploadCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CompleteMultipartUploadCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
CompleteMultipartUploadCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "CompleteMultipartUpload", {}).n("S3Client", "CompleteMultipartUploadCommand").f(CompleteMultipartUploadRequestFilterSensitiveLog, CompleteMultipartUploadOutputFilterSensitiveLog).ser(se_CompleteMultipartUploadCommand).de(de_CompleteMultipartUploadCommand).build() {
static {
__name(this, "CompleteMultipartUploadCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CopyObjectCommand.js
var CopyObjectCommand;
var init_CopyObjectCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CopyObjectCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
CopyObjectCommand = class extends Command.classBuilder().ep({
...commonParams,
DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" },
CopySource: { type: "contextParams", name: "CopySource" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "CopyObject", {}).n("S3Client", "CopyObjectCommand").f(CopyObjectRequestFilterSensitiveLog, CopyObjectOutputFilterSensitiveLog).ser(se_CopyObjectCommand).de(de_CopyObjectCommand).build() {
static {
__name(this, "CopyObjectCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+middleware-location-constraint@3.714.0/node_modules/@aws-sdk/middleware-location-constraint/dist-es/index.js
function locationConstraintMiddleware(options) {
return (next) => async (args) => {
const { CreateBucketConfiguration } = args.input;
const region = await options.region();
if (!CreateBucketConfiguration?.LocationConstraint && !CreateBucketConfiguration?.Location) {
args = {
...args,
input: {
...args.input,
CreateBucketConfiguration: region === "us-east-1" ? void 0 : { LocationConstraint: region }
}
};
}
return next(args);
};
}
var locationConstraintMiddlewareOptions, getLocationConstraintPlugin;
var init_dist_es71 = __esm({
"../../node_modules/.pnpm/@aws-sdk+middleware-location-constraint@3.714.0/node_modules/@aws-sdk/middleware-location-constraint/dist-es/index.js"() {
init_import_meta_url();
__name(locationConstraintMiddleware, "locationConstraintMiddleware");
locationConstraintMiddlewareOptions = {
step: "initialize",
tags: ["LOCATION_CONSTRAINT", "CREATE_BUCKET_CONFIGURATION"],
name: "locationConstraintMiddleware",
override: true
};
getLocationConstraintPlugin = /* @__PURE__ */ __name((config) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(locationConstraintMiddleware(config), locationConstraintMiddlewareOptions);
}, "applyToStack")
}), "getLocationConstraintPlugin");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateBucketCommand.js
var CreateBucketCommand;
var init_CreateBucketCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateBucketCommand.js"() {
init_import_meta_url();
init_dist_es71();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
CreateBucketCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
DisableAccessPoints: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getLocationConstraintPlugin(config)
];
}).s("AmazonS3", "CreateBucket", {}).n("S3Client", "CreateBucketCommand").f(void 0, void 0).ser(se_CreateBucketCommand).de(de_CreateBucketCommand).build() {
static {
__name(this, "CreateBucketCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateBucketMetadataTableConfigurationCommand.js
var CreateBucketMetadataTableConfigurationCommand;
var init_CreateBucketMetadataTableConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateBucketMetadataTableConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
CreateBucketMetadataTableConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "CreateBucketMetadataTableConfiguration", {}).n("S3Client", "CreateBucketMetadataTableConfigurationCommand").f(void 0, void 0).ser(se_CreateBucketMetadataTableConfigurationCommand).de(de_CreateBucketMetadataTableConfigurationCommand).build() {
static {
__name(this, "CreateBucketMetadataTableConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateMultipartUploadCommand.js
var CreateMultipartUploadCommand;
var init_CreateMultipartUploadCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateMultipartUploadCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
CreateMultipartUploadCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "CreateMultipartUpload", {}).n("S3Client", "CreateMultipartUploadCommand").f(CreateMultipartUploadRequestFilterSensitiveLog, CreateMultipartUploadOutputFilterSensitiveLog).ser(se_CreateMultipartUploadCommand).de(de_CreateMultipartUploadCommand).build() {
static {
__name(this, "CreateMultipartUploadCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketAnalyticsConfigurationCommand.js
var DeleteBucketAnalyticsConfigurationCommand;
var init_DeleteBucketAnalyticsConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketAnalyticsConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketAnalyticsConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketAnalyticsConfiguration", {}).n("S3Client", "DeleteBucketAnalyticsConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketAnalyticsConfigurationCommand).de(de_DeleteBucketAnalyticsConfigurationCommand).build() {
static {
__name(this, "DeleteBucketAnalyticsConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketCommand.js
var DeleteBucketCommand;
var init_DeleteBucketCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucket", {}).n("S3Client", "DeleteBucketCommand").f(void 0, void 0).ser(se_DeleteBucketCommand).de(de_DeleteBucketCommand).build() {
static {
__name(this, "DeleteBucketCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketCorsCommand.js
var DeleteBucketCorsCommand;
var init_DeleteBucketCorsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketCorsCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketCorsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketCors", {}).n("S3Client", "DeleteBucketCorsCommand").f(void 0, void 0).ser(se_DeleteBucketCorsCommand).de(de_DeleteBucketCorsCommand).build() {
static {
__name(this, "DeleteBucketCorsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketEncryptionCommand.js
var DeleteBucketEncryptionCommand;
var init_DeleteBucketEncryptionCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketEncryptionCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketEncryptionCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketEncryption", {}).n("S3Client", "DeleteBucketEncryptionCommand").f(void 0, void 0).ser(se_DeleteBucketEncryptionCommand).de(de_DeleteBucketEncryptionCommand).build() {
static {
__name(this, "DeleteBucketEncryptionCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketIntelligentTieringConfigurationCommand.js
var DeleteBucketIntelligentTieringConfigurationCommand;
var init_DeleteBucketIntelligentTieringConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketIntelligentTieringConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketIntelligentTieringConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketIntelligentTieringConfiguration", {}).n("S3Client", "DeleteBucketIntelligentTieringConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketIntelligentTieringConfigurationCommand).de(de_DeleteBucketIntelligentTieringConfigurationCommand).build() {
static {
__name(this, "DeleteBucketIntelligentTieringConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketInventoryConfigurationCommand.js
var DeleteBucketInventoryConfigurationCommand;
var init_DeleteBucketInventoryConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketInventoryConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketInventoryConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketInventoryConfiguration", {}).n("S3Client", "DeleteBucketInventoryConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketInventoryConfigurationCommand).de(de_DeleteBucketInventoryConfigurationCommand).build() {
static {
__name(this, "DeleteBucketInventoryConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketLifecycleCommand.js
var DeleteBucketLifecycleCommand;
var init_DeleteBucketLifecycleCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketLifecycleCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketLifecycleCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketLifecycle", {}).n("S3Client", "DeleteBucketLifecycleCommand").f(void 0, void 0).ser(se_DeleteBucketLifecycleCommand).de(de_DeleteBucketLifecycleCommand).build() {
static {
__name(this, "DeleteBucketLifecycleCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketMetadataTableConfigurationCommand.js
var DeleteBucketMetadataTableConfigurationCommand;
var init_DeleteBucketMetadataTableConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketMetadataTableConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketMetadataTableConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketMetadataTableConfiguration", {}).n("S3Client", "DeleteBucketMetadataTableConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketMetadataTableConfigurationCommand).de(de_DeleteBucketMetadataTableConfigurationCommand).build() {
static {
__name(this, "DeleteBucketMetadataTableConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketMetricsConfigurationCommand.js
var DeleteBucketMetricsConfigurationCommand;
var init_DeleteBucketMetricsConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketMetricsConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketMetricsConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketMetricsConfiguration", {}).n("S3Client", "DeleteBucketMetricsConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketMetricsConfigurationCommand).de(de_DeleteBucketMetricsConfigurationCommand).build() {
static {
__name(this, "DeleteBucketMetricsConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketOwnershipControlsCommand.js
var DeleteBucketOwnershipControlsCommand;
var init_DeleteBucketOwnershipControlsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketOwnershipControlsCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketOwnershipControlsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketOwnershipControls", {}).n("S3Client", "DeleteBucketOwnershipControlsCommand").f(void 0, void 0).ser(se_DeleteBucketOwnershipControlsCommand).de(de_DeleteBucketOwnershipControlsCommand).build() {
static {
__name(this, "DeleteBucketOwnershipControlsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketPolicyCommand.js
var DeleteBucketPolicyCommand;
var init_DeleteBucketPolicyCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketPolicyCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketPolicyCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketPolicy", {}).n("S3Client", "DeleteBucketPolicyCommand").f(void 0, void 0).ser(se_DeleteBucketPolicyCommand).de(de_DeleteBucketPolicyCommand).build() {
static {
__name(this, "DeleteBucketPolicyCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketReplicationCommand.js
var DeleteBucketReplicationCommand;
var init_DeleteBucketReplicationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketReplicationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketReplicationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketReplication", {}).n("S3Client", "DeleteBucketReplicationCommand").f(void 0, void 0).ser(se_DeleteBucketReplicationCommand).de(de_DeleteBucketReplicationCommand).build() {
static {
__name(this, "DeleteBucketReplicationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketTaggingCommand.js
var DeleteBucketTaggingCommand;
var init_DeleteBucketTaggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketTaggingCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketTaggingCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketTagging", {}).n("S3Client", "DeleteBucketTaggingCommand").f(void 0, void 0).ser(se_DeleteBucketTaggingCommand).de(de_DeleteBucketTaggingCommand).build() {
static {
__name(this, "DeleteBucketTaggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketWebsiteCommand.js
var DeleteBucketWebsiteCommand;
var init_DeleteBucketWebsiteCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteBucketWebsiteCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteBucketWebsiteCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeleteBucketWebsite", {}).n("S3Client", "DeleteBucketWebsiteCommand").f(void 0, void 0).ser(se_DeleteBucketWebsiteCommand).de(de_DeleteBucketWebsiteCommand).build() {
static {
__name(this, "DeleteBucketWebsiteCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectCommand.js
var DeleteObjectCommand;
var init_DeleteObjectCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteObjectCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "DeleteObject", {}).n("S3Client", "DeleteObjectCommand").f(void 0, void 0).ser(se_DeleteObjectCommand).de(de_DeleteObjectCommand).build() {
static {
__name(this, "DeleteObjectCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectsCommand.js
var DeleteObjectsCommand;
var init_DeleteObjectsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectsCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteObjectsCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "DeleteObjects", {}).n("S3Client", "DeleteObjectsCommand").f(void 0, void 0).ser(se_DeleteObjectsCommand).de(de_DeleteObjectsCommand).build() {
static {
__name(this, "DeleteObjectsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectTaggingCommand.js
var DeleteObjectTaggingCommand;
var init_DeleteObjectTaggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeleteObjectTaggingCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeleteObjectTaggingCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "DeleteObjectTagging", {}).n("S3Client", "DeleteObjectTaggingCommand").f(void 0, void 0).ser(se_DeleteObjectTaggingCommand).de(de_DeleteObjectTaggingCommand).build() {
static {
__name(this, "DeleteObjectTaggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeletePublicAccessBlockCommand.js
var DeletePublicAccessBlockCommand;
var init_DeletePublicAccessBlockCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/DeletePublicAccessBlockCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
DeletePublicAccessBlockCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "DeletePublicAccessBlock", {}).n("S3Client", "DeletePublicAccessBlockCommand").f(void 0, void 0).ser(se_DeletePublicAccessBlockCommand).de(de_DeletePublicAccessBlockCommand).build() {
static {
__name(this, "DeletePublicAccessBlockCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketAccelerateConfigurationCommand.js
var GetBucketAccelerateConfigurationCommand;
var init_GetBucketAccelerateConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketAccelerateConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketAccelerateConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketAccelerateConfiguration", {}).n("S3Client", "GetBucketAccelerateConfigurationCommand").f(void 0, void 0).ser(se_GetBucketAccelerateConfigurationCommand).de(de_GetBucketAccelerateConfigurationCommand).build() {
static {
__name(this, "GetBucketAccelerateConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketAclCommand.js
var GetBucketAclCommand;
var init_GetBucketAclCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketAclCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketAclCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketAcl", {}).n("S3Client", "GetBucketAclCommand").f(void 0, void 0).ser(se_GetBucketAclCommand).de(de_GetBucketAclCommand).build() {
static {
__name(this, "GetBucketAclCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketAnalyticsConfigurationCommand.js
var GetBucketAnalyticsConfigurationCommand;
var init_GetBucketAnalyticsConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketAnalyticsConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketAnalyticsConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketAnalyticsConfiguration", {}).n("S3Client", "GetBucketAnalyticsConfigurationCommand").f(void 0, void 0).ser(se_GetBucketAnalyticsConfigurationCommand).de(de_GetBucketAnalyticsConfigurationCommand).build() {
static {
__name(this, "GetBucketAnalyticsConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketCorsCommand.js
var GetBucketCorsCommand;
var init_GetBucketCorsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketCorsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketCorsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketCors", {}).n("S3Client", "GetBucketCorsCommand").f(void 0, void 0).ser(se_GetBucketCorsCommand).de(de_GetBucketCorsCommand).build() {
static {
__name(this, "GetBucketCorsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketEncryptionCommand.js
var GetBucketEncryptionCommand;
var init_GetBucketEncryptionCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketEncryptionCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
GetBucketEncryptionCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketEncryption", {}).n("S3Client", "GetBucketEncryptionCommand").f(void 0, GetBucketEncryptionOutputFilterSensitiveLog).ser(se_GetBucketEncryptionCommand).de(de_GetBucketEncryptionCommand).build() {
static {
__name(this, "GetBucketEncryptionCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketIntelligentTieringConfigurationCommand.js
var GetBucketIntelligentTieringConfigurationCommand;
var init_GetBucketIntelligentTieringConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketIntelligentTieringConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketIntelligentTieringConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketIntelligentTieringConfiguration", {}).n("S3Client", "GetBucketIntelligentTieringConfigurationCommand").f(void 0, void 0).ser(se_GetBucketIntelligentTieringConfigurationCommand).de(de_GetBucketIntelligentTieringConfigurationCommand).build() {
static {
__name(this, "GetBucketIntelligentTieringConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketInventoryConfigurationCommand.js
var GetBucketInventoryConfigurationCommand;
var init_GetBucketInventoryConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketInventoryConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
GetBucketInventoryConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketInventoryConfiguration", {}).n("S3Client", "GetBucketInventoryConfigurationCommand").f(void 0, GetBucketInventoryConfigurationOutputFilterSensitiveLog).ser(se_GetBucketInventoryConfigurationCommand).de(de_GetBucketInventoryConfigurationCommand).build() {
static {
__name(this, "GetBucketInventoryConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketLifecycleConfigurationCommand.js
var GetBucketLifecycleConfigurationCommand;
var init_GetBucketLifecycleConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketLifecycleConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketLifecycleConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketLifecycleConfiguration", {}).n("S3Client", "GetBucketLifecycleConfigurationCommand").f(void 0, void 0).ser(se_GetBucketLifecycleConfigurationCommand).de(de_GetBucketLifecycleConfigurationCommand).build() {
static {
__name(this, "GetBucketLifecycleConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketLocationCommand.js
var GetBucketLocationCommand;
var init_GetBucketLocationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketLocationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketLocationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketLocation", {}).n("S3Client", "GetBucketLocationCommand").f(void 0, void 0).ser(se_GetBucketLocationCommand).de(de_GetBucketLocationCommand).build() {
static {
__name(this, "GetBucketLocationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketLoggingCommand.js
var GetBucketLoggingCommand;
var init_GetBucketLoggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketLoggingCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketLoggingCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketLogging", {}).n("S3Client", "GetBucketLoggingCommand").f(void 0, void 0).ser(se_GetBucketLoggingCommand).de(de_GetBucketLoggingCommand).build() {
static {
__name(this, "GetBucketLoggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketMetadataTableConfigurationCommand.js
var GetBucketMetadataTableConfigurationCommand;
var init_GetBucketMetadataTableConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketMetadataTableConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketMetadataTableConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketMetadataTableConfiguration", {}).n("S3Client", "GetBucketMetadataTableConfigurationCommand").f(void 0, void 0).ser(se_GetBucketMetadataTableConfigurationCommand).de(de_GetBucketMetadataTableConfigurationCommand).build() {
static {
__name(this, "GetBucketMetadataTableConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketMetricsConfigurationCommand.js
var GetBucketMetricsConfigurationCommand;
var init_GetBucketMetricsConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketMetricsConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketMetricsConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketMetricsConfiguration", {}).n("S3Client", "GetBucketMetricsConfigurationCommand").f(void 0, void 0).ser(se_GetBucketMetricsConfigurationCommand).de(de_GetBucketMetricsConfigurationCommand).build() {
static {
__name(this, "GetBucketMetricsConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketNotificationConfigurationCommand.js
var GetBucketNotificationConfigurationCommand;
var init_GetBucketNotificationConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketNotificationConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketNotificationConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketNotificationConfiguration", {}).n("S3Client", "GetBucketNotificationConfigurationCommand").f(void 0, void 0).ser(se_GetBucketNotificationConfigurationCommand).de(de_GetBucketNotificationConfigurationCommand).build() {
static {
__name(this, "GetBucketNotificationConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketOwnershipControlsCommand.js
var GetBucketOwnershipControlsCommand;
var init_GetBucketOwnershipControlsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketOwnershipControlsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketOwnershipControlsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketOwnershipControls", {}).n("S3Client", "GetBucketOwnershipControlsCommand").f(void 0, void 0).ser(se_GetBucketOwnershipControlsCommand).de(de_GetBucketOwnershipControlsCommand).build() {
static {
__name(this, "GetBucketOwnershipControlsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketPolicyCommand.js
var GetBucketPolicyCommand;
var init_GetBucketPolicyCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketPolicyCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketPolicyCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketPolicy", {}).n("S3Client", "GetBucketPolicyCommand").f(void 0, void 0).ser(se_GetBucketPolicyCommand).de(de_GetBucketPolicyCommand).build() {
static {
__name(this, "GetBucketPolicyCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketPolicyStatusCommand.js
var GetBucketPolicyStatusCommand;
var init_GetBucketPolicyStatusCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketPolicyStatusCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketPolicyStatusCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketPolicyStatus", {}).n("S3Client", "GetBucketPolicyStatusCommand").f(void 0, void 0).ser(se_GetBucketPolicyStatusCommand).de(de_GetBucketPolicyStatusCommand).build() {
static {
__name(this, "GetBucketPolicyStatusCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketReplicationCommand.js
var GetBucketReplicationCommand;
var init_GetBucketReplicationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketReplicationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketReplicationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketReplication", {}).n("S3Client", "GetBucketReplicationCommand").f(void 0, void 0).ser(se_GetBucketReplicationCommand).de(de_GetBucketReplicationCommand).build() {
static {
__name(this, "GetBucketReplicationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketRequestPaymentCommand.js
var GetBucketRequestPaymentCommand;
var init_GetBucketRequestPaymentCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketRequestPaymentCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketRequestPaymentCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketRequestPayment", {}).n("S3Client", "GetBucketRequestPaymentCommand").f(void 0, void 0).ser(se_GetBucketRequestPaymentCommand).de(de_GetBucketRequestPaymentCommand).build() {
static {
__name(this, "GetBucketRequestPaymentCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketTaggingCommand.js
var GetBucketTaggingCommand;
var init_GetBucketTaggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketTaggingCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketTaggingCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketTagging", {}).n("S3Client", "GetBucketTaggingCommand").f(void 0, void 0).ser(se_GetBucketTaggingCommand).de(de_GetBucketTaggingCommand).build() {
static {
__name(this, "GetBucketTaggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketVersioningCommand.js
var GetBucketVersioningCommand;
var init_GetBucketVersioningCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketVersioningCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketVersioningCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketVersioning", {}).n("S3Client", "GetBucketVersioningCommand").f(void 0, void 0).ser(se_GetBucketVersioningCommand).de(de_GetBucketVersioningCommand).build() {
static {
__name(this, "GetBucketVersioningCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketWebsiteCommand.js
var GetBucketWebsiteCommand;
var init_GetBucketWebsiteCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetBucketWebsiteCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetBucketWebsiteCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetBucketWebsite", {}).n("S3Client", "GetBucketWebsiteCommand").f(void 0, void 0).ser(se_GetBucketWebsiteCommand).de(de_GetBucketWebsiteCommand).build() {
static {
__name(this, "GetBucketWebsiteCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectAclCommand.js
var GetObjectAclCommand;
var init_GetObjectAclCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectAclCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetObjectAclCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetObjectAcl", {}).n("S3Client", "GetObjectAclCommand").f(void 0, void 0).ser(se_GetObjectAclCommand).de(de_GetObjectAclCommand).build() {
static {
__name(this, "GetObjectAclCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectAttributesCommand.js
var GetObjectAttributesCommand;
var init_GetObjectAttributesCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectAttributesCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
GetObjectAttributesCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "GetObjectAttributes", {}).n("S3Client", "GetObjectAttributesCommand").f(GetObjectAttributesRequestFilterSensitiveLog, void 0).ser(se_GetObjectAttributesCommand).de(de_GetObjectAttributesCommand).build() {
static {
__name(this, "GetObjectAttributesCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectCommand.js
var GetObjectCommand;
var init_GetObjectCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
GetObjectCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestChecksumRequired: false,
requestValidationModeMember: "ChecksumMode",
responseAlgorithms: ["CRC32", "CRC32C", "SHA256", "SHA1"]
}),
getSsecPlugin(config),
getS3ExpiresMiddlewarePlugin(config)
];
}).s("AmazonS3", "GetObject", {}).n("S3Client", "GetObjectCommand").f(GetObjectRequestFilterSensitiveLog, GetObjectOutputFilterSensitiveLog).ser(se_GetObjectCommand).de(de_GetObjectCommand).build() {
static {
__name(this, "GetObjectCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectLegalHoldCommand.js
var GetObjectLegalHoldCommand;
var init_GetObjectLegalHoldCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectLegalHoldCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetObjectLegalHoldCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetObjectLegalHold", {}).n("S3Client", "GetObjectLegalHoldCommand").f(void 0, void 0).ser(se_GetObjectLegalHoldCommand).de(de_GetObjectLegalHoldCommand).build() {
static {
__name(this, "GetObjectLegalHoldCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectLockConfigurationCommand.js
var GetObjectLockConfigurationCommand;
var init_GetObjectLockConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectLockConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetObjectLockConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetObjectLockConfiguration", {}).n("S3Client", "GetObjectLockConfigurationCommand").f(void 0, void 0).ser(se_GetObjectLockConfigurationCommand).de(de_GetObjectLockConfigurationCommand).build() {
static {
__name(this, "GetObjectLockConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectRetentionCommand.js
var GetObjectRetentionCommand;
var init_GetObjectRetentionCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectRetentionCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetObjectRetentionCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetObjectRetention", {}).n("S3Client", "GetObjectRetentionCommand").f(void 0, void 0).ser(se_GetObjectRetentionCommand).de(de_GetObjectRetentionCommand).build() {
static {
__name(this, "GetObjectRetentionCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectTaggingCommand.js
var GetObjectTaggingCommand;
var init_GetObjectTaggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectTaggingCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetObjectTaggingCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetObjectTagging", {}).n("S3Client", "GetObjectTaggingCommand").f(void 0, void 0).ser(se_GetObjectTaggingCommand).de(de_GetObjectTaggingCommand).build() {
static {
__name(this, "GetObjectTaggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectTorrentCommand.js
var GetObjectTorrentCommand;
var init_GetObjectTorrentCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectTorrentCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
GetObjectTorrentCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "GetObjectTorrent", {}).n("S3Client", "GetObjectTorrentCommand").f(void 0, GetObjectTorrentOutputFilterSensitiveLog).ser(se_GetObjectTorrentCommand).de(de_GetObjectTorrentCommand).build() {
static {
__name(this, "GetObjectTorrentCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetPublicAccessBlockCommand.js
var GetPublicAccessBlockCommand;
var init_GetPublicAccessBlockCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetPublicAccessBlockCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
GetPublicAccessBlockCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "GetPublicAccessBlock", {}).n("S3Client", "GetPublicAccessBlockCommand").f(void 0, void 0).ser(se_GetPublicAccessBlockCommand).de(de_GetPublicAccessBlockCommand).build() {
static {
__name(this, "GetPublicAccessBlockCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/HeadBucketCommand.js
var HeadBucketCommand;
var init_HeadBucketCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/HeadBucketCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
HeadBucketCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "HeadBucket", {}).n("S3Client", "HeadBucketCommand").f(void 0, void 0).ser(se_HeadBucketCommand).de(de_HeadBucketCommand).build() {
static {
__name(this, "HeadBucketCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/HeadObjectCommand.js
var HeadObjectCommand;
var init_HeadObjectCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/HeadObjectCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
HeadObjectCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config),
getS3ExpiresMiddlewarePlugin(config)
];
}).s("AmazonS3", "HeadObject", {}).n("S3Client", "HeadObjectCommand").f(HeadObjectRequestFilterSensitiveLog, HeadObjectOutputFilterSensitiveLog).ser(se_HeadObjectCommand).de(de_HeadObjectCommand).build() {
static {
__name(this, "HeadObjectCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketAnalyticsConfigurationsCommand.js
var ListBucketAnalyticsConfigurationsCommand;
var init_ListBucketAnalyticsConfigurationsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketAnalyticsConfigurationsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListBucketAnalyticsConfigurationsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListBucketAnalyticsConfigurations", {}).n("S3Client", "ListBucketAnalyticsConfigurationsCommand").f(void 0, void 0).ser(se_ListBucketAnalyticsConfigurationsCommand).de(de_ListBucketAnalyticsConfigurationsCommand).build() {
static {
__name(this, "ListBucketAnalyticsConfigurationsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketIntelligentTieringConfigurationsCommand.js
var ListBucketIntelligentTieringConfigurationsCommand;
var init_ListBucketIntelligentTieringConfigurationsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketIntelligentTieringConfigurationsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListBucketIntelligentTieringConfigurationsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListBucketIntelligentTieringConfigurations", {}).n("S3Client", "ListBucketIntelligentTieringConfigurationsCommand").f(void 0, void 0).ser(se_ListBucketIntelligentTieringConfigurationsCommand).de(de_ListBucketIntelligentTieringConfigurationsCommand).build() {
static {
__name(this, "ListBucketIntelligentTieringConfigurationsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketInventoryConfigurationsCommand.js
var ListBucketInventoryConfigurationsCommand;
var init_ListBucketInventoryConfigurationsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketInventoryConfigurationsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
ListBucketInventoryConfigurationsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListBucketInventoryConfigurations", {}).n("S3Client", "ListBucketInventoryConfigurationsCommand").f(void 0, ListBucketInventoryConfigurationsOutputFilterSensitiveLog).ser(se_ListBucketInventoryConfigurationsCommand).de(de_ListBucketInventoryConfigurationsCommand).build() {
static {
__name(this, "ListBucketInventoryConfigurationsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketMetricsConfigurationsCommand.js
var ListBucketMetricsConfigurationsCommand;
var init_ListBucketMetricsConfigurationsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketMetricsConfigurationsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListBucketMetricsConfigurationsCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListBucketMetricsConfigurations", {}).n("S3Client", "ListBucketMetricsConfigurationsCommand").f(void 0, void 0).ser(se_ListBucketMetricsConfigurationsCommand).de(de_ListBucketMetricsConfigurationsCommand).build() {
static {
__name(this, "ListBucketMetricsConfigurationsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketsCommand.js
var ListBucketsCommand;
var init_ListBucketsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListBucketsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListBucketsCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListBuckets", {}).n("S3Client", "ListBucketsCommand").f(void 0, void 0).ser(se_ListBucketsCommand).de(de_ListBucketsCommand).build() {
static {
__name(this, "ListBucketsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListDirectoryBucketsCommand.js
var ListDirectoryBucketsCommand;
var init_ListDirectoryBucketsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListDirectoryBucketsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListDirectoryBucketsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListDirectoryBuckets", {}).n("S3Client", "ListDirectoryBucketsCommand").f(void 0, void 0).ser(se_ListDirectoryBucketsCommand).de(de_ListDirectoryBucketsCommand).build() {
static {
__name(this, "ListDirectoryBucketsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListMultipartUploadsCommand.js
var ListMultipartUploadsCommand;
var init_ListMultipartUploadsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListMultipartUploadsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListMultipartUploadsCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Prefix: { type: "contextParams", name: "Prefix" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListMultipartUploads", {}).n("S3Client", "ListMultipartUploadsCommand").f(void 0, void 0).ser(se_ListMultipartUploadsCommand).de(de_ListMultipartUploadsCommand).build() {
static {
__name(this, "ListMultipartUploadsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectsCommand.js
var ListObjectsCommand;
var init_ListObjectsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListObjectsCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Prefix: { type: "contextParams", name: "Prefix" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListObjects", {}).n("S3Client", "ListObjectsCommand").f(void 0, void 0).ser(se_ListObjectsCommand).de(de_ListObjectsCommand).build() {
static {
__name(this, "ListObjectsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectsV2Command.js
var ListObjectsV2Command;
var init_ListObjectsV2Command = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectsV2Command.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListObjectsV2Command = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Prefix: { type: "contextParams", name: "Prefix" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListObjectsV2", {}).n("S3Client", "ListObjectsV2Command").f(void 0, void 0).ser(se_ListObjectsV2Command).de(de_ListObjectsV2Command).build() {
static {
__name(this, "ListObjectsV2Command");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectVersionsCommand.js
var ListObjectVersionsCommand;
var init_ListObjectVersionsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectVersionsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
ListObjectVersionsCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Prefix: { type: "contextParams", name: "Prefix" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "ListObjectVersions", {}).n("S3Client", "ListObjectVersionsCommand").f(void 0, void 0).ser(se_ListObjectVersionsCommand).de(de_ListObjectVersionsCommand).build() {
static {
__name(this, "ListObjectVersionsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListPartsCommand.js
var ListPartsCommand;
var init_ListPartsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/ListPartsCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_0();
init_Aws_restXml();
ListPartsCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "ListParts", {}).n("S3Client", "ListPartsCommand").f(ListPartsRequestFilterSensitiveLog, void 0).ser(se_ListPartsCommand).de(de_ListPartsCommand).build() {
static {
__name(this, "ListPartsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketAccelerateConfigurationCommand.js
var PutBucketAccelerateConfigurationCommand;
var init_PutBucketAccelerateConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketAccelerateConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketAccelerateConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: false
})
];
}).s("AmazonS3", "PutBucketAccelerateConfiguration", {}).n("S3Client", "PutBucketAccelerateConfigurationCommand").f(void 0, void 0).ser(se_PutBucketAccelerateConfigurationCommand).de(de_PutBucketAccelerateConfigurationCommand).build() {
static {
__name(this, "PutBucketAccelerateConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketAclCommand.js
var PutBucketAclCommand;
var init_PutBucketAclCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketAclCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketAclCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketAcl", {}).n("S3Client", "PutBucketAclCommand").f(void 0, void 0).ser(se_PutBucketAclCommand).de(de_PutBucketAclCommand).build() {
static {
__name(this, "PutBucketAclCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketAnalyticsConfigurationCommand.js
var PutBucketAnalyticsConfigurationCommand;
var init_PutBucketAnalyticsConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketAnalyticsConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketAnalyticsConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "PutBucketAnalyticsConfiguration", {}).n("S3Client", "PutBucketAnalyticsConfigurationCommand").f(void 0, void 0).ser(se_PutBucketAnalyticsConfigurationCommand).de(de_PutBucketAnalyticsConfigurationCommand).build() {
static {
__name(this, "PutBucketAnalyticsConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketCorsCommand.js
var PutBucketCorsCommand;
var init_PutBucketCorsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketCorsCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketCorsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketCors", {}).n("S3Client", "PutBucketCorsCommand").f(void 0, void 0).ser(se_PutBucketCorsCommand).de(de_PutBucketCorsCommand).build() {
static {
__name(this, "PutBucketCorsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketEncryptionCommand.js
var PutBucketEncryptionCommand;
var init_PutBucketEncryptionCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketEncryptionCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
PutBucketEncryptionCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketEncryption", {}).n("S3Client", "PutBucketEncryptionCommand").f(PutBucketEncryptionRequestFilterSensitiveLog, void 0).ser(se_PutBucketEncryptionCommand).de(de_PutBucketEncryptionCommand).build() {
static {
__name(this, "PutBucketEncryptionCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketIntelligentTieringConfigurationCommand.js
var PutBucketIntelligentTieringConfigurationCommand;
var init_PutBucketIntelligentTieringConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketIntelligentTieringConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketIntelligentTieringConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "PutBucketIntelligentTieringConfiguration", {}).n("S3Client", "PutBucketIntelligentTieringConfigurationCommand").f(void 0, void 0).ser(se_PutBucketIntelligentTieringConfigurationCommand).de(de_PutBucketIntelligentTieringConfigurationCommand).build() {
static {
__name(this, "PutBucketIntelligentTieringConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketInventoryConfigurationCommand.js
var PutBucketInventoryConfigurationCommand;
var init_PutBucketInventoryConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketInventoryConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
PutBucketInventoryConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "PutBucketInventoryConfiguration", {}).n("S3Client", "PutBucketInventoryConfigurationCommand").f(PutBucketInventoryConfigurationRequestFilterSensitiveLog, void 0).ser(se_PutBucketInventoryConfigurationCommand).de(de_PutBucketInventoryConfigurationCommand).build() {
static {
__name(this, "PutBucketInventoryConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketLifecycleConfigurationCommand.js
var PutBucketLifecycleConfigurationCommand;
var init_PutBucketLifecycleConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketLifecycleConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketLifecycleConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "PutBucketLifecycleConfiguration", {}).n("S3Client", "PutBucketLifecycleConfigurationCommand").f(void 0, void 0).ser(se_PutBucketLifecycleConfigurationCommand).de(de_PutBucketLifecycleConfigurationCommand).build() {
static {
__name(this, "PutBucketLifecycleConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketLoggingCommand.js
var PutBucketLoggingCommand;
var init_PutBucketLoggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketLoggingCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketLoggingCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketLogging", {}).n("S3Client", "PutBucketLoggingCommand").f(void 0, void 0).ser(se_PutBucketLoggingCommand).de(de_PutBucketLoggingCommand).build() {
static {
__name(this, "PutBucketLoggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketMetricsConfigurationCommand.js
var PutBucketMetricsConfigurationCommand;
var init_PutBucketMetricsConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketMetricsConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketMetricsConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "PutBucketMetricsConfiguration", {}).n("S3Client", "PutBucketMetricsConfigurationCommand").f(void 0, void 0).ser(se_PutBucketMetricsConfigurationCommand).de(de_PutBucketMetricsConfigurationCommand).build() {
static {
__name(this, "PutBucketMetricsConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketNotificationConfigurationCommand.js
var PutBucketNotificationConfigurationCommand;
var init_PutBucketNotificationConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketNotificationConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketNotificationConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "PutBucketNotificationConfiguration", {}).n("S3Client", "PutBucketNotificationConfigurationCommand").f(void 0, void 0).ser(se_PutBucketNotificationConfigurationCommand).de(de_PutBucketNotificationConfigurationCommand).build() {
static {
__name(this, "PutBucketNotificationConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketOwnershipControlsCommand.js
var PutBucketOwnershipControlsCommand;
var init_PutBucketOwnershipControlsCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketOwnershipControlsCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketOwnershipControlsCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketOwnershipControls", {}).n("S3Client", "PutBucketOwnershipControlsCommand").f(void 0, void 0).ser(se_PutBucketOwnershipControlsCommand).de(de_PutBucketOwnershipControlsCommand).build() {
static {
__name(this, "PutBucketOwnershipControlsCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketPolicyCommand.js
var PutBucketPolicyCommand;
var init_PutBucketPolicyCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketPolicyCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketPolicyCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketPolicy", {}).n("S3Client", "PutBucketPolicyCommand").f(void 0, void 0).ser(se_PutBucketPolicyCommand).de(de_PutBucketPolicyCommand).build() {
static {
__name(this, "PutBucketPolicyCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketReplicationCommand.js
var PutBucketReplicationCommand;
var init_PutBucketReplicationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketReplicationCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketReplicationCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketReplication", {}).n("S3Client", "PutBucketReplicationCommand").f(void 0, void 0).ser(se_PutBucketReplicationCommand).de(de_PutBucketReplicationCommand).build() {
static {
__name(this, "PutBucketReplicationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketRequestPaymentCommand.js
var PutBucketRequestPaymentCommand;
var init_PutBucketRequestPaymentCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketRequestPaymentCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketRequestPaymentCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketRequestPayment", {}).n("S3Client", "PutBucketRequestPaymentCommand").f(void 0, void 0).ser(se_PutBucketRequestPaymentCommand).de(de_PutBucketRequestPaymentCommand).build() {
static {
__name(this, "PutBucketRequestPaymentCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketTaggingCommand.js
var PutBucketTaggingCommand;
var init_PutBucketTaggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketTaggingCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketTaggingCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketTagging", {}).n("S3Client", "PutBucketTaggingCommand").f(void 0, void 0).ser(se_PutBucketTaggingCommand).de(de_PutBucketTaggingCommand).build() {
static {
__name(this, "PutBucketTaggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketVersioningCommand.js
var PutBucketVersioningCommand;
var init_PutBucketVersioningCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketVersioningCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketVersioningCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketVersioning", {}).n("S3Client", "PutBucketVersioningCommand").f(void 0, void 0).ser(se_PutBucketVersioningCommand).de(de_PutBucketVersioningCommand).build() {
static {
__name(this, "PutBucketVersioningCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketWebsiteCommand.js
var PutBucketWebsiteCommand;
var init_PutBucketWebsiteCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutBucketWebsiteCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutBucketWebsiteCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutBucketWebsite", {}).n("S3Client", "PutBucketWebsiteCommand").f(void 0, void 0).ser(se_PutBucketWebsiteCommand).de(de_PutBucketWebsiteCommand).build() {
static {
__name(this, "PutBucketWebsiteCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectAclCommand.js
var PutObjectAclCommand;
var init_PutObjectAclCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectAclCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutObjectAclCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "PutObjectAcl", {}).n("S3Client", "PutObjectAclCommand").f(void 0, void 0).ser(se_PutObjectAclCommand).de(de_PutObjectAclCommand).build() {
static {
__name(this, "PutObjectAclCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectCommand.js
var PutObjectCommand;
var init_PutObjectCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
PutObjectCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: false
}),
getCheckContentLengthHeaderPlugin(config),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "PutObject", {}).n("S3Client", "PutObjectCommand").f(PutObjectRequestFilterSensitiveLog, PutObjectOutputFilterSensitiveLog).ser(se_PutObjectCommand).de(de_PutObjectCommand).build() {
static {
__name(this, "PutObjectCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectLegalHoldCommand.js
var PutObjectLegalHoldCommand;
var init_PutObjectLegalHoldCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectLegalHoldCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutObjectLegalHoldCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "PutObjectLegalHold", {}).n("S3Client", "PutObjectLegalHoldCommand").f(void 0, void 0).ser(se_PutObjectLegalHoldCommand).de(de_PutObjectLegalHoldCommand).build() {
static {
__name(this, "PutObjectLegalHoldCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectLockConfigurationCommand.js
var PutObjectLockConfigurationCommand;
var init_PutObjectLockConfigurationCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectLockConfigurationCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutObjectLockConfigurationCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "PutObjectLockConfiguration", {}).n("S3Client", "PutObjectLockConfigurationCommand").f(void 0, void 0).ser(se_PutObjectLockConfigurationCommand).de(de_PutObjectLockConfigurationCommand).build() {
static {
__name(this, "PutObjectLockConfigurationCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectRetentionCommand.js
var PutObjectRetentionCommand;
var init_PutObjectRetentionCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectRetentionCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutObjectRetentionCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "PutObjectRetention", {}).n("S3Client", "PutObjectRetentionCommand").f(void 0, void 0).ser(se_PutObjectRetentionCommand).de(de_PutObjectRetentionCommand).build() {
static {
__name(this, "PutObjectRetentionCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectTaggingCommand.js
var PutObjectTaggingCommand;
var init_PutObjectTaggingCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectTaggingCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutObjectTaggingCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "PutObjectTagging", {}).n("S3Client", "PutObjectTaggingCommand").f(void 0, void 0).ser(se_PutObjectTaggingCommand).de(de_PutObjectTaggingCommand).build() {
static {
__name(this, "PutObjectTaggingCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutPublicAccessBlockCommand.js
var PutPublicAccessBlockCommand;
var init_PutPublicAccessBlockCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutPublicAccessBlockCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_Aws_restXml();
PutPublicAccessBlockCommand = class extends Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: true
})
];
}).s("AmazonS3", "PutPublicAccessBlock", {}).n("S3Client", "PutPublicAccessBlockCommand").f(void 0, void 0).ser(se_PutPublicAccessBlockCommand).de(de_PutPublicAccessBlockCommand).build() {
static {
__name(this, "PutPublicAccessBlockCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/RestoreObjectCommand.js
var RestoreObjectCommand;
var init_RestoreObjectCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/RestoreObjectCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
RestoreObjectCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: false
}),
getThrow200ExceptionsPlugin(config)
];
}).s("AmazonS3", "RestoreObject", {}).n("S3Client", "RestoreObjectCommand").f(RestoreObjectRequestFilterSensitiveLog, void 0).ser(se_RestoreObjectCommand).de(de_RestoreObjectCommand).build() {
static {
__name(this, "RestoreObjectCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/SelectObjectContentCommand.js
var SelectObjectContentCommand;
var init_SelectObjectContentCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/SelectObjectContentCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
SelectObjectContentCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "SelectObjectContent", {
eventStream: {
output: true
}
}).n("S3Client", "SelectObjectContentCommand").f(SelectObjectContentRequestFilterSensitiveLog, SelectObjectContentOutputFilterSensitiveLog).ser(se_SelectObjectContentCommand).de(de_SelectObjectContentCommand).build() {
static {
__name(this, "SelectObjectContentCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/UploadPartCommand.js
var UploadPartCommand;
var init_UploadPartCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/UploadPartCommand.js"() {
init_import_meta_url();
init_dist_es25();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
UploadPartCommand = class extends Command.classBuilder().ep({
...commonParams,
Bucket: { type: "contextParams", name: "Bucket" },
Key: { type: "contextParams", name: "Key" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getFlexibleChecksumsPlugin(config, {
requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" },
requestChecksumRequired: false
}),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "UploadPart", {}).n("S3Client", "UploadPartCommand").f(UploadPartRequestFilterSensitiveLog, UploadPartOutputFilterSensitiveLog).ser(se_UploadPartCommand).de(de_UploadPartCommand).build() {
static {
__name(this, "UploadPartCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/UploadPartCopyCommand.js
var UploadPartCopyCommand;
var init_UploadPartCopyCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/UploadPartCopyCommand.js"() {
init_import_meta_url();
init_dist_es31();
init_dist_es70();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
UploadPartCopyCommand = class extends Command.classBuilder().ep({
...commonParams,
DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true },
Bucket: { type: "contextParams", name: "Bucket" }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions()),
getThrow200ExceptionsPlugin(config),
getSsecPlugin(config)
];
}).s("AmazonS3", "UploadPartCopy", {}).n("S3Client", "UploadPartCopyCommand").f(UploadPartCopyRequestFilterSensitiveLog, UploadPartCopyOutputFilterSensitiveLog).ser(se_UploadPartCopyCommand).de(de_UploadPartCopyCommand).build() {
static {
__name(this, "UploadPartCopyCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/WriteGetObjectResponseCommand.js
var WriteGetObjectResponseCommand;
var init_WriteGetObjectResponseCommand = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/WriteGetObjectResponseCommand.js"() {
init_import_meta_url();
init_dist_es42();
init_dist_es5();
init_dist_es20();
init_EndpointParameters();
init_models_1();
init_Aws_restXml();
WriteGetObjectResponseCommand = class extends Command.classBuilder().ep({
...commonParams,
UseObjectLambdaEndpoint: { type: "staticContextParams", value: true }
}).m(function(Command2, cs2, config, o5) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
];
}).s("AmazonS3", "WriteGetObjectResponse", {}).n("S3Client", "WriteGetObjectResponseCommand").f(WriteGetObjectResponseRequestFilterSensitiveLog, void 0).ser(se_WriteGetObjectResponseCommand).de(de_WriteGetObjectResponseCommand).build() {
static {
__name(this, "WriteGetObjectResponseCommand");
}
};
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/S3.js
var commands4, S3;
var init_S3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/S3.js"() {
init_import_meta_url();
init_dist_es20();
init_AbortMultipartUploadCommand();
init_CompleteMultipartUploadCommand();
init_CopyObjectCommand();
init_CreateBucketCommand();
init_CreateBucketMetadataTableConfigurationCommand();
init_CreateMultipartUploadCommand();
init_CreateSessionCommand();
init_DeleteBucketAnalyticsConfigurationCommand();
init_DeleteBucketCommand();
init_DeleteBucketCorsCommand();
init_DeleteBucketEncryptionCommand();
init_DeleteBucketIntelligentTieringConfigurationCommand();
init_DeleteBucketInventoryConfigurationCommand();
init_DeleteBucketLifecycleCommand();
init_DeleteBucketMetadataTableConfigurationCommand();
init_DeleteBucketMetricsConfigurationCommand();
init_DeleteBucketOwnershipControlsCommand();
init_DeleteBucketPolicyCommand();
init_DeleteBucketReplicationCommand();
init_DeleteBucketTaggingCommand();
init_DeleteBucketWebsiteCommand();
init_DeleteObjectCommand();
init_DeleteObjectsCommand();
init_DeleteObjectTaggingCommand();
init_DeletePublicAccessBlockCommand();
init_GetBucketAccelerateConfigurationCommand();
init_GetBucketAclCommand();
init_GetBucketAnalyticsConfigurationCommand();
init_GetBucketCorsCommand();
init_GetBucketEncryptionCommand();
init_GetBucketIntelligentTieringConfigurationCommand();
init_GetBucketInventoryConfigurationCommand();
init_GetBucketLifecycleConfigurationCommand();
init_GetBucketLocationCommand();
init_GetBucketLoggingCommand();
init_GetBucketMetadataTableConfigurationCommand();
init_GetBucketMetricsConfigurationCommand();
init_GetBucketNotificationConfigurationCommand();
init_GetBucketOwnershipControlsCommand();
init_GetBucketPolicyCommand();
init_GetBucketPolicyStatusCommand();
init_GetBucketReplicationCommand();
init_GetBucketRequestPaymentCommand();
init_GetBucketTaggingCommand();
init_GetBucketVersioningCommand();
init_GetBucketWebsiteCommand();
init_GetObjectAclCommand();
init_GetObjectAttributesCommand();
init_GetObjectCommand();
init_GetObjectLegalHoldCommand();
init_GetObjectLockConfigurationCommand();
init_GetObjectRetentionCommand();
init_GetObjectTaggingCommand();
init_GetObjectTorrentCommand();
init_GetPublicAccessBlockCommand();
init_HeadBucketCommand();
init_HeadObjectCommand();
init_ListBucketAnalyticsConfigurationsCommand();
init_ListBucketIntelligentTieringConfigurationsCommand();
init_ListBucketInventoryConfigurationsCommand();
init_ListBucketMetricsConfigurationsCommand();
init_ListBucketsCommand();
init_ListDirectoryBucketsCommand();
init_ListMultipartUploadsCommand();
init_ListObjectsCommand();
init_ListObjectsV2Command();
init_ListObjectVersionsCommand();
init_ListPartsCommand();
init_PutBucketAccelerateConfigurationCommand();
init_PutBucketAclCommand();
init_PutBucketAnalyticsConfigurationCommand();
init_PutBucketCorsCommand();
init_PutBucketEncryptionCommand();
init_PutBucketIntelligentTieringConfigurationCommand();
init_PutBucketInventoryConfigurationCommand();
init_PutBucketLifecycleConfigurationCommand();
init_PutBucketLoggingCommand();
init_PutBucketMetricsConfigurationCommand();
init_PutBucketNotificationConfigurationCommand();
init_PutBucketOwnershipControlsCommand();
init_PutBucketPolicyCommand();
init_PutBucketReplicationCommand();
init_PutBucketRequestPaymentCommand();
init_PutBucketTaggingCommand();
init_PutBucketVersioningCommand();
init_PutBucketWebsiteCommand();
init_PutObjectAclCommand();
init_PutObjectCommand();
init_PutObjectLegalHoldCommand();
init_PutObjectLockConfigurationCommand();
init_PutObjectRetentionCommand();
init_PutObjectTaggingCommand();
init_PutPublicAccessBlockCommand();
init_RestoreObjectCommand();
init_SelectObjectContentCommand();
init_UploadPartCommand();
init_UploadPartCopyCommand();
init_WriteGetObjectResponseCommand();
init_S3Client();
commands4 = {
AbortMultipartUploadCommand,
CompleteMultipartUploadCommand,
CopyObjectCommand,
CreateBucketCommand,
CreateBucketMetadataTableConfigurationCommand,
CreateMultipartUploadCommand,
CreateSessionCommand,
DeleteBucketCommand,
DeleteBucketAnalyticsConfigurationCommand,
DeleteBucketCorsCommand,
DeleteBucketEncryptionCommand,
DeleteBucketIntelligentTieringConfigurationCommand,
DeleteBucketInventoryConfigurationCommand,
DeleteBucketLifecycleCommand,
DeleteBucketMetadataTableConfigurationCommand,
DeleteBucketMetricsConfigurationCommand,
DeleteBucketOwnershipControlsCommand,
DeleteBucketPolicyCommand,
DeleteBucketReplicationCommand,
DeleteBucketTaggingCommand,
DeleteBucketWebsiteCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
DeleteObjectTaggingCommand,
DeletePublicAccessBlockCommand,
GetBucketAccelerateConfigurationCommand,
GetBucketAclCommand,
GetBucketAnalyticsConfigurationCommand,
GetBucketCorsCommand,
GetBucketEncryptionCommand,
GetBucketIntelligentTieringConfigurationCommand,
GetBucketInventoryConfigurationCommand,
GetBucketLifecycleConfigurationCommand,
GetBucketLocationCommand,
GetBucketLoggingCommand,
GetBucketMetadataTableConfigurationCommand,
GetBucketMetricsConfigurationCommand,
GetBucketNotificationConfigurationCommand,
GetBucketOwnershipControlsCommand,
GetBucketPolicyCommand,
GetBucketPolicyStatusCommand,
GetBucketReplicationCommand,
GetBucketRequestPaymentCommand,
GetBucketTaggingCommand,
GetBucketVersioningCommand,
GetBucketWebsiteCommand,
GetObjectCommand,
GetObjectAclCommand,
GetObjectAttributesCommand,
GetObjectLegalHoldCommand,
GetObjectLockConfigurationCommand,
GetObjectRetentionCommand,
GetObjectTaggingCommand,
GetObjectTorrentCommand,
GetPublicAccessBlockCommand,
HeadBucketCommand,
HeadObjectCommand,
ListBucketAnalyticsConfigurationsCommand,
ListBucketIntelligentTieringConfigurationsCommand,
ListBucketInventoryConfigurationsCommand,
ListBucketMetricsConfigurationsCommand,
ListBucketsCommand,
ListDirectoryBucketsCommand,
ListMultipartUploadsCommand,
ListObjectsCommand,
ListObjectsV2Command,
ListObjectVersionsCommand,
ListPartsCommand,
PutBucketAccelerateConfigurationCommand,
PutBucketAclCommand,
PutBucketAnalyticsConfigurationCommand,
PutBucketCorsCommand,
PutBucketEncryptionCommand,
PutBucketIntelligentTieringConfigurationCommand,
PutBucketInventoryConfigurationCommand,
PutBucketLifecycleConfigurationCommand,
PutBucketLoggingCommand,
PutBucketMetricsConfigurationCommand,
PutBucketNotificationConfigurationCommand,
PutBucketOwnershipControlsCommand,
PutBucketPolicyCommand,
PutBucketReplicationCommand,
PutBucketRequestPaymentCommand,
PutBucketTaggingCommand,
PutBucketVersioningCommand,
PutBucketWebsiteCommand,
PutObjectCommand,
PutObjectAclCommand,
PutObjectLegalHoldCommand,
PutObjectLockConfigurationCommand,
PutObjectRetentionCommand,
PutObjectTaggingCommand,
PutPublicAccessBlockCommand,
RestoreObjectCommand,
SelectObjectContentCommand,
UploadPartCommand,
UploadPartCopyCommand,
WriteGetObjectResponseCommand
};
S3 = class extends S3Client {
static {
__name(this, "S3");
}
};
createAggregatedClient(commands4, S3);
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/index.js
var init_commands5 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/commands/index.js"() {
init_import_meta_url();
init_AbortMultipartUploadCommand();
init_CompleteMultipartUploadCommand();
init_CopyObjectCommand();
init_CreateBucketCommand();
init_CreateBucketMetadataTableConfigurationCommand();
init_CreateMultipartUploadCommand();
init_CreateSessionCommand();
init_DeleteBucketAnalyticsConfigurationCommand();
init_DeleteBucketCommand();
init_DeleteBucketCorsCommand();
init_DeleteBucketEncryptionCommand();
init_DeleteBucketIntelligentTieringConfigurationCommand();
init_DeleteBucketInventoryConfigurationCommand();
init_DeleteBucketLifecycleCommand();
init_DeleteBucketMetadataTableConfigurationCommand();
init_DeleteBucketMetricsConfigurationCommand();
init_DeleteBucketOwnershipControlsCommand();
init_DeleteBucketPolicyCommand();
init_DeleteBucketReplicationCommand();
init_DeleteBucketTaggingCommand();
init_DeleteBucketWebsiteCommand();
init_DeleteObjectCommand();
init_DeleteObjectTaggingCommand();
init_DeleteObjectsCommand();
init_DeletePublicAccessBlockCommand();
init_GetBucketAccelerateConfigurationCommand();
init_GetBucketAclCommand();
init_GetBucketAnalyticsConfigurationCommand();
init_GetBucketCorsCommand();
init_GetBucketEncryptionCommand();
init_GetBucketIntelligentTieringConfigurationCommand();
init_GetBucketInventoryConfigurationCommand();
init_GetBucketLifecycleConfigurationCommand();
init_GetBucketLocationCommand();
init_GetBucketLoggingCommand();
init_GetBucketMetadataTableConfigurationCommand();
init_GetBucketMetricsConfigurationCommand();
init_GetBucketNotificationConfigurationCommand();
init_GetBucketOwnershipControlsCommand();
init_GetBucketPolicyCommand();
init_GetBucketPolicyStatusCommand();
init_GetBucketReplicationCommand();
init_GetBucketRequestPaymentCommand();
init_GetBucketTaggingCommand();
init_GetBucketVersioningCommand();
init_GetBucketWebsiteCommand();
init_GetObjectAclCommand();
init_GetObjectAttributesCommand();
init_GetObjectCommand();
init_GetObjectLegalHoldCommand();
init_GetObjectLockConfigurationCommand();
init_GetObjectRetentionCommand();
init_GetObjectTaggingCommand();
init_GetObjectTorrentCommand();
init_GetPublicAccessBlockCommand();
init_HeadBucketCommand();
init_HeadObjectCommand();
init_ListBucketAnalyticsConfigurationsCommand();
init_ListBucketIntelligentTieringConfigurationsCommand();
init_ListBucketInventoryConfigurationsCommand();
init_ListBucketMetricsConfigurationsCommand();
init_ListBucketsCommand();
init_ListDirectoryBucketsCommand();
init_ListMultipartUploadsCommand();
init_ListObjectVersionsCommand();
init_ListObjectsCommand();
init_ListObjectsV2Command();
init_ListPartsCommand();
init_PutBucketAccelerateConfigurationCommand();
init_PutBucketAclCommand();
init_PutBucketAnalyticsConfigurationCommand();
init_PutBucketCorsCommand();
init_PutBucketEncryptionCommand();
init_PutBucketIntelligentTieringConfigurationCommand();
init_PutBucketInventoryConfigurationCommand();
init_PutBucketLifecycleConfigurationCommand();
init_PutBucketLoggingCommand();
init_PutBucketMetricsConfigurationCommand();
init_PutBucketNotificationConfigurationCommand();
init_PutBucketOwnershipControlsCommand();
init_PutBucketPolicyCommand();
init_PutBucketReplicationCommand();
init_PutBucketRequestPaymentCommand();
init_PutBucketTaggingCommand();
init_PutBucketVersioningCommand();
init_PutBucketWebsiteCommand();
init_PutObjectAclCommand();
init_PutObjectCommand();
init_PutObjectLegalHoldCommand();
init_PutObjectLockConfigurationCommand();
init_PutObjectRetentionCommand();
init_PutObjectTaggingCommand();
init_PutPublicAccessBlockCommand();
init_RestoreObjectCommand();
init_SelectObjectContentCommand();
init_UploadPartCommand();
init_UploadPartCopyCommand();
init_WriteGetObjectResponseCommand();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/Interfaces.js
var init_Interfaces2 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/Interfaces.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListBucketsPaginator.js
var paginateListBuckets;
var init_ListBucketsPaginator = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListBucketsPaginator.js"() {
init_import_meta_url();
init_dist_es16();
init_ListBucketsCommand();
init_S3Client();
paginateListBuckets = createPaginator(S3Client, ListBucketsCommand, "ContinuationToken", "ContinuationToken", "MaxBuckets");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListDirectoryBucketsPaginator.js
var paginateListDirectoryBuckets;
var init_ListDirectoryBucketsPaginator = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListDirectoryBucketsPaginator.js"() {
init_import_meta_url();
init_dist_es16();
init_ListDirectoryBucketsCommand();
init_S3Client();
paginateListDirectoryBuckets = createPaginator(S3Client, ListDirectoryBucketsCommand, "ContinuationToken", "ContinuationToken", "MaxDirectoryBuckets");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListObjectsV2Paginator.js
var paginateListObjectsV2;
var init_ListObjectsV2Paginator = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListObjectsV2Paginator.js"() {
init_import_meta_url();
init_dist_es16();
init_ListObjectsV2Command();
init_S3Client();
paginateListObjectsV2 = createPaginator(S3Client, ListObjectsV2Command, "ContinuationToken", "NextContinuationToken", "MaxKeys");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListPartsPaginator.js
var paginateListParts;
var init_ListPartsPaginator = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/ListPartsPaginator.js"() {
init_import_meta_url();
init_dist_es16();
init_ListPartsCommand();
init_S3Client();
paginateListParts = createPaginator(S3Client, ListPartsCommand, "PartNumberMarker", "NextPartNumberMarker", "MaxParts");
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/index.js
var init_pagination3 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/pagination/index.js"() {
init_import_meta_url();
init_Interfaces2();
init_ListBucketsPaginator();
init_ListDirectoryBucketsPaginator();
init_ListObjectsV2Paginator();
init_ListPartsPaginator();
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/utils/sleep.js
var init_sleep = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/utils/sleep.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/waiter.js
var WaiterState;
var init_waiter2 = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/waiter.js"() {
init_import_meta_url();
(function(WaiterState2) {
WaiterState2["ABORTED"] = "ABORTED";
WaiterState2["FAILURE"] = "FAILURE";
WaiterState2["SUCCESS"] = "SUCCESS";
WaiterState2["RETRY"] = "RETRY";
WaiterState2["TIMEOUT"] = "TIMEOUT";
})(WaiterState || (WaiterState = {}));
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/poller.js
var init_poller = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/poller.js"() {
init_import_meta_url();
init_sleep();
init_waiter2();
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/utils/validate.js
var init_validate3 = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/utils/validate.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/utils/index.js
var init_utils10 = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/utils/index.js"() {
init_import_meta_url();
init_sleep();
init_validate3();
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/createWaiter.js
var init_createWaiter = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/createWaiter.js"() {
init_import_meta_url();
init_poller();
init_utils10();
init_waiter2();
}
});
// ../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/index.js
var init_dist_es72 = __esm({
"../../node_modules/.pnpm/@smithy+util-waiter@3.2.0/node_modules/@smithy/util-waiter/dist-es/index.js"() {
init_import_meta_url();
init_createWaiter();
init_waiter2();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForBucketExists.js
var init_waitForBucketExists = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForBucketExists.js"() {
init_import_meta_url();
init_dist_es72();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForBucketNotExists.js
var init_waitForBucketNotExists = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForBucketNotExists.js"() {
init_import_meta_url();
init_dist_es72();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForObjectExists.js
var init_waitForObjectExists = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForObjectExists.js"() {
init_import_meta_url();
init_dist_es72();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForObjectNotExists.js
var init_waitForObjectNotExists = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/waitForObjectNotExists.js"() {
init_import_meta_url();
init_dist_es72();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/index.js
var init_waiters = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/waiters/index.js"() {
init_import_meta_url();
init_waitForBucketExists();
init_waitForBucketNotExists();
init_waitForObjectExists();
init_waitForObjectNotExists();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/index.js
var init_models4 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/models/index.js"() {
init_import_meta_url();
init_models_0();
init_models_1();
}
});
// ../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/index.js
var init_dist_es73 = __esm({
"../../node_modules/.pnpm/@aws-sdk+client-s3@3.721.0/node_modules/@aws-sdk/client-s3/dist-es/index.js"() {
init_import_meta_url();
init_S3Client();
init_S3();
init_commands5();
init_pagination3();
init_waiters();
init_models4();
}
});
// src/pipelines/client.ts
async function generateR2ServiceToken(accountId, bucketName, pipelineName) {
const controller = new AbortController();
const signal = controller.signal;
const timeoutPromise = (0, import_promises26.setTimeout)(12e4, "timeout", { signal });
const serverPromise = new Promise((resolve25, reject) => {
const server = import_node_http2.default.createServer(async (request4, response) => {
(0, import_node_assert21.default)(request4.url, "This request doesn't have a URL");
if (request4.method !== "GET") {
response.writeHead(405);
response.end("Method not allowed.");
return;
}
const { pathname, searchParams } = new URL(
request4.url,
`http://${request4.headers.host}`
);
if (pathname !== "/") {
response.writeHead(404);
response.end("Not found.");
return;
}
const accessKeyId = searchParams.get("access-key-id");
const secretAccessKey = searchParams.get("secret-access-key");
if (!accessKeyId || !secretAccessKey) {
reject(new UserError("Missing required URL parameters"));
return;
}
resolve25({ accessKeyId, secretAccessKey });
response.writeHead(307, {
Location: "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted"
});
response.end();
});
signal.addEventListener("abort", () => {
server.close();
});
server.listen(8976, "localhost");
});
const env6 = getCloudflareApiEnvironmentFromEnv();
const oauthDomain = env6 === "staging" ? "oauth.pipelines-staging.cloudflare.com" : "oauth.pipelines.cloudflare.com";
const urlToOpen = `https://${oauthDomain}/oauth/login?accountId=${accountId}&bucketName=${bucketName}&pipelineName=${pipelineName}`;
logger.log(`Opening a link in your default browser: ${urlToOpen}`);
await openInBrowser(urlToOpen);
const result = await Promise.race([timeoutPromise, serverPromise]);
controller.abort();
if (result === "timeout") {
throw new UserError(
"Timed out waiting for authorization code, please try again."
);
}
return result;
}
async function getR2Bucket2(complianceConfig, accountId, name2) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/r2/buckets/${name2}`
);
}
async function createPipeline(complianceConfig, accountId, pipelineConfig) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pipelines`,
{
method: "POST",
headers: API_HEADERS,
body: JSON.stringify(pipelineConfig)
}
);
}
async function getPipeline(complianceConfig, accountId, name2) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pipelines/${name2}`,
{
method: "GET"
}
);
}
async function updatePipeline(complianceConfig, accountId, name2, pipelineConfig) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pipelines/${name2}`,
{
method: "PUT",
headers: API_HEADERS,
body: JSON.stringify(pipelineConfig)
}
);
}
async function listPipelines(complianceConfig, accountId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pipelines`,
{
method: "GET"
}
);
}
async function deletePipeline(complianceConfig, accountId, name2) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pipelines/${name2}`,
{
method: "DELETE",
headers: API_HEADERS
}
);
}
var import_node_assert21, import_node_crypto10, import_node_http2, import_promises26, API_HEADERS;
var init_client7 = __esm({
"src/pipelines/client.ts"() {
init_import_meta_url();
import_node_assert21 = __toESM(require("assert"));
import_node_crypto10 = require("crypto");
import_node_http2 = __toESM(require("http"));
import_promises26 = require("timers/promises");
init_cfetch();
init_misc_variables();
init_errors();
init_logger();
init_open_in_browser();
API_HEADERS = {
"Content-Type": "application/json"
};
__name(generateR2ServiceToken, "generateR2ServiceToken");
__name(getR2Bucket2, "getR2Bucket");
__name(createPipeline, "createPipeline");
__name(getPipeline, "getPipeline");
__name(updatePipeline, "updatePipeline");
__name(listPipelines, "listPipelines");
__name(deletePipeline, "deletePipeline");
}
});
// src/pipelines/index.ts
async function verifyBucketAccess(r22, bucketName) {
const MAX_ATTEMPTS2 = 10;
const DELAY_MS = 1e3;
const checkCredentials = /* @__PURE__ */ __name(async () => {
logger.debug(`Checking if credentials are active`);
await r22.send(new HeadBucketCommand({ Bucket: bucketName }));
}, "checkCredentials");
for (let attempt = 1; attempt <= MAX_ATTEMPTS2; attempt++) {
try {
logger.debug(`Attempt ${attempt} of ${MAX_ATTEMPTS2}`);
await checkCredentials();
return;
} catch (error2) {
logger.debug("HeadBucket request failed", error2);
if (attempt === MAX_ATTEMPTS2) {
throw error2;
}
await (0, import_promises27.setTimeout)(DELAY_MS);
}
}
}
async function authorizeR2Bucket(complianceConfig, pipelineName, accountId, bucketName) {
try {
await getR2Bucket2(complianceConfig, accountId, bucketName);
} catch (err) {
if (err instanceof APIError) {
if (err.code == 10006) {
throw new FatalError(`The R2 bucket [${bucketName}] doesn't exist`);
}
}
throw err;
}
logger.log(`\u{1F300} Authorizing R2 bucket "${bucketName}"`);
const serviceToken = await generateR2ServiceToken(
accountId,
bucketName,
pipelineName
);
if (__testSkipDelaysFlag) {
return serviceToken;
}
const endpoint = getAccountR2Endpoint(accountId);
logger.debug(`Using R2 Endpoint ${endpoint}`);
const r22 = new S3Client({
region: "auto",
credentials: {
accessKeyId: serviceToken.accessKeyId,
secretAccessKey: serviceToken.secretAccessKey
},
endpoint
});
logger.log(`\u{1F300} Checking access to R2 bucket "${bucketName}"`);
await verifyBucketAccess(r22, bucketName);
return serviceToken;
}
function getAccountR2Endpoint(accountId) {
const env6 = getCloudflareApiEnvironmentFromEnv();
if (env6 === "staging") {
return `https://${accountId}.r2-staging.cloudflarestorage.com`;
}
return `https://${accountId}.r2.cloudflarestorage.com`;
}
function parseTransform(spec) {
const [script, entrypoint, ...rest] = spec.split(".");
if (!script || rest.length > 0) {
throw new Error(
"Invalid transform: required syntax <script>[.<entrypoint>]"
);
}
return {
script,
entrypoint: entrypoint || "Transform"
};
}
function formatPipelinePretty(pipeline) {
let buffer = "";
const formatTypeLabels = {
json: "JSON"
};
buffer += `${formatLabelledValues({
Id: pipeline.id,
Name: pipeline.name
})}
`;
buffer += "Sources:\n";
const httpSource = pipeline.source.find((s5) => s5.type === "http");
if (httpSource) {
const httpInfo = {
Endpoint: pipeline.endpoint,
Authentication: httpSource.authentication === true ? "on" : "off",
...httpSource?.cors?.origins && {
"CORS Origins": httpSource.cors.origins.join(", ")
},
Format: formatTypeLabels[httpSource.format]
};
buffer += " HTTP:\n";
buffer += `${formatLabelledValues(httpInfo, { indentationCount: 4 })}
`;
}
const bindingSource = pipeline.source.find((s5) => s5.type === "binding");
if (bindingSource) {
const bindingInfo = {
Format: formatTypeLabels[bindingSource.format]
};
buffer += " Worker:\n";
buffer += `${formatLabelledValues(bindingInfo, { indentationCount: 4 })}
`;
}
const destinationInfo = {
Type: pipeline.destination.type.toUpperCase(),
Bucket: pipeline.destination.path.bucket,
Format: "newline-delimited JSON",
// TODO: Make dynamic once we support more output formats
...pipeline.destination.path.prefix && {
Prefix: pipeline.destination.path.prefix
},
...pipeline.destination.compression.type && {
Compression: pipeline.destination.compression.type.toUpperCase()
}
};
buffer += "Destination:\n";
buffer += `${formatLabelledValues(destinationInfo, { indentationCount: 2 })}
`;
const batchHints = {
...pipeline.destination.batch.max_bytes && {
"Max bytes": prettyBytes(pipeline.destination.batch.max_bytes)
},
...pipeline.destination.batch.max_duration_s && {
"Max duration": `${pipeline.destination.batch.max_duration_s?.toLocaleString()} seconds`
},
...pipeline.destination.batch.max_rows && {
"Max records": pipeline.destination.batch.max_rows?.toLocaleString()
}
};
if (Object.keys(batchHints).length > 0) {
buffer += " Batch hints:\n";
buffer += `${formatLabelledValues(batchHints, { indentationCount: 4 })}
`;
}
return buffer;
}
var import_promises27, BYTES_PER_MB, __testSkipDelaysFlag, pipelinesNamespace;
var init_pipelines = __esm({
"src/pipelines/index.ts"() {
init_import_meta_url();
import_promises27 = require("timers/promises");
init_dist_es73();
init_pretty_bytes();
init_create_command();
init_misc_variables();
init_errors();
init_logger();
init_parse();
init_render_labelled_values();
init_client7();
BYTES_PER_MB = 1e3 * 1e3;
__testSkipDelaysFlag = false;
__name(verifyBucketAccess, "verifyBucketAccess");
__name(authorizeR2Bucket, "authorizeR2Bucket");
__name(getAccountR2Endpoint, "getAccountR2Endpoint");
__name(parseTransform, "parseTransform");
pipelinesNamespace = createNamespace({
metadata: {
description: "\u{1F6B0} Manage Cloudflare Pipelines",
owner: "Product: Pipelines",
status: "open-beta"
}
});
__name(formatPipelinePretty, "formatPipelinePretty");
}
});
// src/pipelines/validate.ts
function validateName(label, name2) {
if (!name2.match(/^[a-zA-Z0-9-]+$/)) {
throw new UserError(`Must provide a valid ${label}`);
}
}
function validateCorsOrigins(values) {
if (!values || !values.length) {
return values;
}
if (values.includes("none")) {
if (values.length > 1) {
throw new UserError(
"When specifying 'none', only one value is permitted."
);
}
return [];
}
if (values.includes("*")) {
if (values.length > 1) {
throw new UserError("When specifying '*', only one value is permitted.");
}
return values;
}
for (const value of values) {
if (!value.match(/^https?:\/\/[^/]+$/i)) {
throw new UserError(
`Provided value ${value} is not a valid CORS origin.`
);
}
}
return values;
}
function validateInRange(name2, min, max) {
return (val2) => {
if (val2 < min || val2 > max) {
throw new UserError(`${name2} must be between ${min} and ${max}`);
}
return val2;
};
}
var init_validate4 = __esm({
"src/pipelines/validate.ts"() {
init_import_meta_url();
init_errors();
__name(validateName, "validateName");
__name(validateCorsOrigins, "validateCorsOrigins");
__name(validateInRange, "validateInRange");
}
});
// src/pipelines/cli/create.ts
var pipelinesCreateCommand;
var init_create5 = __esm({
"src/pipelines/cli/create.ts"() {
init_import_meta_url();
init_config2();
init_create_command();
init_errors();
init_logger();
init_helpers();
init_user2();
init_getValidBindingName();
init_client7();
init_pipelines();
init_validate4();
pipelinesCreateCommand = createCommand({
metadata: {
description: "Create a new pipeline",
owner: "Product: Pipelines",
status: "open-beta"
},
args: {
pipeline: {
describe: "The name of the new pipeline",
type: "string",
demandOption: true
},
source: {
type: "array",
describe: "Space separated list of allowed sources. Options are 'http' or 'worker'",
default: ["http", "worker"],
demandOption: false,
group: "Source settings"
},
"require-http-auth": {
type: "boolean",
describe: "Require Cloudflare API Token for HTTPS endpoint authentication",
default: false,
demandOption: false,
group: "Source settings"
},
"cors-origins": {
type: "array",
describe: "CORS origin allowlist for HTTP endpoint (use * for any origin). Defaults to an empty array",
demandOption: false,
coerce: validateCorsOrigins,
group: "Source settings"
},
"batch-max-mb": {
type: "number",
describe: "Maximum batch size in megabytes before flushing. Defaults to 100 MB if unset. Minimum: 1, Maximum: 100",
demandOption: false,
coerce: validateInRange("batch-max-mb", 1, 100),
group: "Batch hints"
},
"batch-max-rows": {
type: "number",
describe: "Maximum number of rows per batch before flushing. Defaults to 10,000,000 if unset. Minimum: 100, Maximum: 10,000,000",
demandOption: false,
coerce: validateInRange("batch-max-rows", 100, 1e7),
group: "Batch hints"
},
"batch-max-seconds": {
type: "number",
describe: "Maximum age of batch in seconds before flushing. Defaults to 300 if unset. Minimum: 1, Maximum: 300",
demandOption: false,
coerce: validateInRange("batch-max-seconds", 1, 300),
group: "Batch hints"
},
// Transform options
"transform-worker": {
type: "string",
describe: "Pipeline transform Worker and entrypoint (<worker>.<entrypoint>)",
demandOption: false,
hidden: true,
// TODO: Remove once transformations launch
group: "Transformations"
},
"r2-bucket": {
type: "string",
describe: "Destination R2 bucket name",
demandOption: true,
group: "Destination settings"
},
"r2-access-key-id": {
type: "string",
describe: "R2 service Access Key ID for authentication. Leave empty for OAuth confirmation.",
demandOption: false,
group: "Destination settings",
implies: "r2-secret-access-key"
},
"r2-secret-access-key": {
type: "string",
describe: "R2 service Secret Access Key for authentication. Leave empty for OAuth confirmation.",
demandOption: false,
group: "Destination settings",
implies: "r2-access-key-id"
},
"r2-prefix": {
type: "string",
describe: "Prefix for storing files in the destination bucket. Default is no prefix",
default: "",
demandOption: false,
group: "Destination settings"
},
compression: {
type: "string",
describe: "Compression format for output files",
choices: ["none", "gzip", "deflate"],
default: "gzip",
demandOption: false,
group: "Destination settings"
},
// Pipeline settings
"shard-count": {
type: "number",
describe: "Number of shards for the pipeline. More shards handle higher request volume; fewer shards produce larger output files. Defaults to 2 if unset. Minimum: 1, Maximum: 15",
demandOption: false,
group: "Pipeline settings"
}
},
positionalArgs: ["pipeline"],
validateArgs(args) {
if (args.r2AccessKeyId && !args.r2SecretAccessKey || !args.r2AccessKeyId && args.r2SecretAccessKey) {
throw new UserError(
"--r2-access-key-id and --r2-secret-access-key must be provided together"
);
}
},
async handler(args, { config }) {
const bucket = args.r2Bucket;
if (!isValidR2BucketName(bucket)) {
throw new UserError(
`The bucket name "${bucket}" is invalid. ${bucketFormatMessage}`
);
}
const name2 = args.pipeline;
const compression = args.compression;
const batch = {
max_bytes: args.batchMaxMb ? args.batchMaxMb * BYTES_PER_MB : void 0,
max_duration_s: args.batchMaxSeconds,
max_rows: args.batchMaxRows
};
const accountId = await requireAuth(config);
const pipelineConfig = {
name: name2,
metadata: {},
source: [],
transforms: [],
destination: {
type: "r2",
format: "json",
compression: {
type: compression
},
batch,
path: {
bucket
},
credentials: {
endpoint: getAccountR2Endpoint(accountId),
access_key_id: args.r2AccessKeyId || "",
secret_access_key: args.r2SecretAccessKey || ""
}
}
};
const destination = pipelineConfig.destination;
if (!destination.credentials.access_key_id && !destination.credentials.secret_access_key) {
const auth = await authorizeR2Bucket(
config,
name2,
accountId,
pipelineConfig.destination.path.bucket
);
destination.credentials.access_key_id = auth.accessKeyId;
destination.credentials.secret_access_key = auth.secretAccessKey;
}
if (!destination.credentials.access_key_id) {
throw new FatalError("Requires a r2 access key id");
}
if (!destination.credentials.secret_access_key) {
throw new FatalError("Requires a r2 secret access key");
}
if (args.source.length > 0) {
const sourceHandlers = {
http: /* @__PURE__ */ __name(() => {
const http5 = {
type: "http",
format: "json",
authentication: args.requireHttpAuth
};
if (args.corsOrigins && args.corsOrigins.length > 0) {
http5.cors = { origins: args.corsOrigins };
}
return http5;
}, "http"),
worker: /* @__PURE__ */ __name(() => ({
type: "binding",
format: "json"
}), "worker")
};
for (const source of args.source) {
const handler = sourceHandlers[source];
if (handler) {
pipelineConfig.source.push(handler());
}
}
}
if (pipelineConfig.source.length === 0) {
throw new UserError(
"No sources have been enabled. At least one source (HTTP or Worker Binding) should be enabled"
);
}
if (args.transformWorker) {
pipelineConfig.transforms.push(parseTransform(args.transformWorker));
}
if (args.r2Prefix) {
pipelineConfig.destination.path.prefix = args.r2Prefix;
}
if (args.shardCount) {
pipelineConfig.metadata.shards = args.shardCount;
}
logger.log(`\u{1F300} Creating pipeline named "${name2}"`);
const pipeline = await createPipeline(config, accountId, pipelineConfig);
logger.log(
`\u2705 Successfully created pipeline "${pipeline.name}" with ID ${pipeline.id}
`
);
logger.log(formatPipelinePretty(pipeline));
logger.log("\u{1F389} You can now send data to your pipeline!");
if (args.source.includes("worker")) {
await updateConfigFile(
(bindingName) => ({
pipelines: [
{
pipeline: pipeline.name,
binding: getValidBindingName(
bindingName ?? "PIPELINE",
"PIPELINE"
)
}
]
}),
config.configPath,
args.env
);
}
if (args.source.includes("http")) {
logger.log(`
Send data to your pipeline's HTTP endpoint:
`);
logger.log(`curl "${pipeline.endpoint}" -d '[{"foo": "bar"}]'
`);
}
}
});
}
});
// src/pipelines/cli/delete.ts
var pipelinesDeleteCommand;
var init_delete5 = __esm({
"src/pipelines/cli/delete.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_client7();
init_validate4();
pipelinesDeleteCommand = createCommand({
metadata: {
description: "Delete a pipeline",
owner: "Product: Pipelines",
status: "open-beta"
},
args: {
pipeline: {
type: "string",
describe: "The name of the pipeline to delete",
demandOption: true
}
},
positionalArgs: ["pipeline"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
const name2 = args.pipeline;
validateName("pipeline name", name2);
logger.log(`Deleting pipeline ${name2}.`);
await deletePipeline(config, accountId, name2);
logger.log(`Deleted pipeline ${name2}.`);
}
});
}
});
// src/pipelines/cli/get.ts
var pipelinesGetCommand;
var init_get2 = __esm({
"src/pipelines/cli/get.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_client7();
init_pipelines();
init_validate4();
pipelinesGetCommand = createCommand({
metadata: {
description: "Get a pipeline's configuration",
owner: "Product: Pipelines",
status: "open-beta"
},
args: {
pipeline: {
type: "string",
describe: "The name of the pipeline to inspect",
demandOption: true
},
format: {
choices: ["pretty", "json"],
describe: "The output format for pipeline",
default: "pretty"
}
},
positionalArgs: ["pipeline"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
const name2 = args.pipeline;
validateName("pipeline name", name2);
const pipeline = await getPipeline(config, accountId, name2);
switch (args.format) {
case "json":
logger.log(JSON.stringify(pipeline, null, 2));
break;
case "pretty":
logger.log(formatPipelinePretty(pipeline));
break;
}
}
});
}
});
// src/pipelines/cli/list.ts
var pipelinesListCommand;
var init_list5 = __esm({
"src/pipelines/cli/list.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_client7();
pipelinesListCommand = createCommand({
metadata: {
description: "List all pipelines",
owner: "Product: Pipelines",
status: "open-beta"
},
async handler(_4, { config }) {
const accountId = await requireAuth(config);
const list = await listPipelines(config, accountId);
logger.table(
list.map((pipeline) => ({
name: pipeline.name,
id: pipeline.id,
endpoint: pipeline.endpoint
}))
);
}
});
}
});
// src/pipelines/cli/update.ts
var pipelinesUpdateCommand;
var init_update2 = __esm({
"src/pipelines/cli/update.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_user2();
init_client7();
init_pipelines();
init_validate4();
pipelinesUpdateCommand = createCommand({
metadata: {
description: "Update a pipeline",
owner: "Product: Pipelines",
status: "open-beta"
},
positionalArgs: ["pipeline"],
args: {
pipeline: {
describe: "The name of the new pipeline",
type: "string",
demandOption: true
},
source: {
type: "array",
describe: "Space separated list of allowed sources. Options are 'http' or 'worker'",
group: "Source settings"
},
"require-http-auth": {
type: "boolean",
describe: "Require Cloudflare API Token for HTTPS endpoint authentication",
group: "Source settings"
},
"cors-origins": {
type: "array",
describe: "CORS origin allowlist for HTTP endpoint (use * for any origin). Defaults to an empty array",
demandOption: false,
coerce: validateCorsOrigins,
group: "Source settings"
},
"batch-max-mb": {
type: "number",
describe: "Maximum batch size in megabytes before flushing. Defaults to 100 MB if unset. Minimum: 1, Maximum: 100",
demandOption: false,
coerce: validateInRange("batch-max-mb", 1, 100),
group: "Batch hints"
},
"batch-max-rows": {
type: "number",
describe: "Maximum number of rows per batch before flushing. Defaults to 10,000,000 if unset. Minimum: 100, Maximum: 10,000,000",
demandOption: false,
coerce: validateInRange("batch-max-rows", 100, 1e7),
group: "Batch hints"
},
"batch-max-seconds": {
type: "number",
describe: "Maximum age of batch in seconds before flushing. Defaults to 300 if unset. Minimum: 1, Maximum: 300",
demandOption: false,
coerce: validateInRange("batch-max-seconds", 1, 300),
group: "Batch hints"
},
// Transform options
"transform-worker": {
type: "string",
describe: "Pipeline transform Worker and entrypoint (<worker>.<entrypoint>)",
demandOption: false,
hidden: true,
// TODO: Remove once transformations launch
group: "Transformations"
},
"r2-bucket": {
type: "string",
describe: "Destination R2 bucket name",
group: "Destination settings"
},
"r2-access-key-id": {
type: "string",
describe: "R2 service Access Key ID for authentication. Leave empty for OAuth confirmation.",
demandOption: false,
group: "Destination settings",
implies: "r2-secret-access-key"
},
"r2-secret-access-key": {
type: "string",
describe: "R2 service Secret Access Key for authentication. Leave empty for OAuth confirmation.",
demandOption: false,
group: "Destination settings",
implies: "r2-access-key-id"
},
"r2-prefix": {
type: "string",
describe: "Prefix for storing files in the destination bucket. Default is no prefix",
demandOption: false,
group: "Destination settings"
},
compression: {
type: "string",
describe: "Compression format for output files",
choices: ["none", "gzip", "deflate"],
demandOption: false,
group: "Destination settings"
},
// Pipeline settings
"shard-count": {
type: "number",
describe: "Number of shards for the pipeline. More shards handle higher request volume; fewer shards produce larger output files. Defaults to 2 if unset. Minimum: 1, Maximum: 15",
demandOption: false,
group: "Pipeline settings"
}
},
async handler(args, { config }) {
const name2 = args.pipeline;
const accountId = await requireAuth(config);
const pipelineConfig = await getPipeline(config, accountId, name2);
if (args.compression) {
pipelineConfig.destination.compression.type = args.compression;
}
if (args.batchMaxMb) {
pipelineConfig.destination.batch.max_bytes = args.batchMaxMb * BYTES_PER_MB;
}
if (args.batchMaxSeconds) {
pipelineConfig.destination.batch.max_duration_s = args.batchMaxSeconds;
}
if (args.batchMaxRows) {
pipelineConfig.destination.batch.max_rows = args.batchMaxRows;
}
const bucket = args.r2Bucket;
const accessKeyId = args.r2AccessKeyId;
const secretAccessKey = args.r2SecretAccessKey;
if (bucket || accessKeyId || secretAccessKey) {
const destination = pipelineConfig.destination;
if (bucket) {
pipelineConfig.destination.path.bucket = bucket;
}
destination.credentials = {
endpoint: getAccountR2Endpoint(accountId),
access_key_id: accessKeyId || "",
secret_access_key: secretAccessKey || ""
};
if (!accessKeyId && !secretAccessKey) {
const auth = await authorizeR2Bucket(
config,
name2,
accountId,
destination.path.bucket
);
destination.credentials.access_key_id = auth.accessKeyId;
destination.credentials.secret_access_key = auth.secretAccessKey;
}
if (!destination.credentials.access_key_id) {
throw new FatalError("Requires a r2 access key id");
}
if (!destination.credentials.secret_access_key) {
throw new FatalError("Requires a r2 secret access key");
}
}
if (args.source && args.source.length > 0) {
const existingSources = pipelineConfig.source;
pipelineConfig.source = [];
const sourceHandlers = {
http: /* @__PURE__ */ __name(() => {
const existing = existingSources.find(
(s5) => s5.type === "http"
);
return {
...existing,
// Copy over existing properties for forwards compatibility
type: "http",
format: "json",
...args.requireHttpAuth && {
authentication: args.requireHttpAuth
}
// Include only if defined
};
}, "http"),
worker: /* @__PURE__ */ __name(() => {
const existing = existingSources.find(
(s5) => s5.type === "binding"
);
return {
...existing,
// Copy over existing properties for forwards compatibility
type: "binding",
format: "json"
};
}, "worker")
};
for (const source of args.source) {
const handler = sourceHandlers[source];
if (handler) {
pipelineConfig.source.push(handler());
}
}
}
if (pipelineConfig.source.length === 0) {
throw new UserError(
"No sources have been enabled. At least one source (HTTP or Worker Binding) should be enabled"
);
}
if (args.transformWorker) {
if (args.transformWorker === "none") {
pipelineConfig.transforms = [];
} else {
pipelineConfig.transforms.push(parseTransform(args.transformWorker));
}
}
if (args.r2Prefix) {
pipelineConfig.destination.path.prefix = args.r2Prefix;
}
if (args.shardCount) {
pipelineConfig.metadata.shards = args.shardCount;
}
const httpSource = pipelineConfig.source.find(
(s5) => s5.type === "http"
);
if (httpSource) {
if (args.requireHttpAuth) {
httpSource.authentication = args.requireHttpAuth;
}
if (args.corsOrigins) {
httpSource.cors = { origins: args.corsOrigins };
}
}
logger.log(`\u{1F300} Updating pipeline "${name2}"`);
const pipeline = await updatePipeline(
config,
accountId,
name2,
pipelineConfig
);
logger.log(
`\u2705 Successfully updated pipeline "${pipeline.name}" with ID ${pipeline.id}
`
);
}
});
}
});
// src/pubsub/index.ts
async function listPubSubNamespaces(complianceConfig, accountId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces`
);
}
async function createPubSubNamespace(complianceConfig, accountId, namespace) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces`,
{
method: "POST",
body: JSON.stringify(namespace)
}
);
}
async function deletePubSubNamespace(complianceConfig, accountId, namespace) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}`,
{ method: "DELETE" }
);
}
async function describePubSubNamespace(complianceConfig, accountId, namespace) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}`,
{ method: "GET" }
);
}
async function deletePubSubBroker(complianceConfig, accountId, namespace, broker) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}`,
{ method: "DELETE" }
);
}
async function describePubSubBroker(complianceConfig, accountId, namespace, broker) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}`,
{ method: "GET" }
);
}
async function listPubSubBrokers(complianceConfig, accountId, namespace) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers`
);
}
async function createPubSubBroker(complianceConfig, accountId, namespace, broker) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers`,
{ method: "POST", body: JSON.stringify(broker) }
);
}
async function updatePubSubBroker(complianceConfig, accountId, namespace, broker, update) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}`,
{ method: "PATCH", body: JSON.stringify(update) }
);
}
async function getPubSubBrokerPublicKeys(complianceConfig, accountId, namespace, broker) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}/publickeys`
);
}
async function issuePubSubBrokerTokens(complianceConfig, accountId, namespace, broker, number, type, clientIds, expiration) {
let url4 = `/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}/credentials`;
const params = new URLSearchParams();
params.append("number", `${number}`);
params.append("type", type);
if (clientIds) {
for (const id of clientIds) {
params.append("clientid", id);
}
}
if (expiration) {
params.append("expiration", `${expiration}`);
}
url4 = url4 + `?${params.toString()}`;
return await fetchResult(complianceConfig, url4);
}
async function revokePubSubBrokerTokens(complianceConfig, accountId, namespace, broker, jti) {
let url4 = `/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}/revocations`;
const params = new URLSearchParams();
for (const j6 of jti) {
params.append("jti", j6);
}
url4 = url4 + `?${params.toString()}`;
return await fetchResult(complianceConfig, url4, {
method: "POST",
body: ""
});
}
async function unrevokePubSubBrokerTokens(complianceConfig, accountId, namespace, broker, jti) {
let url4 = `/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}/revocations`;
const params = new URLSearchParams();
for (const j6 of jti) {
params.append("jti", j6);
}
url4 = url4 + `?${params.toString()}`;
return await fetchResult(complianceConfig, url4, { method: "DELETE" });
}
async function listRevokedPubSubBrokerTokens(complianceConfig, accountId, namespace, broker) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/pubsub/namespaces/${namespace}/brokers/${broker}/revocations`
);
}
var pubSubBetaWarning;
var init_pubsub = __esm({
"src/pubsub/index.ts"() {
init_import_meta_url();
init_cfetch();
pubSubBetaWarning = "\u{1F477}\u{1F3FD} 'wrangler pubsub ...' commands are currently in private beta. If your account isn't authorized, commands will fail. Visit the Pub/Sub docs for more info: https://developers.cloudflare.com/pub-sub/";
__name(listPubSubNamespaces, "listPubSubNamespaces");
__name(createPubSubNamespace, "createPubSubNamespace");
__name(deletePubSubNamespace, "deletePubSubNamespace");
__name(describePubSubNamespace, "describePubSubNamespace");
__name(deletePubSubBroker, "deletePubSubBroker");
__name(describePubSubBroker, "describePubSubBroker");
__name(listPubSubBrokers, "listPubSubBrokers");
__name(createPubSubBroker, "createPubSubBroker");
__name(updatePubSubBroker, "updatePubSubBroker");
__name(getPubSubBrokerPublicKeys, "getPubSubBrokerPublicKeys");
__name(issuePubSubBrokerTokens, "issuePubSubBrokerTokens");
__name(revokePubSubBrokerTokens, "revokePubSubBrokerTokens");
__name(unrevokePubSubBrokerTokens, "unrevokePubSubBrokerTokens");
__name(listRevokedPubSubBrokerTokens, "listRevokedPubSubBrokerTokens");
}
});
// src/pubsub/pubsub-commands.ts
function pubSubCommands(pubsubYargs, subHelp) {
return pubsubYargs.command(subHelp).command(
"namespace",
"Manage your Pub/Sub Namespaces",
(pubsubNamespaceYargs) => {
return pubsubNamespaceYargs.command(
"create <name>",
"Create a new Pub/Sub Namespace",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the new Namespace. This name will form part of the public endpoint, in the form <broker>.<namespace>.cloudflarepubsub.com",
type: "string",
demandOption: true
}).option("description", {
describe: "Textual description of Namespace",
type: "string"
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
const namespace = {
name: args.name
};
if (args.description) {
namespace.description = args.description;
}
logger.log(`Creating Pub/Sub Namespace ${args.name}...`);
await createPubSubNamespace(config, accountId, namespace);
logger.log(`Success! Created Pub/Sub Namespace ${args.name}`);
sendMetricsEvent("create pubsub namespace", {
sendMetrics: config.send_metrics
});
}
).command(
"list",
"List your existing Pub/Sub Namespaces",
(yargs) => {
return yargs.epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(await listPubSubNamespaces(config, accountId));
sendMetricsEvent("list pubsub namespaces", {
sendMetrics: config.send_metrics
});
}
).command(
"delete <name>",
"Delete a Pub/Sub Namespace",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the namespace to delete",
type: "string",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
if (await confirm(
`\uFE0F\u2757\uFE0F Are you sure you want to delete the Pub/Sub Namespace ${args.name}? This cannot be undone.
This name will be available for others to register.`
)) {
logger.log(`Deleting namespace ${args.name}...`);
await deletePubSubNamespace(
config,
accountId,
args.name
);
logger.log(`Deleted namespace ${args.name}.`);
sendMetricsEvent("delete pubsub namespace", {
sendMetrics: config.send_metrics
});
}
}
).command(
"describe <name>",
"Describe a Pub/Sub Namespace",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the namespace to describe.",
type: "string",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(
await describePubSubNamespace(
config,
accountId,
args.name
)
);
sendMetricsEvent("view pubsub namespace", {
sendMetrics: config.send_metrics
});
}
).epilogue(pubSubBetaWarning);
}
).command("broker", "Interact with your Pub/Sub Brokers", (brokersYargs) => {
brokersYargs.command(
"create <name>",
"Create a new Pub/Sub Broker",
(yargs) => yargs.positional("name", {
describe: "The name of the Pub/Sub Broker. This name will form part of the public endpoint, in the form <broker>.<namespace>.cloudflarepubsub.com",
type: "string",
demandOption: true
}).option("namespace", {
describe: "An existing Namespace to associate the Broker with. This name will form part of the public endpoint, in the form <broker>.<namespace>.cloudflarepubsub.com",
type: "string",
alias: "ns",
demandOption: true
}).option("description", {
describe: "Longer description for the broker",
type: "string"
}).option("expiration", {
describe: "Time to allow token validity (can use seconds, hours, months, weeks, years)",
type: "string"
}).option("on-publish-url", {
describe: "A (HTTPS) Cloudflare Worker (or webhook) URL that messages will be sent to on-publish.",
type: "string"
}).epilogue(pubSubBetaWarning),
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
const broker = {
name: args.name
};
if (args.description) {
broker.description = args.description;
}
if (args.expiration) {
const expiration = parseHumanDuration(args.expiration);
if (isNaN(expiration)) {
throw new CommandLineArgsError(
`${args.expiration} is not a time duration. (Example of valid values are: 1y, 6 days)`
);
}
broker.expiration = expiration;
}
if (args["on-publish-url"]) {
broker.on_publish = {
url: args["on-publish-url"]
};
}
logger.log(
await createPubSubBroker(
config,
accountId,
args.namespace,
broker
)
);
sendMetricsEvent("create pubsub broker", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"update <name>",
"Update an existing Pub/Sub Broker's configuration.",
(yargs) => yargs.positional("name", {
describe: "The name of an existing Pub/Sub Broker",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with",
type: "string",
alias: "ns",
demandOption: true
}).option("description", {
describe: "A optional description of the Broker.",
type: "string"
}).option("expiration", {
describe: "The expiration date for all client credentials issued by the Broker (can use seconds, hours, months, weeks, years)",
type: "string"
}).option("on-publish-url", {
describe: "A (HTTPS) Cloudflare Worker (or webhook) URL that messages will be sent to on-publish.",
type: "string"
}).epilogue(pubSubBetaWarning),
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
const broker = {};
if (args.description) {
broker.description = args.description;
}
if (args.expiration) {
const expiration = parseHumanDuration(args.expiration);
if (isNaN(expiration)) {
throw new CommandLineArgsError(
`${args.expiration} is not a time duration. Examples of valid values include: '1y', '24h', or '6 days'.`
);
}
broker.expiration = expiration;
}
if (args["on-publish-url"]) {
broker.on_publish = {
url: args["on-publish-url"]
};
}
logger.log(
await updatePubSubBroker(
config,
accountId,
args.namespace,
args.name,
broker
)
);
logger.log(`Successfully updated Pub/Sub Broker ${args.name}`);
sendMetricsEvent("update pubsub broker", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"list",
"List the Pub/Sub Brokers within a Namespace",
(yargs) => {
return yargs.option("namespace", {
describe: "The Namespace the Brokers are associated with.",
type: "string",
alias: "ns",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(
await listPubSubBrokers(config, accountId, args.namespace)
);
sendMetricsEvent("list pubsub brokers", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"delete <name>",
"Delete an existing Pub/Sub Broker",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to delete",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
if (await confirm(
`\uFE0F\u2757\uFE0F Are you sure you want to delete the Pub/Sub Broker ${args.name}? This cannot be undone.
All existing clients will be disconnected.`
)) {
logger.log(`Deleting Pub/Sub Broker ${args.name}.`);
await deletePubSubBroker(
config,
accountId,
args.namespace,
args.name
);
logger.log(`Deleted Pub/Sub Broker ${args.name}.`);
sendMetricsEvent("delete pubsub broker", {
sendMetrics: config.send_metrics
});
}
}
).command(
"describe <name>",
"Describe an existing Pub/Sub Broker.",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to describe.",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(
await describePubSubBroker(
config,
accountId,
args.namespace,
args.name
)
);
sendMetricsEvent("view pubsub broker", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"issue <name>",
"Issue new client credentials for a specific Pub/Sub Broker.",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to issue credentials for.",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).option("number", {
describe: "The number of credentials to generate.",
type: "number",
alias: "n",
default: 1
}).option("type", {
describe: "The type of credential to generate.",
type: "string",
default: "TOKEN"
}).option("expiration", {
describe: "The expiration to set on the issued credentials. This overrides any Broker-level expiration that is set.",
type: "string",
alias: "exp"
}).option("client-id", {
describe: "A list of existing clientIds to generate tokens for. By default, clientIds are randomly generated.",
type: "string",
alias: "jti",
array: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
let parsedExpiration;
if (args.expiration) {
const expiration = parseHumanDuration(args.expiration);
if (isNaN(expiration)) {
throw new CommandLineArgsError(
`${args.expiration} is not a time duration. Example of valid values are: 1y, 6 days.`
);
}
parsedExpiration = expiration;
}
logger.log(
`\u{1F511} Issuing credential(s) for ${args.name}.${args.namespace}...`
);
logger.log(
await issuePubSubBrokerTokens(
config,
accountId,
args.namespace,
args.name,
args.number,
args.type,
args["client-id"],
parsedExpiration
)
);
sendMetricsEvent("issue pubsub broker credentials", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"revoke <name>",
"Revoke a set of active client credentials associated with the given Broker",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to revoke credentials against.",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).option("jti", {
describe: "Tokens to revoke",
type: "string",
demandOption: true,
array: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
const numTokens = args.jti.length;
logger.log(
`\u{1F534} Revoking access to ${args.name} for ${numTokens} credential(s)...`
);
await revokePubSubBrokerTokens(
config,
accountId,
args.namespace,
args.name,
args.jti
);
logger.log(`Revoked ${args.jti.length} credential(s).`);
sendMetricsEvent("revoke pubsub broker credentials", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"unrevoke <name>",
"Restore access to a set of previously revoked client credentials.",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to revoke credentials against.",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).option("jti", {
describe: "Tokens to revoke",
type: "string",
demandOption: true,
array: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
const numTokens = args.jti.length;
logger.log(
`\u{1F7E2} Restoring access to ${args.broker} for ${numTokens} credential(s)...`
);
await unrevokePubSubBrokerTokens(
config,
accountId,
args.namespace,
args.name,
args.jti
);
logger.log(`Unrevoked ${numTokens} credential(s)`);
sendMetricsEvent("unrevoke pubsub broker credentials", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"show-revocations <name>",
"Show all previously revoked client credentials.",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to revoke credentials against.",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(`Listing previously revoked tokens for ${args.name}...`);
logger.log(
await listRevokedPubSubBrokerTokens(
config,
accountId,
args.namespace,
args.name
)
);
sendMetricsEvent("list pubsub broker revoked credentials", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.command(
"public-keys <name>",
"Show the public keys used for verifying on-publish hooks and credentials for a Broker.",
(yargs) => {
return yargs.positional("name", {
describe: "The name of the Broker to revoke credentials against.",
type: "string",
demandOption: true
}).option("namespace", {
describe: "The Namespace the Broker is associated with.",
type: "string",
alias: "ns",
demandOption: true
}).epilogue(pubSubBetaWarning);
},
async (args) => {
const config = readConfig(args);
const accountId = await requireAuth(config);
logger.log(
await getPubSubBrokerPublicKeys(
config,
accountId,
args.namespace,
args.name
)
);
sendMetricsEvent("list pubsub broker public-keys", {
sendMetrics: config.send_metrics
});
}
);
brokersYargs.epilogue(pubSubBetaWarning);
return brokersYargs;
}).epilogue(pubSubBetaWarning);
}
var init_pubsub_commands = __esm({
"src/pubsub/pubsub-commands.ts"() {
init_import_meta_url();
init_config2();
init_dialogs();
init_errors();
init_logger();
init_metrics();
init_parse();
init_user2();
init_pubsub();
__name(pubSubCommands, "pubSubCommands");
}
});
// src/queues/cli/commands/index.ts
var queuesNamespace;
var init_commands6 = __esm({
"src/queues/cli/commands/index.ts"() {
init_import_meta_url();
init_create_command();
queuesNamespace = createNamespace({
metadata: {
description: "\u{1F4EC} Manage Workers Queues",
owner: "Product: Queues",
status: "stable"
}
});
}
});
// src/queues/cli/commands/consumer/index.ts
var queuesConsumerNamespace;
var init_consumer = __esm({
"src/queues/cli/commands/consumer/index.ts"() {
init_import_meta_url();
init_create_command();
queuesConsumerNamespace = createNamespace({
metadata: {
description: "Configure queue consumers",
owner: "Product: Queues",
status: "stable"
}
});
}
});
// src/queues/cli/commands/consumer/http-pull/index.ts
var queuesConsumerHttpNamespace;
var init_http_pull = __esm({
"src/queues/cli/commands/consumer/http-pull/index.ts"() {
init_import_meta_url();
init_create_command();
queuesConsumerHttpNamespace = createNamespace({
metadata: {
description: "Configure Queue HTTP Pull Consumers",
owner: "Product: Queues",
status: "stable"
}
});
}
});
// src/queues/cli/commands/consumer/http-pull/add.ts
var queuesConsumerHttpAddCommand;
var init_add = __esm({
"src/queues/cli/commands/consumer/http-pull/add.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client2();
queuesConsumerHttpAddCommand = createCommand({
metadata: {
description: "Add a Queue HTTP Pull Consumer",
owner: "Product: Queues",
status: "stable"
},
args: {
"queue-name": {
type: "string",
demandOption: true,
description: "Name of the queue for the consumer"
},
"batch-size": {
type: "number",
description: "Maximum number of messages per batch"
},
"message-retries": {
type: "number",
description: "Maximum number of retries for each message"
},
"dead-letter-queue": {
type: "string",
description: "Queue to send messages that failed to be consumed"
},
"visibility-timeout-secs": {
type: "number",
description: "The number of seconds a message will wait for an acknowledgement before being returned to the queue."
},
"retry-delay-secs": {
type: "number",
description: "The number of seconds to wait before retrying a message"
}
},
positionalArgs: ["queue-name"],
async handler(args, { config }) {
if (Array.isArray(args.retryDelaySecs)) {
throw new CommandLineArgsError(
`Cannot specify --retry-delay-secs multiple times`
);
}
const body = {
type: "http_pull",
settings: {
batch_size: args.batchSize,
max_retries: args.messageRetries,
visibility_timeout_ms: args.visibilityTimeoutSecs ? args.visibilityTimeoutSecs * 1e3 : void 0,
retry_delay: args.retryDelaySecs
},
dead_letter_queue: args.deadLetterQueue
};
logger.log(`Adding consumer to queue ${args.queueName}.`);
await postConsumer(config, args.queueName, body);
logger.log(`Added consumer to queue ${args.queueName}.`);
}
});
}
});
// src/queues/cli/commands/consumer/http-pull/remove.ts
var queuesConsumerHttpRemoveCommand;
var init_remove = __esm({
"src/queues/cli/commands/consumer/http-pull/remove.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client2();
queuesConsumerHttpRemoveCommand = createCommand({
metadata: {
description: "Remove a Queue HTTP Pull Consumer",
owner: "Product: Queues",
status: "stable"
},
args: {
"queue-name": {
type: "string",
demandOption: true,
description: "Name of the queue for the consumer"
}
},
positionalArgs: ["queue-name"],
async handler(args, { config }) {
logger.log(`Removing consumer from queue ${args.queueName}.`);
await deletePullConsumer(config, args.queueName);
logger.log(`Removed consumer from queue ${args.queueName}.`);
}
});
}
});
// src/queues/cli/commands/consumer/worker/index.ts
var queuesConsumerWorkerNamespace;
var init_worker = __esm({
"src/queues/cli/commands/consumer/worker/index.ts"() {
init_import_meta_url();
init_create_command();
queuesConsumerWorkerNamespace = createNamespace({
metadata: {
description: "Configure Queue Worker Consumers",
owner: "Product: Queues",
status: "stable"
}
});
}
});
// src/queues/cli/commands/consumer/worker/add.ts
var queuesConsumerAddCommand;
var init_add2 = __esm({
"src/queues/cli/commands/consumer/worker/add.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client2();
queuesConsumerAddCommand = createCommand({
metadata: {
description: "Add a Queue Worker Consumer",
owner: "Product: Queues",
status: "stable"
},
args: {
"queue-name": {
type: "string",
demandOption: true,
description: "Name of the queue to configure"
},
"script-name": {
type: "string",
demandOption: true,
description: "Name of the consumer script"
},
"batch-size": {
type: "number",
describe: "Maximum number of messages per batch"
},
"batch-timeout": {
type: "number",
describe: "Maximum number of seconds to wait to fill a batch with messages"
},
"message-retries": {
type: "number",
describe: "Maximum number of retries for each message"
},
"dead-letter-queue": {
type: "string",
describe: "Queue to send messages that failed to be consumed"
},
"max-concurrency": {
type: "number",
describe: "The maximum number of concurrent consumer Worker invocations. Must be a positive integer"
},
"retry-delay-secs": {
type: "number",
describe: "The number of seconds to wait before retrying a message"
}
},
positionalArgs: ["queue-name", "script-name"],
async handler(args, { config }) {
if (Array.isArray(args.retryDelaySecs)) {
throw new CommandLineArgsError(
`Cannot specify --retry-delay-secs multiple times`
);
}
const body = {
script_name: args.scriptName,
// TODO(soon) is this still the correct usage of the environment?
environment_name: args.env ?? "",
// API expects empty string as default
type: "worker",
settings: {
batch_size: args.batchSize,
max_retries: args.messageRetries,
max_wait_time_ms: args.batchTimeout !== void 0 ? 1e3 * args.batchTimeout : void 0,
max_concurrency: args.maxConcurrency,
retry_delay: args.retryDelaySecs
},
dead_letter_queue: args.deadLetterQueue
};
logger.log(`Adding consumer to queue ${args.queueName}.`);
await postConsumer(config, args.queueName, body);
logger.log(`Added consumer to queue ${args.queueName}.`);
}
});
}
});
// src/queues/cli/commands/consumer/worker/remove.ts
var queuesConsumerRemoveCommand;
var init_remove2 = __esm({
"src/queues/cli/commands/consumer/worker/remove.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client2();
queuesConsumerRemoveCommand = createCommand({
metadata: {
description: "Remove a Queue Worker Consumer",
owner: "Product: Queues",
status: "stable"
},
args: {
"queue-name": {
type: "string",
demandOption: true,
description: "Name of the queue to configure"
},
"script-name": {
type: "string",
demandOption: true,
description: "Name of the consumer script"
}
},
positionalArgs: ["queue-name", "script-name"],
async handler(args, { config }) {
logger.log(`Removing consumer from queue ${args.queueName}.`);
await deleteWorkerConsumer(
config,
args.queueName,
args.scriptName,
args.env
);
logger.log(`Removed consumer from queue ${args.queueName}.`);
}
});
}
});
// src/queues/constants.ts
var INVALID_CONSUMER_SETTINGS_ERROR, INVALID_QUEUE_SETTINGS_ERROR, MIN_DELIVERY_DELAY_SECS, MAX_DELIVERY_DELAY_SECS, MIN_MESSAGE_RETENTION_PERIOD_SECS, MAX_MESSAGE_RETENTION_PERIOD_SECS;
var init_constants16 = __esm({
"src/queues/constants.ts"() {
init_import_meta_url();
INVALID_CONSUMER_SETTINGS_ERROR = 100127;
INVALID_QUEUE_SETTINGS_ERROR = 100128;
MIN_DELIVERY_DELAY_SECS = 0;
MAX_DELIVERY_DELAY_SECS = 43200;
MIN_MESSAGE_RETENTION_PERIOD_SECS = 60;
MAX_MESSAGE_RETENTION_PERIOD_SECS = 1209600;
}
});
// src/queues/utils.ts
function handleFetchError(e7) {
if (e7.code === INVALID_CONSUMER_SETTINGS_ERROR) {
throw new UserError(`The specified consumer settings are invalid.`);
}
if (e7.code === INVALID_QUEUE_SETTINGS_ERROR) {
throw new UserError(`The specified queue settings are invalid.`);
}
throw e7;
}
var init_utils11 = __esm({
"src/queues/utils.ts"() {
init_import_meta_url();
init_errors();
init_constants16();
__name(handleFetchError, "handleFetchError");
}
});
// src/queues/cli/commands/create.ts
function createBody(args) {
const body = {
queue_name: args.name
};
body.settings = {};
if (args.deliveryDelaySecs != void 0) {
if (args.deliveryDelaySecs < MIN_DELIVERY_DELAY_SECS || args.deliveryDelaySecs > MAX_DELIVERY_DELAY_SECS) {
throw new CommandLineArgsError(
`Invalid --delivery-delay-secs value: ${args.deliveryDelaySecs}. Must be between ${MIN_DELIVERY_DELAY_SECS} and ${MAX_DELIVERY_DELAY_SECS}`
);
}
body.settings.delivery_delay = args.deliveryDelaySecs;
}
if (args.messageRetentionPeriodSecs != void 0) {
if (args.messageRetentionPeriodSecs < MIN_MESSAGE_RETENTION_PERIOD_SECS || args.messageRetentionPeriodSecs > MAX_MESSAGE_RETENTION_PERIOD_SECS) {
throw new CommandLineArgsError(
`Invalid --message-retention-period-secs value: ${args.messageRetentionPeriodSecs}. Must be between ${MIN_MESSAGE_RETENTION_PERIOD_SECS} and ${MAX_MESSAGE_RETENTION_PERIOD_SECS}`
);
}
body.settings.message_retention_period = args.messageRetentionPeriodSecs;
}
if (Object.keys(body.settings).length === 0) {
body.settings = void 0;
}
return body;
}
var queuesCreateCommand;
var init_create6 = __esm({
"src/queues/cli/commands/create.ts"() {
init_import_meta_url();
init_esm2();
init_config2();
init_create_command();
init_errors();
init_logger();
init_getValidBindingName();
init_client2();
init_constants16();
init_utils11();
queuesCreateCommand = createCommand({
metadata: {
description: "Create a queue",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
},
"delivery-delay-secs": {
type: "number",
describe: "How long a published message should be delayed for, in seconds. Must be between 0 and 42300",
default: 0
},
"message-retention-period-secs": {
type: "number",
describe: "How long to retain a message in the queue, in seconds. Must be between 60 and 1209600",
default: 345600
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const body = createBody(args);
try {
logger.log(`\u{1F300} Creating queue '${args.name}'`);
await createQueue(config, body);
logger.log(esm_default2`
✅ Created queue '${args.name}'
Configure your Worker to send messages to this queue:
${formatConfigSnippet(
{
queues: {
producers: [
{
queue: args.name,
binding: getValidBindingName(args.name, "queue")
}
]
}
},
config.configPath
)}
Configure your Worker to consume messages from this queue:
${formatConfigSnippet(
{
queues: {
consumers: [
{
queue: args.name
}
]
}
},
config.configPath
)}`);
} catch (e7) {
handleFetchError(e7);
}
}
});
__name(createBody, "createBody");
}
});
// src/queues/cli/commands/delete.ts
var queuesDeleteCommand;
var init_delete6 = __esm({
"src/queues/cli/commands/delete.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client2();
queuesDeleteCommand = createCommand({
metadata: {
description: "Delete a queue",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
logger.log(`Deleting queue ${args.name}.`);
await deleteQueue(config, args.name);
logger.log(`Deleted queue ${args.name}.`);
}
});
}
});
// src/queues/cli/commands/info.ts
var queuesInfoCommand;
var init_info3 = __esm({
"src/queues/cli/commands/info.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_client2();
queuesInfoCommand = createCommand({
metadata: {
description: "Get queue information",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const queue = await getQueue(config, args.name);
const accountId = await requireAuth(config);
logger.log(`Queue Name: ${queue.queue_name}`);
logger.log(`Queue ID: ${queue.queue_id}`);
logger.log(`Created On: ${queue.created_on}`);
logger.log(`Last Modified: ${queue.modified_on}`);
logger.log(`Number of Producers: ${queue.producers_total_count}`);
if (queue.producers_total_count > 0) {
logger.log(
`Producers:${queue.producers.map((p6) => p6.type === "r2_bucket" ? ` ${p6.type}:${p6.bucket_name}` : ` ${p6.type}:${p6.script}`).toString()}`
);
}
logger.log(`Number of Consumers: ${queue.consumers_total_count}`);
if (queue.consumers_total_count > 0) {
logger.log(
`Consumers: ${queue.consumers.map((c6) => {
if (c6.type === "r2_bucket") {
return `${c6.type}:${c6.bucket_name}`;
}
if (c6.type === "http_pull") {
return `HTTP Pull Consumer.
Pull messages using:
curl "https://api.cloudflare.com/client/v4/accounts/${accountId || "<add your account id here>"}/queues/${queue.queue_id || "<add your queue id here>"}/messages/pull" \\
--header "Authorization: Bearer <add your api key here>" \\
--header "Content-Type: application/json" \\
--data '{ "visibility_timeout": 10000, "batch_size": 2 }'`;
}
return `${c6.type}:${c6.script}`;
}).toString()}`
);
}
}
});
}
});
// src/queues/cli/commands/list.ts
var queuesListCommand;
var init_list6 = __esm({
"src/queues/cli/commands/list.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client2();
queuesListCommand = createCommand({
metadata: {
description: "List queues",
status: "stable",
owner: "Product: Queues"
},
args: {
page: {
type: "number",
describe: "Page number for pagination"
}
},
async handler(args, { config }) {
const queues = await listQueues(config, args.page);
logger.table(
queues.map((queue) => ({
id: queue.queue_id,
name: queue.queue_name,
created_on: queue.created_on,
modified_on: queue.modified_on,
producers: queue.producers_total_count.toString(),
consumers: queue.consumers_total_count.toString()
}))
);
}
});
}
});
// src/queues/cli/commands/pause-resume.ts
async function toggleDeliveryPaused(args, config, paused) {
const body = {
queue_name: args.name,
settings: {
delivery_paused: paused
}
};
try {
const currentQueue = await getQueue(config, args.name);
let msg = paused ? "Pausing" : "Resuming";
logger.log(`${msg} message delivery for queue ${args.name}.`);
await updateQueue(config, body, currentQueue.queue_id);
msg = paused ? "Paused" : "Resumed";
logger.log(`${msg} message delivery for queue ${args.name}.`);
} catch (e7) {
handleFetchError(e7);
}
}
var queuesPauseCommand, queuesResumeCommand;
var init_pause_resume = __esm({
"src/queues/cli/commands/pause-resume.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client2();
init_utils11();
queuesPauseCommand = createCommand({
metadata: {
description: "Pause message delivery for a queue",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
await toggleDeliveryPaused(args, config, true);
}
});
queuesResumeCommand = createCommand({
metadata: {
description: "Resume message delivery for a queue",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
await toggleDeliveryPaused(args, config, false);
}
});
__name(toggleDeliveryPaused, "toggleDeliveryPaused");
}
});
// src/queues/cli/commands/purge.ts
var queuesPurgeCommand;
var init_purge = __esm({
"src/queues/cli/commands/purge.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_errors();
init_is_interactive();
init_logger();
init_client2();
queuesPurgeCommand = createCommand({
metadata: {
description: "Purge messages from a queue",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
},
force: {
describe: "Skip the confirmation dialog and forcefully purge the Queue",
type: "boolean"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
if (!args.force && !isInteractive2()) {
throw new FatalError(
"The --force flag is required to purge a Queue in non-interactive mode"
);
}
if (!args.force && isInteractive2()) {
const result = await prompt(
`This operation will permanently delete all the messages in Queue ${args.name}. Type ${args.name} to proceed.`
);
if (result !== args.name) {
throw new FatalError(
"Incorrect queue name provided. Skipping purge operation"
);
}
}
await purgeQueue(config, args.name);
logger.log(`Purged Queue '${args.name}'`);
}
});
}
});
// src/queues/cli/commands/subscription/index.ts
var queuesSubscriptionNamespace;
var init_subscription = __esm({
"src/queues/cli/commands/subscription/index.ts"() {
init_import_meta_url();
init_create_command();
queuesSubscriptionNamespace = createNamespace({
metadata: {
description: "Manage event subscriptions for a queue",
owner: "Product: Queues",
status: "stable"
}
});
}
});
// src/queues/subscription-types.ts
var EventSourceType, EVENT_SOURCE_TYPES;
var init_subscription_types = __esm({
"src/queues/subscription-types.ts"() {
init_import_meta_url();
EventSourceType = /* @__PURE__ */ ((EventSourceType2) => {
EventSourceType2["KV"] = "kv";
EventSourceType2["R2"] = "r2";
EventSourceType2["SUPER_SLURPER"] = "superSlurper";
EventSourceType2["VECTORIZE"] = "vectorize";
EventSourceType2["WORKERS_AI_MODEL"] = "workersAi.model";
EventSourceType2["WORKERS_BUILDS_WORKER"] = "workersBuilds.worker";
EventSourceType2["WORKFLOWS_WORKFLOW"] = "workflows.workflow";
return EventSourceType2;
})(EventSourceType || {});
EVENT_SOURCE_TYPES = Object.values(EventSourceType);
}
});
// src/queues/cli/commands/subscription/create.ts
function parseSourceArgument(source, args) {
switch (source) {
case "kv" /* KV */:
return { type: "kv" /* KV */ };
case "r2" /* R2 */:
return { type: "r2" /* R2 */ };
case "superSlurper" /* SUPER_SLURPER */:
return { type: "superSlurper" /* SUPER_SLURPER */ };
case "vectorize" /* VECTORIZE */:
return { type: "vectorize" /* VECTORIZE */ };
case "workersAi.model" /* WORKERS_AI_MODEL */:
if (!args.modelName) {
throw new UserError(
`--model-name is required when using source '${"workersAi.model" /* WORKERS_AI_MODEL */}'`
);
}
return {
type: "workersAi.model" /* WORKERS_AI_MODEL */,
model_name: args.modelName
};
case "workersBuilds.worker" /* WORKERS_BUILDS_WORKER */:
if (!args.workerName) {
throw new UserError(
`--worker-name is required when using source '${"workersBuilds.worker" /* WORKERS_BUILDS_WORKER */}'`
);
}
return {
type: "workersBuilds.worker" /* WORKERS_BUILDS_WORKER */,
worker_name: args.workerName
};
case "workflows.workflow" /* WORKFLOWS_WORKFLOW */:
if (!args.workflowName) {
throw new UserError(
`--workflow-name is required when using source '${"workflows.workflow" /* WORKFLOWS_WORKFLOW */}'`
);
}
return {
type: "workflows.workflow" /* WORKFLOWS_WORKFLOW */,
workflow_name: args.workflowName
};
default:
throw new UserError(
`Unknown source type: ${source}. Supported sources: ${EVENT_SOURCE_TYPES.join(", ")}`
);
}
}
var queuesSubscriptionCreateCommand;
var init_create7 = __esm({
"src/queues/cli/commands/subscription/create.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client2();
init_subscription_types();
__name(parseSourceArgument, "parseSourceArgument");
queuesSubscriptionCreateCommand = createCommand({
metadata: {
description: "Create a new event subscription for a queue",
owner: "Product: Queues",
status: "stable"
},
positionalArgs: ["queue"],
args: {
queue: {
describe: "The name of the queue to create the subscription for",
type: "string",
demandOption: true
},
source: {
describe: "The event source type",
type: "string",
demandOption: true,
choices: EVENT_SOURCE_TYPES
},
events: {
describe: "Comma-separated list of event types to subscribe to",
type: "string",
demandOption: true
},
name: {
describe: "Name for the subscription (auto-generated if not provided)",
type: "string"
},
enabled: {
describe: "Whether the subscription should be active",
type: "boolean",
default: true
},
"model-name": {
describe: "Workers AI model name (required for workersAi.model source)",
type: "string"
},
"worker-name": {
describe: "Worker name (required for workersBuilds.worker source)",
type: "string"
},
"workflow-name": {
describe: "Workflow name (required for workflows.workflow source)",
type: "string"
}
},
async handler(args, { config }) {
const source = parseSourceArgument(args.source, {
modelName: args.modelName,
workerName: args.workerName,
workflowName: args.workflowName
});
const events6 = args.events.split(",").map((event) => event.trim()).filter(Boolean);
if (events6.length === 0) {
throw new UserError(
"No events specified. Use --events to provide a comma-separated list of event types to subscribe to. For a complete list of sources and corresponding events, please refer to: https://developers.cloudflare.com/queues/event-subscriptions/events-schemas/"
);
}
const request4 = {
name: args.name || `${args.queue} ${args.source}`,
enabled: args.enabled,
source,
destination: {
type: "queues.queue",
queue_id: ""
},
events: events6
};
logger.log(`Creating event subscription for queue '${args.queue}'...`);
const subscription = await createEventSubscription(
config,
args.queue,
request4
);
logger.log(
`\u2728 Successfully created event subscription '${subscription.name}' with id '${subscription.id}'.`
);
}
});
}
});
// src/queues/cli/commands/subscription/delete.ts
var queuesSubscriptionDeleteCommand;
var init_delete7 = __esm({
"src/queues/cli/commands/subscription/delete.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_logger();
init_client2();
queuesSubscriptionDeleteCommand = createCommand({
metadata: {
description: "Delete an event subscription from a queue",
owner: "Product: Queues",
status: "stable"
},
positionalArgs: ["queue"],
args: {
queue: {
describe: "The name of the queue",
type: "string",
demandOption: true
},
id: {
describe: "The ID of the subscription to delete",
type: "string",
demandOption: true
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const subscription = await getEventSubscriptionForQueue(
config,
args.queue,
args.id
);
if (!args.force) {
const confirmedDelete = await confirm(
`Are you sure you want to delete the event subscription '${subscription.name}' (${args.id})?`
);
if (!confirmedDelete) {
logger.log("Delete cancelled.");
return;
}
}
await deleteEventSubscription(config, args.id);
logger.log(
`\u2728 Successfully deleted event subscription '${subscription.name}' with id '${subscription.id}'.`
);
}
});
}
});
// src/queues/cli/commands/subscription/utils.ts
function getSourceType(source) {
return source.type;
}
function getSourceResource(source) {
switch (source.type) {
case "workersAi.model" /* WORKERS_AI_MODEL */:
return source.model_name;
case "workersBuilds.worker" /* WORKERS_BUILDS_WORKER */:
return source.worker_name;
case "workflows.workflow" /* WORKFLOWS_WORKFLOW */:
return source.workflow_name;
default:
return "";
}
}
var init_utils12 = __esm({
"src/queues/cli/commands/subscription/utils.ts"() {
init_import_meta_url();
init_subscription_types();
__name(getSourceType, "getSourceType");
__name(getSourceResource, "getSourceResource");
}
});
// src/queues/cli/commands/subscription/get.ts
var queuesSubscriptionGetCommand;
var init_get3 = __esm({
"src/queues/cli/commands/subscription/get.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_render_labelled_values();
init_client2();
init_utils12();
queuesSubscriptionGetCommand = createCommand({
metadata: {
description: "Get details about a specific event subscription",
owner: "Product: Queues",
status: "stable"
},
positionalArgs: ["queue"],
args: {
queue: {
describe: "The name of the queue",
type: "string",
demandOption: true
},
id: {
describe: "The ID of the subscription to retrieve",
type: "string",
demandOption: true
},
json: {
describe: "Output in JSON format",
type: "boolean",
default: false
}
},
async handler(args, { config }) {
const subscription = await getEventSubscriptionForQueue(
config,
args.queue,
args.id
);
if (args.json) {
logger.log(JSON.stringify(subscription, null, 2));
return;
}
const resource = getSourceResource(subscription.source);
const output = {
ID: subscription.id,
Name: subscription.name,
Source: getSourceType(subscription.source),
...resource && { Resource: resource },
"Queue ID": subscription.destination.queue_id,
Events: subscription.events.join(", "),
Enabled: subscription.enabled ? "Yes" : "No",
"Created At": new Date(subscription.created_at).toLocaleString(),
"Modified At": new Date(subscription.modified_at).toLocaleString()
};
logger.log(formatLabelledValues(output));
}
});
}
});
// src/queues/cli/commands/subscription/list.ts
var queuesSubscriptionListCommand;
var init_list7 = __esm({
"src/queues/cli/commands/subscription/list.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client2();
init_utils12();
queuesSubscriptionListCommand = createCommand({
metadata: {
description: "List event subscriptions for a queue",
owner: "Product: Queues",
status: "stable"
},
positionalArgs: ["queue"],
args: {
queue: {
describe: "The name of the queue to list subscriptions for",
type: "string",
demandOption: true
},
page: {
describe: "Page number for pagination",
type: "number",
default: 1
},
"per-page": {
describe: "Number of subscriptions per page",
type: "number",
default: 20
},
json: {
describe: "Output in JSON format",
type: "boolean",
default: false
}
},
async handler(args, { config }) {
const subscriptions = await listEventSubscriptions(config, args.queue, {
page: args.page,
per_page: args.perPage
});
if (args.json) {
logger.log(JSON.stringify(subscriptions, null, 2));
return;
}
if (!subscriptions || subscriptions.length === 0) {
logger.log(`No event subscriptions found for queue '${args.queue}'.`);
return;
}
logger.log(`Event subscriptions for queue '${args.queue}':`);
logger.table(
subscriptions.map((subscription) => ({
ID: subscription.id,
Name: subscription.name,
Source: getSourceType(subscription.source),
Events: subscription.events.join(", "),
Resource: getSourceResource(subscription.source),
Enabled: subscription.enabled ? "Yes" : "No"
}))
);
}
});
}
});
// src/queues/cli/commands/subscription/update.ts
var queuesSubscriptionUpdateCommand;
var init_update3 = __esm({
"src/queues/cli/commands/subscription/update.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client2();
queuesSubscriptionUpdateCommand = createCommand({
metadata: {
description: "Update an existing event subscription",
owner: "Product: Queues",
status: "stable"
},
positionalArgs: ["queue"],
args: {
queue: {
describe: "The name of the queue",
type: "string",
demandOption: true
},
id: {
describe: "The ID of the subscription to update",
type: "string",
demandOption: true
},
name: {
describe: "New name for the subscription",
type: "string"
},
events: {
describe: "Comma-separated list of event types to subscribe to",
type: "string"
},
enabled: {
describe: "Whether the subscription should be active",
type: "boolean"
},
json: {
describe: "Output in JSON format",
type: "boolean",
default: false
}
},
async handler(args, { config }) {
const updateRequest = {};
if (args.name !== void 0) {
updateRequest.name = args.name;
}
if (args.events !== void 0) {
const events6 = args.events.split(",").map((event) => event.trim()).filter(Boolean);
if (events6.length === 0) {
throw new UserError(
"No events specified. Use --events to provide a comma-separated list of event types to subscribe to. For a complete list of sources and corresponding events, please refer to: https://developers.cloudflare.com/queues/event-subscriptions/events-schemas/"
);
}
updateRequest.events = events6;
}
if (args.enabled !== void 0) {
updateRequest.enabled = args.enabled;
}
if (Object.keys(updateRequest).length === 0) {
throw new UserError(
"No fields specified for update. Provide at least one of --name, --events, or --enabled to update the subscription."
);
}
await getEventSubscriptionForQueue(config, args.queue, args.id);
logger.log("Updating event subscription...");
const updatedSubscription = await updateEventSubscription(
config,
args.id,
updateRequest
);
if (args.json) {
logger.log(JSON.stringify(updatedSubscription, null, 2));
return;
}
logger.log(
`\u2728 Successfully updated event subscription '${updatedSubscription.name}' with id '${args.id}'.`
);
}
});
}
});
// src/queues/cli/commands/update.ts
function updateBody(args, currentSettings) {
const body = {
queue_name: args.name
};
if (Array.isArray(args.deliveryDelaySecs)) {
throw new CommandLineArgsError(
"Cannot specify --delivery-delay-secs multiple times"
);
}
if (Array.isArray(args.messageRetentionPeriodSecs)) {
throw new CommandLineArgsError(
"Cannot specify --message-retention-period-secs multiple times"
);
}
body.settings = {};
if (args.deliveryDelaySecs != void 0) {
if (args.deliveryDelaySecs < MIN_DELIVERY_DELAY_SECS || args.deliveryDelaySecs > MAX_DELIVERY_DELAY_SECS) {
throw new CommandLineArgsError(
`Invalid --delivery-delay-secs value: ${args.deliveryDelaySecs}. Must be between ${MIN_DELIVERY_DELAY_SECS} and ${MAX_DELIVERY_DELAY_SECS}`
);
}
body.settings.delivery_delay = args.deliveryDelaySecs;
} else if (currentSettings?.delivery_delay != void 0) {
body.settings.delivery_delay = currentSettings.delivery_delay;
}
if (args.messageRetentionPeriodSecs != void 0) {
if (args.messageRetentionPeriodSecs < MIN_MESSAGE_RETENTION_PERIOD_SECS || args.messageRetentionPeriodSecs > MAX_MESSAGE_RETENTION_PERIOD_SECS) {
throw new CommandLineArgsError(
`Invalid --message-retention-period-secs value: ${args.messageRetentionPeriodSecs}. Must be between ${MIN_MESSAGE_RETENTION_PERIOD_SECS} and ${MAX_MESSAGE_RETENTION_PERIOD_SECS}`
);
}
body.settings.message_retention_period = args.messageRetentionPeriodSecs;
} else if (currentSettings?.message_retention_period != void 0) {
body.settings.message_retention_period = currentSettings.message_retention_period;
}
if (Object.keys(body.settings).length === 0) {
body.settings = void 0;
}
return body;
}
var queuesUpdateCommand;
var init_update4 = __esm({
"src/queues/cli/commands/update.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client2();
init_constants16();
init_utils11();
queuesUpdateCommand = createCommand({
metadata: {
description: "Update a queue",
owner: "Product: Queues",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the queue"
},
"delivery-delay-secs": {
type: "number",
describe: "How long a published message should be delayed for, in seconds. Must be between 0 and 42300"
},
"message-retention-period-secs": {
type: "number",
describe: "How long to retain a message in the queue, in seconds. Must be between 60 and 1209600"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
try {
const currentQueue = await getQueue(config, args.name);
const body = updateBody(args, currentQueue.settings);
logger.log(`Updating queue ${args.name}.`);
await updateQueue(config, body, currentQueue.queue_id);
logger.log(`Updated queue ${args.name}.`);
} catch (e7) {
handleFetchError(e7);
}
}
});
__name(updateBody, "updateBody");
}
});
// src/r2/index.ts
var r2Namespace;
var init_r2 = __esm({
"src/r2/index.ts"() {
init_import_meta_url();
init_create_command();
r2Namespace = createNamespace({
metadata: {
description: "\u{1F4E6} Manage R2 buckets & objects",
status: "stable",
owner: "Product: R2"
}
});
}
});
// src/r2/constants.ts
var MAX_UPLOAD_SIZE, LOCATION_CHOICES2;
var init_constants17 = __esm({
"src/r2/constants.ts"() {
init_import_meta_url();
MAX_UPLOAD_SIZE = 300 * 1024 * 1024;
LOCATION_CHOICES2 = ["weur", "eeur", "apac", "wnam", "enam", "oc"];
}
});
// src/r2/bucket.ts
var r2BucketNamespace, r2BucketCreateCommand, r2BucketUpdateNamespace, r2BucketUpdateStorageClassCommand, r2BucketListCommand, r2BucketInfoCommand, r2BucketDeleteCommand;
var init_bucket = __esm({
"src/r2/bucket.ts"() {
init_import_meta_url();
init_esm2();
init_config2();
init_create_command();
init_errors();
init_logger();
init_metrics();
init_user2();
init_getValidBindingName();
init_render_labelled_values();
init_constants17();
init_helpers();
r2BucketNamespace = createNamespace({
metadata: {
description: "Manage R2 buckets",
status: "stable",
owner: "Product: R2"
}
});
r2BucketCreateCommand = createCommand({
metadata: {
description: "Create a new R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["name"],
args: {
name: {
describe: "The name of the new bucket",
type: "string",
demandOption: true
},
location: {
describe: "The optional location hint that determines geographic placement of the R2 bucket",
choices: LOCATION_CHOICES2,
requiresArg: true,
type: "string"
},
"storage-class": {
describe: "The default storage class for objects uploaded to this bucket",
alias: "s",
requiresArg: false,
type: "string"
},
jurisdiction: {
describe: "The jurisdiction where the new bucket will be created",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { name: name2, location, storageClass, jurisdiction } = args;
if (!isValidR2BucketName(name2)) {
throw new UserError(
`The bucket name "${name2}" is invalid. ${bucketFormatMessage}`
);
}
if (jurisdiction && location) {
throw new UserError(
"Provide either a jurisdiction or location hint - not both."
);
}
let fullBucketName = `${name2}`;
if (jurisdiction !== void 0) {
fullBucketName += ` (${jurisdiction})`;
}
logger.log(`Creating bucket '${fullBucketName}'...`);
await createR2Bucket(
config,
accountId,
name2,
location,
jurisdiction,
storageClass
);
logger.log(esm_default2`
✅ Created bucket '${fullBucketName}' with${location ? ` location hint ${location} and` : ``} default storage class of ${storageClass ? storageClass : `Standard`}.`);
await updateConfigFile(
(bindingName) => ({
r2_buckets: [
{
bucket_name: args.name,
binding: getValidBindingName(bindingName ?? args.name, "r2")
}
]
}),
config.configPath,
args.env
);
sendMetricsEvent("create r2 bucket", {
sendMetrics: config.send_metrics
});
}
});
r2BucketUpdateNamespace = createNamespace({
metadata: {
description: "Update bucket state",
status: "stable",
owner: "Product: R2"
}
});
r2BucketUpdateStorageClassCommand = createCommand({
metadata: {
description: "Update the default storage class of an existing R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["name"],
args: {
name: {
describe: "The name of the existing bucket",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction of the bucket to be updated",
alias: "J",
requiresArg: true,
type: "string"
},
"storage-class": {
describe: "The new default storage class for this bucket",
alias: "s",
demandOption: true,
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
let fullBucketName = `${args.name}`;
if (args.jurisdiction !== void 0) {
fullBucketName += ` (${args.jurisdiction})`;
}
logger.log(
`Updating bucket ${fullBucketName} to ${args.storageClass} default storage class.`
);
await updateR2BucketStorageClass(
config,
accountId,
args.name,
args.storageClass,
args.jurisdiction
);
logger.log(
`Updated bucket ${fullBucketName} to ${args.storageClass} default storage class.`
);
}
});
r2BucketListCommand = createCommand({
metadata: {
description: "List R2 buckets",
status: "stable",
owner: "Product: R2"
},
args: {
jurisdiction: {
describe: "The jurisdiction to list",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
logger.log(`Listing buckets...`);
const buckets = await listR2Buckets(config, accountId, args.jurisdiction);
const tableOutput = tablefromR2BucketsListResponse(buckets);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
});
r2BucketInfoCommand = createCommand({
metadata: {
description: "Get information about an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the bucket to retrieve info for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
json: {
describe: "Return the bucket information as JSON",
type: "boolean",
default: false
}
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
if (!args.json) {
logger.log(`Getting info for '${args.bucket}'...`);
}
const bucketInfo = await getR2Bucket(
config,
accountId,
args.bucket,
args.jurisdiction
);
const bucketMetrics = await getR2BucketMetrics(
config,
accountId,
args.bucket,
args.jurisdiction
);
const output = {
name: bucketInfo.name,
created: bucketInfo.creation_date,
location: bucketInfo.location || "(unknown)",
default_storage_class: bucketInfo.storage_class || "(unknown)",
object_count: bucketMetrics.objectCount.toLocaleString(),
bucket_size: bucketMetrics.totalSize
};
if (args.json) {
logger.json(output);
} else {
logger.log(formatLabelledValues(output));
}
}
});
r2BucketDeleteCommand = createCommand({
metadata: {
description: "Delete an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the bucket to delete",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
let fullBucketName = `${args.bucket}`;
if (args.jurisdiction !== void 0) {
fullBucketName += ` (${args.jurisdiction})`;
}
logger.log(`Deleting bucket ${fullBucketName}.`);
await deleteR2Bucket(config, accountId, args.bucket, args.jurisdiction);
logger.log(`Deleted bucket ${fullBucketName}.`);
sendMetricsEvent("delete r2 bucket", {
sendMetrics: config.send_metrics
});
}
});
}
});
// src/r2/catalog.ts
var r2BucketCatalogNamespace, r2BucketCatalogEnableCommand, r2BucketCatalogDisableCommand, r2BucketCatalogGetCommand;
var init_catalog = __esm({
"src/r2/catalog.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_misc_variables();
init_logger();
init_parse();
init_user2();
init_render_labelled_values();
init_helpers();
r2BucketCatalogNamespace = createNamespace({
metadata: {
description: "Manage the data catalog for your R2 buckets - provides an Iceberg REST interface for query engines like Spark and PyIceberg",
status: "open-beta",
owner: "Product: R2 Data Catalog"
}
});
r2BucketCatalogEnableCommand = createCommand({
metadata: {
description: "Enable the data catalog on an R2 bucket",
status: "open-beta",
owner: "Product: R2 Data Catalog"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the bucket to enable",
type: "string",
demandOption: true
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const response = await enableR2Catalog(config, accountId, args.bucket);
let catalogHost;
const env6 = getCloudflareApiEnvironmentFromEnv();
const path72 = response.name.replace("_", "/");
if (env6 === "staging") {
catalogHost = `https://catalog-staging.cloudflarestorage.com/${path72}`;
} else {
catalogHost = `https://catalog.cloudflarestorage.com/${path72}`;
}
logger.log(
`\u2728 Successfully enabled data catalog on bucket '${args.bucket}'.
Catalog URI: '${catalogHost}'
Warehouse: '${response.name}'
Use this Catalog URI with Iceberg-compatible query engines (Spark, PyIceberg etc.) to query data as tables.
Note: You will need a Cloudflare API token with 'R2 Data Catalog' permission to authenticate your client with this catalog.
For more details, refer to: https://developers.cloudflare.com/r2/api/s3/tokens/`
);
}
});
r2BucketCatalogDisableCommand = createCommand({
metadata: {
description: "Disable the data catalog for an R2 bucket",
status: "open-beta",
owner: "Product: R2 Data Catalog"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the bucket to disable the data catalog for",
type: "string",
demandOption: true
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const confirmedDisable = await confirm(
`Are you sure you want to disable the data catalog for bucket '${args.bucket}'?`
);
if (!confirmedDisable) {
logger.log("Disable cancelled.");
return;
}
try {
await disableR2Catalog(config, accountId, args.bucket);
logger.log(
`Successfully disabled the data catalog on bucket '${args.bucket}'.`
);
} catch (e7) {
if (e7 instanceof APIError && e7.code == 40401) {
logger.log(
`Data catalog is not enabled for bucket '${args.bucket}'. Please use 'wrangler r2 bucket catalog enable ${args.bucket}' to first enable the data catalog on this bucket.`
);
} else {
throw e7;
}
}
}
});
r2BucketCatalogGetCommand = createCommand({
metadata: {
description: "Get the status of the data catalog for an R2 bucket",
status: "open-beta",
owner: "Product: R2 Data Catalog"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket whose data catalog status to retrieve",
type: "string",
demandOption: true
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
logger.log(`Getting data catalog status for '${args.bucket}'...
`);
try {
const catalog = await getR2Catalog(config, accountId, args.bucket);
const env6 = getCloudflareApiEnvironmentFromEnv();
let catalogHost;
const path72 = catalog.name.replace("_", "/");
if (env6 === "staging") {
catalogHost = `https://catalog-staging.cloudflarestorage.com/${path72}`;
} else {
catalogHost = `https://catalog.cloudflarestorage.com/${path72}`;
}
const output = {
"Catalog URI": catalogHost,
Warehouse: catalog.name,
Status: catalog.status
};
logger.log(formatLabelledValues(output));
} catch (e7) {
if (e7 instanceof APIError && e7.code == 40401) {
logger.log(
`Data catalog is not enabled for bucket '${args.bucket}'. Please use 'wrangler r2 bucket catalog enable ${args.bucket}' to first enable the data catalog on this bucket.`
);
} else {
throw e7;
}
}
}
});
}
});
// src/r2/cors.ts
var import_node_path52, r2BucketCORSNamespace, r2BucketCORSListCommand, r2BucketCORSSetCommand, r2BucketCORSDeleteCommand;
var init_cors = __esm({
"src/r2/cors.ts"() {
init_import_meta_url();
import_node_path52 = __toESM(require("path"));
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_parse();
init_user2();
init_render_labelled_values();
init_helpers();
r2BucketCORSNamespace = createNamespace({
metadata: {
description: "Manage CORS configuration for an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketCORSListCommand = createCommand({
metadata: {
description: "List the CORS rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to list the CORS rules for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler({ bucket, jurisdiction }, { config }) {
const accountId = await requireAuth(config);
logger.log(`Listing CORS rules for bucket '${bucket}'...`);
const corsPolicy = await getCORSPolicy(
config,
accountId,
bucket,
jurisdiction
);
if (corsPolicy.length === 0) {
logger.log(
`There is no CORS configuration defined for bucket '${bucket}'.`
);
} else {
const tableOutput = tableFromCORSPolicyResponse(corsPolicy);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
}
});
r2BucketCORSSetCommand = createCommand({
metadata: {
description: "Set the CORS configuration for an R2 bucket from a JSON file",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to set the CORS configuration for",
type: "string",
demandOption: true
},
file: {
describe: "Path to the JSON file containing the CORS configuration",
type: "string",
demandOption: true,
requiresArg: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler({ bucket, file, jurisdiction, force }, { config }) {
const accountId = await requireAuth(config);
const jsonFilePath = import_node_path52.default.resolve(file);
const corsConfig = parseJSON(readFileSync6(jsonFilePath), jsonFilePath);
if (!corsConfig.rules || !Array.isArray(corsConfig.rules)) {
throw new UserError(
`The CORS configuration file must contain a 'rules' array as expected by the request body of the CORS API: https://developers.cloudflare.com/api/operations/r2-put-bucket-cors-policy`
);
}
if (!force) {
const confirmedRemoval = await confirm(
`Are you sure you want to overwrite the existing CORS configuration for bucket '${bucket}'?`
);
if (!confirmedRemoval) {
logger.log("Set cancelled.");
return;
}
}
logger.log(
`Setting CORS configuration (${corsConfig.rules.length} rules) for bucket '${bucket}'...`
);
await putCORSPolicy(
config,
accountId,
bucket,
corsConfig.rules,
jurisdiction
);
logger.log(`\u2728 Set CORS configuration for bucket '${bucket}'.`);
}
});
r2BucketCORSDeleteCommand = createCommand({
metadata: {
description: "Clear the CORS configuration for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to delete the CORS configuration for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler({ bucket, jurisdiction, force }, { config }) {
const accountId = await requireAuth(config);
if (!force) {
const confirmedRemoval = await confirm(
`Are you sure you want to clear the existing CORS configuration for bucket '${bucket}'?`
);
if (!confirmedRemoval) {
logger.log("Set cancelled.");
return;
}
}
logger.log(`Deleting the CORS configuration for bucket '${bucket}'...`);
await deleteCORSPolicy(config, accountId, bucket, jurisdiction);
logger.log(`CORS configuration deleted for bucket '${bucket}'.`);
}
});
}
});
// src/r2/domain.ts
var r2BucketDomainNamespace, r2BucketDomainGetCommand, r2BucketDomainListCommand, r2BucketDomainAddCommand, r2BucketDomainRemoveCommand, r2BucketDomainUpdateCommand;
var init_domain = __esm({
"src/r2/domain.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_logger();
init_user2();
init_render_labelled_values();
init_helpers();
r2BucketDomainNamespace = createNamespace({
metadata: {
description: "Manage custom domains for an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketDomainGetCommand = createCommand({
metadata: {
description: "Get custom domain connected to an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket whose custom domain to retrieve",
type: "string",
demandOption: true
},
domain: {
describe: "The custom domain to get information for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler({ bucket, domain: domain2, jurisdiction }, { config }) {
const accountId = await requireAuth(config);
logger.log(
`Retrieving custom domain '${domain2}' connected to bucket '${bucket}'...`
);
const domainResponse = await getCustomDomain(
config,
accountId,
bucket,
domain2,
jurisdiction
);
const tableOutput = tableFromCustomDomainListResponse([domainResponse]);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
});
r2BucketDomainListCommand = createCommand({
metadata: {
description: "List custom domains for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket whose connected custom domains will be listed",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, jurisdiction } = args;
logger.log(`Listing custom domains connected to bucket '${bucket}'...`);
const domains = await listCustomDomainsOfBucket(
config,
accountId,
bucket,
jurisdiction
);
if (domains.length === 0) {
logger.log("There are no custom domains connected to this bucket.");
} else {
const tableOutput = tableFromCustomDomainListResponse(domains);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
}
});
r2BucketDomainAddCommand = createCommand({
metadata: {
description: "Connect a custom domain to an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to connect a custom domain to",
type: "string",
demandOption: true
},
domain: {
describe: "The custom domain to connect to the R2 bucket",
type: "string",
demandOption: true
},
"zone-id": {
describe: "The zone ID associated with the custom domain",
type: "string",
demandOption: true
},
"min-tls": {
describe: "Set the minimum TLS version for the custom domain (defaults to 1.0 if not set)",
choices: ["1.0", "1.1", "1.2", "1.3"],
type: "string"
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const {
bucket,
domain: domain2,
zoneId,
minTls = "1.0",
jurisdiction,
force
} = args;
if (!force) {
const confirmedAdd = await confirm(
`Are you sure you want to add the custom domain '${domain2}' to bucket '${bucket}'? The contents of your bucket will be made publicly available at 'https://${domain2}'`
);
if (!confirmedAdd) {
logger.log("Add cancelled.");
return;
}
}
logger.log(`Connecting custom domain '${domain2}' to bucket '${bucket}'...`);
await attachCustomDomainToBucket(
config,
accountId,
bucket,
{
domain: domain2,
zoneId,
minTLS: minTls
},
jurisdiction
);
logger.log(`\u2728 Custom domain '${domain2}' connected successfully.`);
}
});
r2BucketDomainRemoveCommand = createCommand({
metadata: {
description: "Remove a custom domain from an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to remove the custom domain from",
type: "string",
demandOption: true
},
domain: {
describe: "The custom domain to remove from the R2 bucket",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, domain: domain2, jurisdiction, force } = args;
if (!force) {
const confirmedRemoval = await confirm(
`Are you sure you want to remove the custom domain '${domain2}' from bucket '${bucket}'? Your bucket will no longer be available from 'https://${domain2}'`
);
if (!confirmedRemoval) {
logger.log("Removal cancelled.");
return;
}
}
logger.log(`Removing custom domain '${domain2}' from bucket '${bucket}'...`);
await removeCustomDomainFromBucket(
config,
accountId,
bucket,
domain2,
jurisdiction
);
logger.log(`Custom domain '${domain2}' removed successfully.`);
}
});
r2BucketDomainUpdateCommand = createCommand({
metadata: {
description: "Update settings for a custom domain connected to an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket associated with the custom domain to update",
type: "string",
demandOption: true
},
domain: {
describe: "The custom domain whose settings will be updated",
type: "string",
demandOption: true
},
"min-tls": {
describe: "Update the minimum TLS version for the custom domain",
choices: ["1.0", "1.1", "1.2", "1.3"],
type: "string"
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, domain: domain2, minTls, jurisdiction } = args;
logger.log(`Updating custom domain '${domain2}' for bucket '${bucket}'...`);
await configureCustomDomainSettings(
config,
accountId,
bucket,
domain2,
{
domain: domain2,
minTLS: minTls
},
jurisdiction
);
logger.log(`\u2728 Custom domain '${domain2}' updated successfully.`);
}
});
}
});
// src/r2/lifecycle.ts
var r2BucketLifecycleNamespace, r2BucketLifecycleListCommand, r2BucketLifecycleAddCommand, r2BucketLifecycleRemoveCommand, r2BucketLifecycleSetCommand;
var init_lifecycle = __esm({
"src/r2/lifecycle.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_errors();
init_is_interactive();
init_logger();
init_parse();
init_user2();
init_render_labelled_values();
init_helpers();
r2BucketLifecycleNamespace = createNamespace({
metadata: {
description: "Manage lifecycle rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketLifecycleListCommand = createCommand({
metadata: {
description: "List lifecycle rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to list lifecycle rules for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, jurisdiction } = args;
logger.log(`Listing lifecycle rules for bucket '${bucket}'...`);
const lifecycleRules = await getLifecycleRules(
config,
accountId,
bucket,
jurisdiction
);
if (lifecycleRules.length === 0) {
logger.log(`There are no lifecycle rules for bucket '${bucket}'.`);
} else {
const tableOutput = tableFromLifecycleRulesResponse(lifecycleRules);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
}
});
r2BucketLifecycleAddCommand = createCommand({
metadata: {
description: "Add a lifecycle rule to an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket", "name", "prefix"],
args: {
bucket: {
describe: "The name of the R2 bucket to add a lifecycle rule to",
type: "string",
demandOption: true
},
name: {
describe: "A unique name for the lifecycle rule, used to identify and manage it.",
alias: "id",
type: "string",
requiresArg: true
},
prefix: {
describe: "Prefix condition for the lifecycle rule (leave empty for all prefixes)",
type: "string",
requiresArg: true
},
"expire-days": {
describe: "Number of days after which objects expire",
type: "number",
requiresArg: true
},
"expire-date": {
describe: "Date after which objects expire (YYYY-MM-DD)",
type: "string",
requiresArg: true
},
"ia-transition-days": {
describe: "Number of days after which objects transition to Infrequent Access storage",
type: "number",
requiresArg: true
},
"ia-transition-date": {
describe: "Date after which objects transition to Infrequent Access storage (YYYY-MM-DD)",
type: "string",
requiresArg: true
},
"abort-multipart-days": {
describe: "Number of days after which incomplete multipart uploads are aborted",
type: "number",
requiresArg: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler({
bucket,
expireDays,
expireDate,
iaTransitionDays,
iaTransitionDate,
abortMultipartDays,
jurisdiction,
force,
name: name2,
prefix
}, { config }) {
const accountId = await requireAuth(config);
const lifecycleRules = await getLifecycleRules(
config,
accountId,
bucket,
jurisdiction
);
if (!name2 && isInteractive2()) {
name2 = await prompt("Enter a unique name for the lifecycle rule");
}
if (!name2) {
throw new UserError("Must specify a rule name.");
}
const newRule = {
id: name2,
enabled: true,
conditions: {}
};
let selectedActions = [];
if (expireDays !== void 0 || expireDate !== void 0) {
selectedActions.push("expire");
}
if (iaTransitionDays !== void 0 || iaTransitionDate !== void 0) {
selectedActions.push("transition");
}
if (abortMultipartDays !== void 0) {
selectedActions.push("abort-multipart");
}
if (selectedActions.length === 0 && isInteractive2()) {
if (prefix === void 0) {
prefix = await prompt(
"Enter a prefix for the lifecycle rule (leave empty for all prefixes)"
);
}
const actionChoices = [
{ title: "Expire objects", value: "expire" },
{
title: "Transition to Infrequent Access storage class",
value: "transition"
},
{
title: "Abort incomplete multipart uploads",
value: "abort-multipart"
}
];
selectedActions = await multiselect("Select the actions to apply", {
choices: actionChoices
});
}
if (selectedActions.length === 0) {
throw new UserError("Must specify at least one action.");
}
for (const action of selectedActions) {
let conditionType;
let conditionValue;
if (action === "abort-multipart") {
if (abortMultipartDays !== void 0) {
conditionValue = abortMultipartDays;
} else {
conditionValue = await prompt(
`Enter the number of days after which to ${formatActionDescription(action)}`
);
}
if (!isNonNegativeNumber(String(conditionValue))) {
throw new UserError("Must be a positive number.");
}
conditionType = "Age";
conditionValue = Number(conditionValue) * 86400;
newRule.abortMultipartUploadsTransition = {
condition: {
maxAge: conditionValue,
type: conditionType
}
};
} else {
if (expireDays !== void 0) {
conditionType = "Age";
conditionValue = expireDays;
} else if (iaTransitionDays !== void 0) {
conditionType = "Age";
conditionValue = iaTransitionDays;
} else if (expireDate !== void 0) {
conditionType = "Date";
conditionValue = expireDate;
} else if (iaTransitionDate !== void 0) {
conditionType = "Date";
conditionValue = iaTransitionDate;
} else {
conditionValue = await prompt(
`Enter the number of days or a date (YYYY-MM-DD) after which to ${formatActionDescription(action)}`
);
if (!isNonNegativeNumber(String(conditionValue)) && !isValidDate(String(conditionValue))) {
throw new UserError(
"Must be a positive number or a valid date in the YYYY-MM-DD format."
);
}
}
if (isNonNegativeNumber(String(conditionValue))) {
conditionType = "Age";
conditionValue = Number(conditionValue) * 86400;
} else if (isValidDate(String(conditionValue))) {
conditionType = "Date";
const date = /* @__PURE__ */ new Date(`${conditionValue}T00:00:00.000Z`);
conditionValue = date.toISOString();
} else {
throw new UserError("Invalid condition input.");
}
if (action === "expire") {
newRule.deleteObjectsTransition = {
condition: {
[conditionType === "Age" ? "maxAge" : "date"]: conditionValue,
type: conditionType
}
};
} else if (action === "transition") {
newRule.storageClassTransitions = [
{
condition: {
[conditionType === "Age" ? "maxAge" : "date"]: conditionValue,
type: conditionType
},
storageClass: "InfrequentAccess"
}
];
}
}
}
if (!prefix && !force) {
const confirmedAdd = await confirm(
`Are you sure you want to add lifecycle rule '${name2}' to bucket '${bucket}' without a prefix? The lifecycle rule will apply to all objects in your bucket.`
);
if (!confirmedAdd) {
logger.log("Add cancelled.");
return;
}
}
if (prefix) {
newRule.conditions.prefix = prefix;
}
lifecycleRules.push(newRule);
logger.log(`Adding lifecycle rule '${name2}' to bucket '${bucket}'...`);
await putLifecycleRules(
config,
accountId,
bucket,
lifecycleRules,
jurisdiction
);
logger.log(`\u2728 Added lifecycle rule '${name2}' to bucket '${bucket}'.`);
}
});
r2BucketLifecycleRemoveCommand = createCommand({
metadata: {
description: "Remove a lifecycle rule from an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to remove a lifecycle rule from",
type: "string",
demandOption: true
},
name: {
describe: "The unique name of the lifecycle rule to remove",
alias: "id",
type: "string",
demandOption: true,
requiresArg: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, name: name2, jurisdiction } = args;
const lifecycleRules = await getLifecycleRules(
config,
accountId,
bucket,
jurisdiction
);
const index = lifecycleRules.findIndex((rule) => rule.id === name2);
if (index === -1) {
throw new UserError(
`Lifecycle rule with ID '${name2}' not found in configuration for '${bucket}'.`
);
}
lifecycleRules.splice(index, 1);
logger.log(`Removing lifecycle rule '${name2}' from bucket '${bucket}'...`);
await putLifecycleRules(
config,
accountId,
bucket,
lifecycleRules,
jurisdiction
);
logger.log(`Lifecycle rule '${name2}' removed from bucket '${bucket}'.`);
}
});
r2BucketLifecycleSetCommand = createCommand({
metadata: {
description: "Set the lifecycle configuration for an R2 bucket from a JSON file",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to set lifecycle configuration for",
type: "string",
demandOption: true
},
file: {
describe: "Path to the JSON file containing lifecycle configuration",
type: "string",
demandOption: true,
requiresArg: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, file, jurisdiction, force } = args;
let lifecyclePolicy;
try {
lifecyclePolicy = JSON.parse(readFileSync6(file));
} catch (e7) {
if (e7 instanceof Error) {
throw new UserError(
`Failed to read or parse the lifecycle configuration config file: '${e7.message}'`
);
} else {
throw e7;
}
}
if (!lifecyclePolicy.rules || !Array.isArray(lifecyclePolicy.rules)) {
throw new UserError(
"The lifecycle configuration file must contain a 'rules' array."
);
}
if (!force) {
const confirmedRemoval = await confirm(
`Are you sure you want to overwrite all existing lifecycle rules for bucket '${bucket}'?`
);
if (!confirmedRemoval) {
logger.log("Set cancelled.");
return;
}
}
logger.log(
`Setting lifecycle configuration (${lifecyclePolicy.rules.length} rules) for bucket '${bucket}'...`
);
await putLifecycleRules(
config,
accountId,
bucket,
lifecyclePolicy.rules,
jurisdiction
);
logger.log(`\u2728 Set lifecycle configuration for bucket '${bucket}'.`);
}
});
}
});
// src/r2/lock.ts
var r2BucketLockNamespace, r2BucketLockListCommand, r2BucketLockAddCommand, r2BucketLockRemoveCommand, r2BucketLockSetCommand;
var init_lock = __esm({
"src/r2/lock.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_errors();
init_is_interactive();
init_logger();
init_parse();
init_user2();
init_render_labelled_values();
init_helpers();
r2BucketLockNamespace = createNamespace({
metadata: {
description: "Manage lock rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketLockListCommand = createCommand({
metadata: {
description: "List lock rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to list lock rules for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, jurisdiction } = args;
logger.log(`Listing lock rules for bucket '${bucket}'...`);
const rules = await getBucketLockRules(
config,
accountId,
bucket,
jurisdiction
);
if (rules.length === 0) {
logger.log(`There are no lock rules for bucket '${bucket}'.`);
} else {
const tableOutput = tableFromBucketLockRulesResponse(rules);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
}
});
r2BucketLockAddCommand = createCommand({
metadata: {
description: "Add a lock rule to an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket", "name", "prefix"],
args: {
bucket: {
describe: "The name of the R2 bucket to add a bucket lock rule to",
type: "string",
demandOption: true
},
name: {
describe: "A unique name for the bucket lock rule, used to identify and manage it.",
alias: "id",
type: "string",
requiresArg: true
},
prefix: {
describe: 'Prefix condition for the bucket lock rule (set to "" for all prefixes)',
type: "string",
requiresArg: true
},
"retention-days": {
describe: "Number of days which objects will be retained for",
type: "number",
conflicts: ["retention-date", "retention-indefinite"]
},
"retention-date": {
describe: "Date after which objects will be retained until (YYYY-MM-DD)",
type: "string",
conflicts: ["retention-days", "retention-indefinite"]
},
"retention-indefinite": {
describe: "Retain objects indefinitely",
type: "boolean",
conflicts: ["retention-date", "retention-days"]
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler({
bucket,
retentionDays,
retentionDate,
retentionIndefinite,
jurisdiction,
force,
name: name2,
prefix
}, { config }) {
const accountId = await requireAuth(config);
const rules = await getBucketLockRules(
config,
accountId,
bucket,
jurisdiction
);
if (!name2 && !isNonInteractiveOrCI() && !force) {
name2 = await prompt("Enter a unique name for the lock rule");
}
if (!name2) {
throw new UserError("Must specify a rule name.", {
telemetryMessage: true
});
}
const newRule = {
id: name2,
enabled: true,
condition: { type: "Indefinite" }
};
if (prefix === void 0 && !force) {
prefix = await prompt(
'Enter a prefix for the bucket lock rule (set to "" for all prefixes)',
{ defaultValue: "" }
);
if (prefix === "") {
const confirmedAdd = await confirm(
`Are you sure you want to add lock rule '${name2}' to bucket '${bucket}' without a prefix? The lock rule will apply to all objects in your bucket.`,
{ defaultValue: false }
);
if (!confirmedAdd) {
logger.log("Add cancelled.");
return;
}
}
}
if (prefix) {
newRule.prefix = prefix;
}
if (retentionDays === void 0 && retentionDate === void 0 && retentionIndefinite === void 0 && !force) {
retentionIndefinite = await confirm(
`Are you sure you want to add lock rule '${name2}' to bucket '${bucket}' without retention? The lock rule will apply to all matching objects indefinitely.`,
{ defaultValue: false }
);
if (retentionIndefinite !== true) {
logger.log("Add cancelled.");
return;
}
}
if (retentionDays !== void 0) {
if (!isNaN(retentionDays)) {
if (retentionDays > 0) {
const conditionDaysValue = Number(retentionDays) * 86400;
newRule.condition = {
type: "Age",
maxAgeSeconds: conditionDaysValue
};
} else {
throw new UserError(
`Days must be a positive number: ${retentionDays}`,
{
telemetryMessage: "Retention days not a positive number."
}
);
}
} else {
throw new UserError(`Days must be a number.`, {
telemetryMessage: "Retention days not a positive number."
});
}
} else if (retentionDate !== void 0) {
if (isValidDate(retentionDate)) {
const date = /* @__PURE__ */ new Date(`${retentionDate}T00:00:00.000Z`);
const conditionDateValue = date.toISOString();
newRule.condition = {
type: "Date",
date: conditionDateValue
};
} else {
throw new UserError(
`Date must be a valid date in the YYYY-MM-DD format: ${String(retentionDate)}`,
{
telemetryMessage: "Retention date not a valid date in the YYYY-MM-DD format."
}
);
}
} else if (retentionIndefinite !== void 0 && retentionIndefinite === true) {
newRule.condition = {
type: "Indefinite"
};
} else {
throw new UserError(`Retention must be specified.`, {
telemetryMessage: "Lock retention not specified."
});
}
rules.push(newRule);
logger.log(`Adding lock rule '${name2}' to bucket '${bucket}'...`);
await putBucketLockRules(config, accountId, bucket, rules, jurisdiction);
logger.log(`\u2728 Added lock rule '${name2}' to bucket '${bucket}'.`);
}
});
r2BucketLockRemoveCommand = createCommand({
metadata: {
description: "Remove a bucket lock rule from an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to remove a bucket lock rule from",
type: "string",
demandOption: true
},
name: {
describe: "The unique name of the bucket lock rule to remove",
alias: "id",
type: "string",
demandOption: true,
requiresArg: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, name: name2, jurisdiction } = args;
const lockPolicies = await getBucketLockRules(
config,
accountId,
bucket,
jurisdiction
);
const index = lockPolicies.findIndex((policy) => policy.id === name2);
if (index === -1) {
throw new UserError(
`Lock rule with ID '${name2}' not found in configuration for '${bucket}'.`,
{
telemetryMessage: "Lock rule with name not found in configuration for bucket."
}
);
}
lockPolicies.splice(index, 1);
logger.log(`Removing lock rule '${name2}' from bucket '${bucket}'...`);
await putBucketLockRules(
config,
accountId,
bucket,
lockPolicies,
jurisdiction
);
logger.log(`Lock rule '${name2}' removed from bucket '${bucket}'.`);
}
});
r2BucketLockSetCommand = createCommand({
metadata: {
description: "Set the lock configuration for an R2 bucket from a JSON file",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to set lock configuration for",
type: "string",
demandOption: true
},
file: {
describe: "Path to the JSON file containing lock configuration",
type: "string",
demandOption: true,
requiresArg: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, file, jurisdiction, force } = args;
let lockRule;
try {
lockRule = JSON.parse(readFileSync6(file));
} catch (e7) {
if (e7 instanceof Error) {
throw new ParseError({
text: `Failed to read or parse the lock configuration config file: '${e7.message}'`,
telemetryMessage: "Failed to read or parse the lock configuration config file."
});
} else {
throw e7;
}
}
if (!lockRule.rules || !Array.isArray(lockRule.rules)) {
throw new UserError(
"The lock configuration file must contain a 'rules' array.",
{ telemetryMessage: true }
);
}
if (!force) {
const confirmedRemoval = await confirm(
`Are you sure you want to overwrite all existing lock rules for bucket '${bucket}'?`,
{ defaultValue: true }
);
if (!confirmedRemoval) {
logger.log("Set cancelled.");
return;
}
}
logger.log(
`Setting lock configuration (${lockRule.rules.length} rules) for bucket '${bucket}'...`
);
await putBucketLockRules(
config,
accountId,
bucket,
lockRule.rules,
jurisdiction
);
logger.log(`\u2728 Set lock configuration for bucket '${bucket}'.`);
}
});
}
});
// src/r2/notification.ts
var r2BucketNotificationNamespace, r2BucketNotificationGetAlias, r2BucketNotificationListCommand, r2BucketNotificationCreateCommand, r2BucketNotificationDeleteCommand;
var init_notification = __esm({
"src/r2/notification.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_user2();
init_render_labelled_values();
init_helpers();
r2BucketNotificationNamespace = createNamespace({
metadata: {
description: "Manage event notification rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketNotificationGetAlias = createAlias({
aliasOf: "wrangler r2 bucket notification list"
});
r2BucketNotificationListCommand = createCommand({
metadata: {
description: "List event notification rules for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to get event notification rules for",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
if (args._[3] === "get") {
logger.warn(
"`wrangler r2 bucket notification get` is deprecated and will be removed in an upcoming release.\nPlease use `wrangler r2 bucket notification list` instead."
);
}
const accountId = await requireAuth(config);
const apiCreds = requireApiToken();
const { bucket, jurisdiction = "" } = args;
const resp = await listEventNotificationConfig(
config,
apiCreds,
accountId,
bucket,
jurisdiction
);
const tableOutput = tableFromNotificationGetResponse(resp);
logger.log(tableOutput.map((x6) => formatLabelledValues(x6)).join("\n\n"));
}
});
r2BucketNotificationCreateCommand = createCommand({
metadata: {
description: "Create an event notification rule for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to create an event notification rule for",
type: "string",
demandOption: true
},
"event-types": {
describe: "The type of event(s) that will emit event notifications",
alias: "event-type",
choices: Object.keys(actionsForEventCategories),
demandOption: true,
requiresArg: true,
array: true
},
prefix: {
describe: "The prefix that an object must match to emit event notifications (note: regular expressions not supported)",
requiresArg: false,
type: "string"
},
suffix: {
describe: "The suffix that an object must match to emit event notifications (note: regular expressions not supported)",
type: "string"
},
queue: {
describe: "The name of the queue that will receive event notification messages",
demandOption: true,
requiresArg: true,
type: "string"
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
description: {
describe: "A description that can be used to identify the event notification rule after creation",
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const apiCreds = requireApiToken();
const {
bucket,
queue,
eventTypes,
prefix = "",
suffix = "",
jurisdiction = "",
description
} = args;
await putEventNotificationConfig(
config,
apiCreds,
accountId,
bucket,
jurisdiction,
queue,
eventTypes,
prefix,
suffix,
description
);
logger.log("Event notification rule created successfully!");
}
});
r2BucketNotificationDeleteCommand = createCommand({
metadata: {
description: "Delete an event notification rule from an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to delete an event notification rule for",
type: "string",
demandOption: true
},
queue: {
describe: "The name of the queue that corresponds to the event notification rule. If no rule is provided, all event notification rules associated with the bucket and queue will be deleted",
demandOption: true,
requiresArg: true,
type: "string"
},
rule: {
describe: "The ID of the event notification rule to delete",
requiresArg: false,
type: "string"
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const apiCreds = requireApiToken();
const { bucket, queue, rule, jurisdiction = "" } = args;
await deleteEventNotificationConfig(
config,
apiCreds,
accountId,
bucket,
jurisdiction,
queue,
rule
);
logger.log("Event notification rule deleted successfully!");
}
});
}
});
// src/r2/object.ts
var import_node_buffer5, fs20, path55, stream, r2ObjectNamespace, r2ObjectGetCommand, r2ObjectPutCommand, r2ObjectDeleteCommand;
var init_object = __esm({
"src/r2/object.ts"() {
init_import_meta_url();
import_node_buffer5 = require("buffer");
fs20 = __toESM(require("fs"));
path55 = __toESM(require("path"));
stream = __toESM(require("stream"));
init_pretty_bytes();
init_config2();
init_create_command();
init_errors();
init_logger();
init_user2();
init_is_local();
init_constants17();
init_helpers();
r2ObjectNamespace = createNamespace({
metadata: {
description: `Manage R2 objects`,
status: "stable",
owner: "Product: R2"
}
});
r2ObjectGetCommand = createCommand({
metadata: {
description: "Fetch an object from an R2 bucket",
status: "stable",
owner: "Product: R2"
},
args: {
objectPath: {
describe: "The source object path in the form of {bucket}/{key}",
type: "string",
demandOption: true
},
file: {
describe: "The destination file to create",
alias: "f",
conflicts: "pipe",
requiresArg: true,
type: "string"
},
pipe: {
describe: "Enables the file to be piped to a destination, rather than specified with the --file option",
alias: "p",
conflicts: "file",
type: "boolean"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
},
jurisdiction: {
describe: "The jurisdiction where the object exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
behaviour: {
printBanner({ pipe }) {
return !pipe;
},
printResourceLocation(args) {
return !args?.pipe;
}
},
positionalArgs: ["objectPath"],
async handler(objectGetYargs, { config }) {
const localMode = isLocal(objectGetYargs);
const { objectPath, pipe, jurisdiction } = objectGetYargs;
const { bucket, key } = bucketAndKeyFromObjectPath(objectPath);
let fullBucketName = bucket;
if (jurisdiction !== void 0) {
fullBucketName += ` (${jurisdiction})`;
}
let file = objectGetYargs.file;
if (!file && !pipe) {
file = key;
}
if (!pipe) {
logger.log(`Downloading "${key}" from "${fullBucketName}".`);
}
let output;
if (file) {
fs20.mkdirSync(path55.dirname(file), { recursive: true });
output = fs20.createWriteStream(file);
} else {
output = process.stdout;
}
if (localMode) {
await usingLocalBucket(
objectGetYargs.persistTo,
config,
bucket,
async (r2Bucket) => {
const object = await r2Bucket.get(key);
if (object === null) {
throw new UserError("The specified key does not exist.");
}
await stream.promises.pipeline(object.body, output);
}
);
} else {
const accountId = await requireAuth(config);
const input = await getR2Object(
config,
accountId,
bucket,
key,
jurisdiction
);
if (input === null) {
throw new UserError("The specified key does not exist.");
}
await stream.promises.pipeline(input, output);
}
if (!pipe) {
logger.log("Download complete.");
}
}
});
r2ObjectPutCommand = createCommand({
metadata: {
description: "Create an object in an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["objectPath"],
args: {
objectPath: {
describe: "The destination object path in the form of {bucket}/{key}",
type: "string",
demandOption: true
},
file: {
describe: "The path of the file to upload",
alias: "f",
conflicts: "pipe",
requiresArg: true,
type: "string"
},
pipe: {
describe: "Enables the file to be piped in, rather than specified with the --file option",
alias: "p",
conflicts: "file",
type: "boolean"
},
"content-type": {
describe: "A standard MIME type describing the format of the object data",
alias: "ct",
requiresArg: true,
type: "string"
},
"content-disposition": {
describe: "Specifies presentational information for the object",
alias: "cd",
requiresArg: true,
type: "string"
},
"content-encoding": {
describe: "Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field",
alias: "ce",
requiresArg: true,
type: "string"
},
"content-language": {
describe: "The language the content is in",
alias: "cl",
requiresArg: true,
type: "string"
},
"cache-control": {
describe: "Specifies caching behavior along the request/reply chain",
alias: "cc",
requiresArg: true,
type: "string"
},
expires: {
describe: "The date and time at which the object is no longer cacheable",
alias: "e",
requiresArg: true,
type: "string"
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
},
jurisdiction: {
describe: "The jurisdiction where the object will be created",
alias: "J",
requiresArg: true,
type: "string"
},
"storage-class": {
describe: "The storage class of the object to be created",
alias: "s",
requiresArg: false,
type: "string"
}
},
behaviour: {
printResourceLocation(args) {
return !args?.pipe;
}
},
async handler(objectPutYargs, { config }) {
const {
objectPath,
file,
pipe,
persistTo,
jurisdiction,
storageClass,
...options
} = objectPutYargs;
const localMode = isLocal(objectPutYargs);
const { bucket, key } = bucketAndKeyFromObjectPath(objectPath);
if (!file && !pipe) {
throw new CommandLineArgsError(
"Either the --file or --pipe options are required."
);
}
let object;
let objectSize;
if (file) {
object = await createFileReadableStream(file);
const stats = fs20.statSync(file);
objectSize = stats.size;
} else {
const buffer = await new Promise((resolve25, reject) => {
const stdin = process.stdin;
const chunks = Array();
stdin.on("data", (chunk) => chunks.push(chunk));
stdin.on("end", () => resolve25(Buffer.concat(chunks)));
stdin.on(
"error",
(err) => reject(
new CommandLineArgsError(`Could not pipe. Reason: "${err.message}"`)
)
);
});
const blob = new import_node_buffer5.Blob([buffer]);
object = blob.stream();
objectSize = blob.size;
}
if (objectSize > MAX_UPLOAD_SIZE && !localMode) {
throw new FatalError(
`Error: Wrangler only supports uploading files up to ${prettyBytes(
MAX_UPLOAD_SIZE,
{ binary: true }
)} in size
${key} is ${prettyBytes(objectSize, {
binary: true
})} in size`,
1
);
}
let fullBucketName = bucket;
if (jurisdiction !== void 0) {
fullBucketName += ` (${jurisdiction})`;
}
let storageClassLog = ``;
if (storageClass !== void 0) {
storageClassLog = ` with ${storageClass} storage class`;
}
logger.log(
`Creating object "${key}"${storageClassLog} in bucket "${fullBucketName}".`
);
if (localMode) {
await usingLocalBucket(
persistTo,
config,
bucket,
async (r2Bucket, mf) => {
const putOptions = {
httpMetadata: {
contentType: options.contentType,
contentDisposition: options.contentDisposition,
contentEncoding: options.contentEncoding,
contentLanguage: options.contentLanguage,
cacheControl: options.cacheControl,
// @ts-expect-error `@cloudflare/workers-types` is wrong
// here, `number`'s are allowed for `Date`s
// TODO(now): fix
cacheExpiry: options.expires === void 0 ? void 0 : parseInt(options.expires)
},
customMetadata: void 0,
sha1: void 0,
sha256: void 0,
onlyIf: void 0,
md5: void 0,
sha384: void 0,
sha512: void 0
};
await mf.dispatchFetch(`http://localhost/${key}`, {
method: "PUT",
body: object,
duplex: "half",
headers: {
"Content-Length": objectSize.toString(),
"Wrangler-R2-Put-Options": JSON.stringify(putOptions)
}
});
}
);
} else {
const accountId = await requireAuth(config);
await putR2Object(
config,
accountId,
bucket,
key,
object,
{
...options,
"content-length": `${objectSize}`
},
jurisdiction,
storageClass
);
}
logger.log("Upload complete.");
}
});
r2ObjectDeleteCommand = createCommand({
metadata: {
description: "Delete an object in an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["objectPath"],
args: {
objectPath: {
describe: "The destination object path in the form of {bucket}/{key}",
type: "string",
demandOption: true
},
local: {
type: "boolean",
describe: "Interact with local storage"
},
remote: {
type: "boolean",
describe: "Interact with remote storage",
conflicts: "local"
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
},
jurisdiction: {
describe: "The jurisdiction where the object exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
behaviour: {
printResourceLocation: true
},
async handler(args) {
const localMode = isLocal(args);
const { objectPath, jurisdiction } = args;
const config = readConfig(args);
const { bucket, key } = bucketAndKeyFromObjectPath(objectPath);
let fullBucketName = bucket;
if (jurisdiction !== void 0) {
fullBucketName += ` (${jurisdiction})`;
}
logger.log(`Deleting object "${key}" from bucket "${fullBucketName}".`);
if (localMode) {
await usingLocalBucket(
args.persistTo,
config,
bucket,
(r2Bucket) => r2Bucket.delete(key)
);
} else {
const accountId = await requireAuth(config);
await deleteR2Object(config, accountId, bucket, key, jurisdiction);
}
logger.log("Delete complete.");
}
});
}
});
// src/r2/public-dev-url.ts
var r2BucketDevUrlNamespace, r2BucketDevUrlGetCommand, r2BucketDevUrlEnableCommand, r2BucketDevUrlDisableCommand;
var init_public_dev_url = __esm({
"src/r2/public-dev-url.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_logger();
init_user2();
init_helpers();
r2BucketDevUrlNamespace = createNamespace({
metadata: {
description: "Manage public access via the r2.dev URL for an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketDevUrlGetCommand = createCommand({
metadata: {
description: "Get the r2.dev URL and status for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket whose r2.dev URL status to retrieve",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, jurisdiction } = args;
const devDomain = await getR2DevDomain(
config,
accountId,
bucket,
jurisdiction
);
if (devDomain.enabled) {
logger.log(`Public access is enabled at 'https://${devDomain.domain}'.`);
} else {
logger.log(`Public access via the r2.dev URL is disabled.`);
}
}
});
r2BucketDevUrlEnableCommand = createCommand({
metadata: {
description: "Enable public access via the r2.dev URL for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to enable public access via its r2.dev URL",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, jurisdiction, force } = args;
if (!force) {
const confirmedAdd = await confirm(
`Are you sure you enable public access for bucket '${bucket}'? The contents of your bucket will be made publicly available at its r2.dev URL`
);
if (!confirmedAdd) {
logger.log("Enable cancelled.");
return;
}
}
logger.log(`Enabling public access for bucket '${bucket}'...`);
const devDomain = await updateR2DevDomain(
config,
accountId,
bucket,
true,
jurisdiction
);
logger.log(`\u2728 Public access enabled at 'https://${devDomain.domain}'.`);
}
});
r2BucketDevUrlDisableCommand = createCommand({
metadata: {
description: "Disable public access via the r2.dev URL for an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["bucket"],
args: {
bucket: {
describe: "The name of the R2 bucket to disable public access via its r2.dev URL",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
force: {
describe: "Skip confirmation",
type: "boolean",
alias: "y",
default: false
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const { bucket, jurisdiction, force } = args;
if (!force) {
const confirmedAdd = await confirm(
`Are you sure you disable public access for bucket '${bucket}'? The contents of your bucket will no longer be publicly available at its r2.dev URL`
);
if (!confirmedAdd) {
logger.log("Disable cancelled.");
return;
}
}
logger.log(`Disabling public access for bucket '${bucket}'...`);
const devDomain = await updateR2DevDomain(
config,
accountId,
bucket,
false,
jurisdiction
);
logger.log(`Public access disabled at 'https://${devDomain.domain}'.`);
}
});
}
});
// src/r2/sippy.ts
var NO_SUCH_OBJECT_KEY, SIPPY_PROVIDER_CHOICES, r2BucketSippyNamespace, r2BucketSippyEnableCommand, r2BucketSippyDisableCommand, r2BucketSippyGetCommand;
var init_sippy = __esm({
"src/r2/sippy.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_parse();
init_user2();
init_helpers();
NO_SUCH_OBJECT_KEY = 10007;
SIPPY_PROVIDER_CHOICES = ["AWS", "GCS"];
r2BucketSippyNamespace = createNamespace({
metadata: {
description: "Manage Sippy incremental migration on an R2 bucket",
status: "stable",
owner: "Product: R2"
}
});
r2BucketSippyEnableCommand = createCommand({
metadata: {
description: "Enable Sippy on an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["name"],
args: {
name: {
describe: "The name of the bucket",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
},
provider: {
choices: SIPPY_PROVIDER_CHOICES
},
bucket: {
description: "The name of the upstream bucket",
type: "string"
},
region: {
description: "(AWS provider only) The region of the upstream bucket",
type: "string"
},
"access-key-id": {
description: "(AWS provider only) The secret access key id for the upstream bucket",
type: "string"
},
"secret-access-key": {
description: "(AWS provider only) The secret access key for the upstream bucket",
type: "string"
},
"service-account-key-file": {
description: "(GCS provider only) The path to your Google Cloud service account key JSON file",
type: "string"
},
"client-email": {
description: "(GCS provider only) The client email for your Google Cloud service account key",
type: "string"
},
"private-key": {
description: "(GCS provider only) The private key for your Google Cloud service account key",
type: "string"
},
"r2-access-key-id": {
description: "The secret access key id for this R2 bucket",
type: "string"
},
"r2-secret-access-key": {
description: "The secret access key for this R2 bucket",
type: "string"
}
},
async handler(args, { config }) {
const isInteractive3 = process.stdin.isTTY;
const accountId = await requireAuth(config);
if (isInteractive3) {
args.provider ??= await prompt(
"Enter the cloud storage provider of your bucket (AWS or GCS):"
);
if (!args.provider) {
throw new UserError("Must specify a cloud storage provider.");
}
if (!SIPPY_PROVIDER_CHOICES.includes(args.provider)) {
throw new UserError("Cloud storage provider must be: AWS or GCS");
}
args.bucket ??= await prompt(
`Enter the name of your ${args.provider} bucket:`
);
if (!args.bucket) {
throw new UserError(`Must specify ${args.provider} bucket name.`);
}
if (args.provider === "AWS") {
args.region ??= await prompt(
"Enter the AWS region where your S3 bucket is located (example: us-west-2):"
);
if (!args.region) {
throw new UserError("Must specify an AWS Region.");
}
args.accessKeyId ??= await prompt(
"Enter your AWS Access Key ID (requires read and list access):"
);
if (!args.accessKeyId) {
throw new UserError("Must specify an AWS Access Key ID.");
}
args.secretAccessKey ??= await prompt(
"Enter your AWS Secret Access Key:"
);
if (!args.secretAccessKey) {
throw new UserError("Must specify an AWS Secret Access Key.");
}
} else if (args.provider === "GCS") {
if (!(args.clientEmail && args.privateKey) && !args.serviceAccountKeyFile) {
args.serviceAccountKeyFile = await prompt(
"Enter the path to your Google Cloud service account key JSON file:"
);
if (!args.serviceAccountKeyFile) {
throw new UserError(
"Must specify the path to a service account key JSON file."
);
}
}
}
args.r2AccessKeyId ??= await prompt(
"Enter your R2 Access Key ID (requires read and write access):"
);
if (!args.r2AccessKeyId) {
throw new UserError("Must specify an R2 Access Key ID.");
}
args.r2SecretAccessKey ??= await prompt(
"Enter your R2 Secret Access Key:"
);
if (!args.r2SecretAccessKey) {
throw new UserError("Must specify an R2 Secret Access Key.");
}
}
let sippyConfig;
if (args.provider === "AWS") {
if (!args.region) {
throw new UserError("Error: must provide --region.");
}
if (!args.bucket) {
throw new UserError("Error: must provide --bucket.");
}
if (!args.accessKeyId) {
throw new UserError("Error: must provide --access-key-id.");
}
if (!args.secretAccessKey) {
throw new UserError("Error: must provide --secret-access-key.");
}
if (!args.r2AccessKeyId) {
throw new UserError("Error: must provide --r2-access-key-id.");
}
if (!args.r2SecretAccessKey) {
throw new UserError("Error: must provide --r2-secret-access-key.");
}
sippyConfig = {
source: {
provider: "aws",
region: args.region,
bucket: args.bucket,
accessKeyId: args.accessKeyId,
secretAccessKey: args.secretAccessKey
},
destination: {
provider: "r2",
accessKeyId: args.r2AccessKeyId,
secretAccessKey: args.r2SecretAccessKey
}
};
} else if (args.provider === "GCS") {
if (args.serviceAccountKeyFile) {
const serviceAccount = JSON.parse(
readFileSync6(args.serviceAccountKeyFile)
);
if ("client_email" in serviceAccount && "private_key" in serviceAccount) {
args.clientEmail = serviceAccount.client_email;
args.privateKey = serviceAccount.private_key;
}
}
if (!args.bucket) {
throw new UserError("Error: must provide --bucket.");
}
if (!args.clientEmail) {
throw new UserError(
"Error: must provide --service-account-key-file or --client-email."
);
}
if (!args.privateKey) {
throw new UserError(
"Error: must provide --service-account-key-file or --private-key."
);
}
args.privateKey = args.privateKey.replace(/\\n/g, "\n");
if (!args.r2AccessKeyId) {
throw new UserError("Error: must provide --r2-access-key-id.");
}
if (!args.r2SecretAccessKey) {
throw new UserError("Error: must provide --r2-secret-access-key.");
}
sippyConfig = {
source: {
provider: "gcs",
bucket: args.bucket,
clientEmail: args.clientEmail,
privateKey: args.privateKey
},
destination: {
provider: "r2",
accessKeyId: args.r2AccessKeyId,
secretAccessKey: args.r2SecretAccessKey
}
};
} else {
throw new UserError(
"Error: unrecognized provider. Possible options are AWS & GCS."
);
}
await putR2Sippy(
config,
accountId,
args.name,
sippyConfig,
args.jurisdiction
);
logger.log(`\u2728 Successfully enabled Sippy on the '${args.name}' bucket.`);
}
});
r2BucketSippyDisableCommand = createCommand({
metadata: {
description: "Disable Sippy on an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["name"],
args: {
name: {
describe: "The name of the bucket",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
await deleteR2Sippy(config, accountId, args.name, args.jurisdiction);
logger.log(`\u2728 Successfully disabled Sippy on the '${args.name}' bucket.`);
}
});
r2BucketSippyGetCommand = createCommand({
metadata: {
description: "Check the status of Sippy on an R2 bucket",
status: "stable",
owner: "Product: R2"
},
positionalArgs: ["name"],
args: {
name: {
describe: "The name of the bucket",
type: "string",
demandOption: true
},
jurisdiction: {
describe: "The jurisdiction where the bucket exists",
alias: "J",
requiresArg: true,
type: "string"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
try {
const sippyConfig = await getR2Sippy(
config,
accountId,
args.name,
args.jurisdiction
);
logger.log("Sippy configuration:", sippyConfig);
} catch (e7) {
if (e7 instanceof APIError && "code" in e7 && e7.code === NO_SUCH_OBJECT_KEY) {
logger.log(
`No Sippy configuration found for the '${args.name}' bucket.`
);
} else {
throw e7;
}
}
}
});
}
});
// src/secrets-store/index.ts
var secretsStoreNamespace, secretsStoreStoreNamespace, secretsStoreSecretNamespace;
var init_secrets_store = __esm({
"src/secrets-store/index.ts"() {
init_import_meta_url();
init_create_command();
secretsStoreNamespace = createNamespace({
metadata: {
description: `\u{1F510} Manage the Secrets Store`,
status: "alpha",
owner: "Product: SSL"
}
});
secretsStoreStoreNamespace = createNamespace({
metadata: {
description: "\u{1F510} Manage Stores within the Secrets Store",
status: "alpha",
owner: "Product: SSL"
}
});
secretsStoreSecretNamespace = createNamespace({
metadata: {
description: "\u{1F510} Manage Secrets within the Secrets Store",
status: "alpha",
owner: "Product: SSL"
}
});
}
});
// src/secrets-store/client.ts
async function createStore(complianceConfig, accountId, body) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores`,
{
method: "POST",
body: JSON.stringify(body)
}
);
}
async function deleteStore(complianceConfig, accountId, storeId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}`,
{
method: "DELETE"
}
);
}
async function listStores(complianceConfig, accountId, urlParams) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores`,
{
method: "GET"
},
urlParams
);
}
async function listSecrets(complianceConfig, accountId, storeId, urlParams) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}/secrets`,
{
method: "GET"
},
urlParams
);
}
async function getSecret(complianceConfig, accountId, storeId, secretId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}/secrets/${secretId}`,
{
method: "GET"
}
);
}
async function createSecret(complianceConfig, accountId, storeId, body) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}/secrets`,
{
method: "POST",
body: JSON.stringify([body])
}
);
}
async function updateSecret(complianceConfig, accountId, storeId, secretId, body) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}/secrets/${secretId}`,
{
method: "PATCH",
body: JSON.stringify(body)
}
);
}
async function deleteSecret(complianceConfig, accountId, storeId, secretId) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}/secrets/${secretId}`,
{
method: "DELETE"
}
);
}
async function duplicateSecret(complianceConfig, accountId, storeId, secretId, body) {
return await fetchResult(
complianceConfig,
`/accounts/${accountId}/secrets_store/stores/${storeId}/secrets/${secretId}/duplicate`,
{
method: "POST",
body: JSON.stringify(body)
}
);
}
var init_client8 = __esm({
"src/secrets-store/client.ts"() {
init_import_meta_url();
init_cfetch();
__name(createStore, "createStore");
__name(deleteStore, "deleteStore");
__name(listStores, "listStores");
__name(listSecrets, "listSecrets");
__name(getSecret, "getSecret");
__name(createSecret, "createSecret");
__name(updateSecret, "updateSecret");
__name(deleteSecret, "deleteSecret");
__name(duplicateSecret, "duplicateSecret");
}
});
// src/secrets-store/commands.ts
async function usingLocalSecretsStoreSecretAPI(persistTo, config, storeId, secretName, closure) {
const persist = getLocalPersistencePath(persistTo, config);
const defaultPersistRoot = getDefaultPersistRoot(persist);
const mf = new import_miniflare17.Miniflare({
script: 'addEventListener("fetch", (e) => e.respondWith(new Response(null, { status: 404 })))',
defaultPersistRoot,
secretsStoreSecrets: {
SECRET: {
store_id: storeId,
secret_name: secretName
}
}
});
const namespace = await mf.getSecretsStoreSecretAPI("SECRET");
try {
return await closure(namespace());
} finally {
await mf.dispose();
}
}
var import_miniflare17, secretsStoreStoreCreateCommand, secretsStoreStoreDeleteCommand, secretsStoreStoreListCommand, secretsStoreSecretListCommand, secretsStoreSecretGetCommand, secretsStoreSecretCreateCommand, secretsStoreSecretUpdateCommand, secretsStoreSecretDeleteCommand, secretsStoreSecretDuplicateCommand;
var init_commands7 = __esm({
"src/secrets-store/commands.ts"() {
init_import_meta_url();
import_miniflare17 = require("miniflare");
init_create_command();
init_get_local_persistence_path();
init_miniflare();
init_dialogs();
init_errors();
init_logger();
init_user2();
init_std();
init_client8();
__name(usingLocalSecretsStoreSecretAPI, "usingLocalSecretsStoreSecretAPI");
secretsStoreStoreCreateCommand = createCommand({
metadata: {
description: "Create a store within an account",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["name"],
args: {
name: {
type: "string",
description: "Name of the store",
demandOption: true,
requiresArg: true
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
}
},
async handler(args, { config }) {
let store;
logger.log(`\u{1F510} Creating store... (Name: ${args.name})`);
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
store = await createStore(config, accountId, { name: args.name });
} else {
throw new UserError(
"Local secrets stores are automatically created for you on use. To create a Secrets Store on your account, use the --remote flag.",
{ telemetryMessage: true }
);
}
logger.log(`\u2705 Created store! (Name: ${args.name}, ID: ${store.id})`);
}
});
secretsStoreStoreDeleteCommand = createCommand({
metadata: {
description: "Delete a store within an account",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
type: "string",
description: "ID of the store",
demandOption: true,
requiresArg: true
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
}
},
async handler(args, { config }) {
logger.log(`\u{1F510} Deleting store... (Name: ${args.storeId})`);
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
await deleteStore(config, accountId, args.storeId);
} else {
throw new UserError(
"This command is not supported in local mode. Use `wrangler <cmd> --remote` to delete a Secrets Store from your account.",
{ telemetryMessage: true }
);
}
logger.log(`\u2705 Deleted store! (ID: ${args.storeId})`);
}
});
secretsStoreStoreListCommand = createCommand({
metadata: {
description: "List stores within an account",
status: "alpha",
owner: "Product: SSL"
},
args: {
page: {
describe: 'Page number of stores listing results, can configure page size using "per-page"',
type: "number",
default: 1
},
"per-page": {
describe: "Number of stores to show per page",
type: "number",
default: 10
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
}
},
async handler(args, { config }) {
const urlParams = new URLSearchParams();
urlParams.set("per_page", args.perPage.toString());
urlParams.set("page", args.page.toString());
logger.log(`\u{1F510} Listing stores...`);
let stores;
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
stores = await listStores(config, accountId, urlParams);
} else {
throw new UserError(
"This command is not supported in local mode. Use `wrangler <cmd> --remote` to list Secrets Stores on your account.",
{ telemetryMessage: true }
);
}
if (stores.length === 0) {
throw new UserError("List request returned no stores.", {
telemetryMessage: true
});
} else {
const prettierStores = stores.sort((a5, b6) => a5.name.localeCompare(b6.name)).map((store) => ({
Name: store.name,
ID: store.id,
AccountID: store.account_id,
Created: new Date(store.created).toLocaleString(),
Modified: new Date(store.modified).toLocaleString()
}));
logger.table(prettierStores);
}
}
});
secretsStoreSecretListCommand = createCommand({
metadata: {
description: "List secrets within a store",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
describe: "ID of the store in which to list secrets",
type: "string",
demandOption: true,
requiresArg: true
},
page: {
describe: 'Page number of secrets listing results, can configure page size using "per-page"',
type: "number",
default: 1
},
"per-page": {
describe: "Number of secrets to show per page",
type: "number",
default: 10
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
const urlParams = new URLSearchParams();
urlParams.set("per_page", args.perPage.toString());
urlParams.set("page", args.page.toString());
logger.log(
`\u{1F510} Listing secrets... (store-id: ${args.storeId}, page: ${args.page}, per-page: ${args.perPage})`
);
let secrets;
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
secrets = await listSecrets(config, accountId, args.storeId, urlParams);
} else {
secrets = (await usingLocalSecretsStoreSecretAPI(
args.persistTo,
config,
args.storeId,
"",
(api) => api.list()
)).map((key) => ({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: key.metadata.uuid,
store_id: args.storeId,
name: key.name,
comment: "",
scopes: [],
created: (/* @__PURE__ */ new Date()).toISOString(),
modified: (/* @__PURE__ */ new Date()).toISOString(),
status: "active"
}));
}
if (secrets.length === 0) {
throw new FatalError("List request returned no secrets.", 1, {
telemetryMessage: true
});
} else {
const prettierSecrets = secrets.map((secret) => ({
Name: secret.name,
ID: secret.id,
Comment: secret.comment,
Scopes: secret.scopes.join(", "),
Status: secret.status === "active" ? "active " : "pending",
Created: new Date(secret.created).toLocaleString(),
Modified: new Date(secret.modified).toLocaleString()
}));
logger.table(prettierSecrets);
}
}
});
secretsStoreSecretGetCommand = createCommand({
metadata: {
description: "Get a secret within a store",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
describe: "ID of the store in which the secret resides",
type: "string",
demandOption: true,
requiresArg: true
},
"secret-id": {
describe: "ID of the secret to retrieve",
type: "string",
demandOption: true,
requiresArg: true
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
logger.log(`\u{1F510} Getting secret... (ID: ${args.secretId})`);
let secret;
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
secret = await getSecret(config, accountId, args.storeId, args.secretId);
} else {
const name2 = await usingLocalSecretsStoreSecretAPI(
args.persistTo,
config,
args.storeId,
"",
(api) => api.get(args.secretId)
);
secret = {
id: args.secretId,
store_id: args.storeId,
name: name2,
comment: "",
scopes: [],
created: (/* @__PURE__ */ new Date()).toISOString(),
modified: (/* @__PURE__ */ new Date()).toISOString(),
status: "active"
};
}
const prettierSecret = [
{
Name: secret.name,
ID: secret.id,
StoreID: secret.store_id,
Comment: secret.comment,
Scopes: secret.scopes.join(", "),
Status: secret.status === "active" ? "active " : "pending",
Created: new Date(secret.created).toLocaleString(),
Modified: new Date(secret.modified).toLocaleString()
}
];
logger.table(prettierSecret);
}
});
secretsStoreSecretCreateCommand = createCommand({
metadata: {
description: "Create a secret within a store",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
describe: "ID of the store in which the secret resides",
type: "string",
requiresArg: true,
demandOption: true
},
name: {
describe: "Name of the secret",
type: "string",
requiresArg: true,
demandOption: true
},
value: {
describe: "Value of the secret (Note: Only for testing. Not secure as this will leave secret value in plain-text in terminal history, exclude this flag and use automatic prompt instead)",
type: "string"
},
scopes: {
describe: 'Scopes for the secret (comma-separated list of scopes eg:"workers")',
type: "string",
requiresArg: true,
demandOption: true
},
comment: {
describe: "Comment for the secret",
type: "string"
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
let secretValue = "";
if (!args.value) {
const isInteractive3 = process.stdin.isTTY;
secretValue = trimTrailingWhitespace(
isInteractive3 ? await prompt("Enter a secret value:", { isSecret: true }) : await readFromStdin()
);
} else {
secretValue = args.value;
}
if (!secretValue) {
throw new UserError("Need to pass in a value when creating a secret.");
}
logger.log(
`
\u{1F510} Creating secret... (Name: ${args.name}, Value: REDACTED, Scopes: ${args.scopes}, Comment: ${args.comment})`
);
let secrets;
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
secrets = await createSecret(config, accountId, args.storeId, {
name: args.name,
value: secretValue,
scopes: args.scopes.split(","),
comment: args.comment
});
} else {
secrets = [
await usingLocalSecretsStoreSecretAPI(
args.persistTo,
config,
args.storeId,
args.name,
(api) => api.create(secretValue)
)
].map((id) => ({
id,
store_id: args.storeId,
name: args.name,
comment: args.comment ?? "",
scopes: args.scopes.split(","),
created: (/* @__PURE__ */ new Date()).toISOString(),
modified: (/* @__PURE__ */ new Date()).toISOString(),
status: "pending"
}));
}
if (secrets.length === 0) {
throw new FatalError("Failed to create a secret.", 1, {
telemetryMessage: true
});
}
const secret = secrets[0];
logger.log(`\u2705 Created secret! (ID: ${secret.id})`);
const prettierSecret = [
{
Name: secret.name,
ID: secret.id,
StoreID: secret.store_id,
Comment: secret.comment,
Scopes: secret.scopes.join(", "),
Status: secret.status,
Created: new Date(secret.created).toLocaleString(),
Modified: new Date(secret.modified).toLocaleString()
}
];
logger.table(prettierSecret);
}
});
secretsStoreSecretUpdateCommand = createCommand({
metadata: {
description: "Update a secret within a store",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
describe: "ID of the store in which the secret resides",
type: "string",
requiresArg: true,
demandOption: true
},
"secret-id": {
describe: "ID of the secret to update",
type: "string",
requiresArg: true,
demandOption: true
},
value: {
describe: "Updated value of the secret (Note: Only for testing. Not secure as this will leave secret value in plain-text in terminal history, exclude this flag and use automatic prompt instead)",
type: "string"
},
scopes: {
describe: 'Updated scopes for the secret (comma-separated list of scopes eg:"workers")',
type: "string"
},
comment: {
describe: "Updated comment for the secret",
type: "string"
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
let secretValue = "";
if (!args.value) {
const confirmValueUpdate = await confirm(
"Do you want to update the secret value?",
{ defaultValue: false }
);
if (confirmValueUpdate) {
const isInteractive3 = process.stdin.isTTY;
secretValue = trimTrailingWhitespace(
isInteractive3 ? await prompt("Enter a secret value:", { isSecret: true }) : await readFromStdin()
);
}
} else {
secretValue = args.value;
}
if (!secretValue && !args.scopes && !args.comment) {
throw new UserError(
"Need to pass in a new field using `--value`, `--scopes`, or `--comment` to update a secret."
);
}
logger.log(`\u{1F510} Updating secret... (ID: ${args.secretId})`);
let secret;
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
secret = await updateSecret(
config,
accountId,
args.storeId,
args.secretId,
{
...secretValue && { value: secretValue },
...args.scopes && { scopes: args.scopes.split(",") },
...args.comment && { comment: args.comment }
}
);
} else {
const name2 = await usingLocalSecretsStoreSecretAPI(
args.persistTo,
config,
args.storeId,
"",
(api) => api.update(secretValue, args.secretId)
);
secret = {
id: args.secretId,
store_id: args.storeId,
name: name2,
comment: "",
scopes: [],
created: (/* @__PURE__ */ new Date()).toISOString(),
modified: (/* @__PURE__ */ new Date()).toISOString(),
status: "active"
};
}
logger.log(`\u2705 Updated secret! (ID: ${secret.id})`);
const prettierSecret = [
{
Name: secret.name,
ID: secret.id,
StoreID: secret.store_id,
Comment: secret.comment,
Scopes: secret.scopes.join(", "),
Status: secret.status,
Created: new Date(secret.created).toLocaleString(),
Modified: new Date(secret.modified).toLocaleString()
}
];
logger.table(prettierSecret);
}
});
secretsStoreSecretDeleteCommand = createCommand({
metadata: {
description: "Delete a secret within a store",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
describe: "ID of the store in which the secret resides",
type: "string",
requiresArg: true,
demandOption: true
},
"secret-id": {
describe: "ID of the secret to delete",
type: "string",
requiresArg: true,
demandOption: true
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
logger.log(`\u{1F510} Deleting secret... (ID: ${args.secretId})`);
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
await deleteSecret(config, accountId, args.storeId, args.secretId);
} else {
await usingLocalSecretsStoreSecretAPI(
args.persistTo,
config,
args.storeId,
"",
(api) => api.delete(args.secretId)
);
}
logger.log(`\u2705 Deleted secret! (ID: ${args.secretId})`);
}
});
secretsStoreSecretDuplicateCommand = createCommand({
metadata: {
description: "Duplicate a secret within a store",
status: "alpha",
owner: "Product: SSL"
},
positionalArgs: ["store-id"],
args: {
"store-id": {
describe: "ID of the store in which the secret resides",
type: "string",
requiresArg: true,
demandOption: true
},
"secret-id": {
describe: "ID of the secret to duplicate the secret value of",
type: "string",
requiresArg: true,
demandOption: true
},
name: {
describe: "Name of the new secret",
type: "string",
requiresArg: true,
demandOption: true
},
scopes: {
describe: "Scopes for the new secret",
type: "string",
requiresArg: true,
demandOption: true
},
comment: {
describe: "Comment for the new secret",
type: "string"
},
remote: {
type: "boolean",
description: "Execute command against remote Secrets Store",
default: false
},
"persist-to": {
type: "string",
describe: "Directory for local persistence"
}
},
async handler(args, { config }) {
logger.log(`\u{1F510} Duplicating secret... (ID: ${args.secretId})`);
let duplicatedSecret;
if (args.remote) {
const accountId = config.account_id || await getAccountId(config);
duplicatedSecret = await duplicateSecret(
config,
accountId,
args.storeId,
args.secretId,
{
name: args.name,
scopes: args.scopes.split(","),
comment: args.comment || ""
}
);
} else {
const duplicatedSecretId = await usingLocalSecretsStoreSecretAPI(
args.persistTo,
config,
args.storeId,
"",
(api) => api.duplicate(args.secretId, args.name)
);
duplicatedSecret = {
id: duplicatedSecretId,
store_id: args.storeId,
name: args.name,
comment: "",
scopes: [],
created: (/* @__PURE__ */ new Date()).toISOString(),
modified: (/* @__PURE__ */ new Date()).toISOString(),
status: "active"
};
}
logger.log(`\u2705 Duplicated secret! (ID: ${duplicatedSecret.id})`);
const prettierSecret = [
{
Name: duplicatedSecret.name,
ID: duplicatedSecret.id,
StoreID: duplicatedSecret.store_id,
Comment: duplicatedSecret.comment,
Scopes: duplicatedSecret.scopes.join(", "),
Status: duplicatedSecret.status,
Created: new Date(duplicatedSecret.created).toLocaleString(),
Modified: new Date(duplicatedSecret.modified).toLocaleString()
}
];
logger.table(prettierSecret);
}
});
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/is.js
function isError(wat) {
switch (objectToString.call(wat)) {
case "[object Error]":
case "[object Exception]":
case "[object DOMException]":
return true;
default:
return isInstanceOf(wat, Error);
}
}
function isBuiltin(wat, className) {
return objectToString.call(wat) === `[object ${className}]`;
}
function isString3(wat) {
return isBuiltin(wat, "String");
}
function isPrimitive(wat) {
return wat === null || typeof wat !== "object" && typeof wat !== "function";
}
function isPlainObject(wat) {
return isBuiltin(wat, "Object");
}
function isEvent(wat) {
return typeof Event !== "undefined" && isInstanceOf(wat, Event);
}
function isElement(wat) {
return typeof Element !== "undefined" && isInstanceOf(wat, Element);
}
function isRegExp(wat) {
return isBuiltin(wat, "RegExp");
}
function isThenable(wat) {
return Boolean(wat && wat.then && typeof wat.then === "function");
}
function isSyntheticEvent(wat) {
return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
}
function isNaN2(wat) {
return typeof wat === "number" && wat !== wat;
}
function isInstanceOf(wat, base) {
try {
return wat instanceof base;
} catch (_e2) {
return false;
}
}
function isVueViewModel(wat) {
return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue));
}
var objectToString;
var init_is = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/is.js"() {
init_import_meta_url();
objectToString = Object.prototype.toString;
__name(isError, "isError");
__name(isBuiltin, "isBuiltin");
__name(isString3, "isString");
__name(isPrimitive, "isPrimitive");
__name(isPlainObject, "isPlainObject");
__name(isEvent, "isEvent");
__name(isElement, "isElement");
__name(isRegExp, "isRegExp");
__name(isThenable, "isThenable");
__name(isSyntheticEvent, "isSyntheticEvent");
__name(isNaN2, "isNaN");
__name(isInstanceOf, "isInstanceOf");
__name(isVueViewModel, "isVueViewModel");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/string.js
function truncate3(str, max = 0) {
if (typeof str !== "string" || max === 0) {
return str;
}
return str.length <= max ? str : `${str.slice(0, max)}...`;
}
function snipLine(line, colno) {
let newLine = line;
const lineLength = newLine.length;
if (lineLength <= 150) {
return newLine;
}
if (colno > lineLength) {
colno = lineLength;
}
let start = Math.max(colno - 60, 0);
if (start < 5) {
start = 0;
}
let end = Math.min(start + 140, lineLength);
if (end > lineLength - 5) {
end = lineLength;
}
if (end === lineLength) {
start = Math.max(end - 140, 0);
}
newLine = newLine.slice(start, end);
if (start > 0) {
newLine = `'{snip} ${newLine}`;
}
if (end < lineLength) {
newLine += " {snip}";
}
return newLine;
}
function isMatchingPattern(value, pattern, requireExactStringMatch = false) {
if (!isString3(value)) {
return false;
}
if (isRegExp(pattern)) {
return pattern.test(value);
}
if (isString3(pattern)) {
return requireExactStringMatch ? value === pattern : value.includes(pattern);
}
return false;
}
function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {
return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch));
}
var init_string = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/string.js"() {
init_import_meta_url();
init_is();
__name(truncate3, "truncate");
__name(snipLine, "snipLine");
__name(isMatchingPattern, "isMatchingPattern");
__name(stringMatchesSomePattern, "stringMatchesSomePattern");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/aggregate-errors.js
function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser2, maxValueLimit = 250, key, limit, event, hint) {
if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
return;
}
const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0;
if (originalException) {
event.exception.values = truncateAggregateExceptions(
aggregateExceptionsFromError(
exceptionFromErrorImplementation,
parser2,
limit,
hint.originalException,
key,
event.exception.values,
originalException,
0
),
maxValueLimit
);
}
}
function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser2, limit, error2, key, prevExceptions, exception, exceptionId) {
if (prevExceptions.length >= limit + 1) {
return prevExceptions;
}
let newExceptions = [...prevExceptions];
if (isInstanceOf(error2[key], Error)) {
applyExceptionGroupFieldsForParentException(exception, exceptionId);
const newException = exceptionFromErrorImplementation(parser2, error2[key]);
const newExceptionId = newExceptions.length;
applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);
newExceptions = aggregateExceptionsFromError(
exceptionFromErrorImplementation,
parser2,
limit,
error2[key],
key,
[newException, ...newExceptions],
newException,
newExceptionId
);
}
if (Array.isArray(error2.errors)) {
error2.errors.forEach((childError, i5) => {
if (isInstanceOf(childError, Error)) {
applyExceptionGroupFieldsForParentException(exception, exceptionId);
const newException = exceptionFromErrorImplementation(parser2, childError);
const newExceptionId = newExceptions.length;
applyExceptionGroupFieldsForChildException(newException, `errors[${i5}]`, newExceptionId, exceptionId);
newExceptions = aggregateExceptionsFromError(
exceptionFromErrorImplementation,
parser2,
limit,
childError,
key,
[newException, ...newExceptions],
newException,
newExceptionId
);
}
});
}
return newExceptions;
}
function applyExceptionGroupFieldsForParentException(exception, exceptionId) {
exception.mechanism = exception.mechanism || { type: "generic", handled: true };
exception.mechanism = {
...exception.mechanism,
is_exception_group: true,
exception_id: exceptionId
};
}
function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) {
exception.mechanism = exception.mechanism || { type: "generic", handled: true };
exception.mechanism = {
...exception.mechanism,
type: "chained",
source,
exception_id: exceptionId,
parent_id: parentId
};
}
function truncateAggregateExceptions(exceptions, maxValueLength) {
return exceptions.map((exception) => {
if (exception.value) {
exception.value = truncate3(exception.value, maxValueLength);
}
return exception;
});
}
var init_aggregate_errors = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/aggregate-errors.js"() {
init_import_meta_url();
init_is();
init_string();
__name(applyAggregateErrorsToEvent, "applyAggregateErrorsToEvent");
__name(aggregateExceptionsFromError, "aggregateExceptionsFromError");
__name(applyExceptionGroupFieldsForParentException, "applyExceptionGroupFieldsForParentException");
__name(applyExceptionGroupFieldsForChildException, "applyExceptionGroupFieldsForChildException");
__name(truncateAggregateExceptions, "truncateAggregateExceptions");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/worldwide.js
function isGlobalObj(obj) {
return obj && obj.Math == Math ? obj : void 0;
}
function getGlobalObject() {
return GLOBAL_OBJ;
}
function getGlobalSingleton(name2, creator, obj) {
const gbl = obj || GLOBAL_OBJ;
const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {};
const singleton = __SENTRY__[name2] || (__SENTRY__[name2] = creator());
return singleton;
}
var GLOBAL_OBJ;
var init_worldwide = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/worldwide.js"() {
init_import_meta_url();
__name(isGlobalObj, "isGlobalObj");
GLOBAL_OBJ = typeof globalThis == "object" && isGlobalObj(globalThis) || // eslint-disable-next-line no-restricted-globals
typeof window == "object" && isGlobalObj(window) || typeof self == "object" && isGlobalObj(self) || typeof global == "object" && isGlobalObj(global) || /* @__PURE__ */ function() {
return this;
}() || {};
__name(getGlobalObject, "getGlobalObject");
__name(getGlobalSingleton, "getGlobalSingleton");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/browser.js
function htmlTreeAsString(elem, options = {}) {
if (!elem) {
return "<unknown>";
}
try {
let currentElem = elem;
const MAX_TRAVERSE_HEIGHT = 5;
const out = [];
let height = 0;
let len = 0;
const separator = " > ";
const sepLength = separator.length;
let nextStr;
const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH;
while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = _htmlElementAsString(currentElem, keyAttrs);
if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) {
break;
}
out.push(nextStr);
len += nextStr.length;
currentElem = currentElem.parentNode;
}
return out.reverse().join(separator);
} catch (_oO) {
return "<unknown>";
}
}
function _htmlElementAsString(el, keyAttrs) {
const elem = el;
const out = [];
let className;
let classes;
let key;
let attr;
let i5;
if (!elem || !elem.tagName) {
return "";
}
out.push(elem.tagName.toLowerCase());
const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null;
if (keyAttrPairs && keyAttrPairs.length) {
keyAttrPairs.forEach((keyAttrPair) => {
out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
});
} else {
if (elem.id) {
out.push(`#${elem.id}`);
}
className = elem.className;
if (className && isString3(className)) {
classes = className.split(/\s+/);
for (i5 = 0; i5 < classes.length; i5++) {
out.push(`.${classes[i5]}`);
}
}
}
const allowedAttrs = ["aria-label", "type", "name", "title", "alt"];
for (i5 = 0; i5 < allowedAttrs.length; i5++) {
key = allowedAttrs[i5];
attr = elem.getAttribute(key);
if (attr) {
out.push(`[${key}="${attr}"]`);
}
}
return out.join("");
}
var WINDOW, DEFAULT_MAX_STRING_LENGTH;
var init_browser = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/browser.js"() {
init_import_meta_url();
init_is();
init_worldwide();
WINDOW = getGlobalObject();
DEFAULT_MAX_STRING_LENGTH = 80;
__name(htmlTreeAsString, "htmlTreeAsString");
__name(_htmlElementAsString, "_htmlElementAsString");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/debug-build.js
var DEBUG_BUILD;
var init_debug_build = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/debug-build.js"() {
init_import_meta_url();
DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/logger.js
function consoleSandbox(callback) {
if (!("console" in GLOBAL_OBJ)) {
return callback();
}
const console2 = GLOBAL_OBJ.console;
const wrappedFuncs = {};
const wrappedLevels = Object.keys(originalConsoleMethods);
wrappedLevels.forEach((level) => {
const originalConsoleMethod = originalConsoleMethods[level];
wrappedFuncs[level] = console2[level];
console2[level] = originalConsoleMethod;
});
try {
return callback();
} finally {
wrappedLevels.forEach((level) => {
console2[level] = wrappedFuncs[level];
});
}
}
function makeLogger() {
let enabled = false;
const logger4 = {
enable: /* @__PURE__ */ __name(() => {
enabled = true;
}, "enable"),
disable: /* @__PURE__ */ __name(() => {
enabled = false;
}, "disable"),
isEnabled: /* @__PURE__ */ __name(() => enabled, "isEnabled")
};
if (DEBUG_BUILD) {
CONSOLE_LEVELS.forEach((name2) => {
logger4[name2] = (...args) => {
if (enabled) {
consoleSandbox(() => {
GLOBAL_OBJ.console[name2](`${PREFIX}[${name2}]:`, ...args);
});
}
};
});
} else {
CONSOLE_LEVELS.forEach((name2) => {
logger4[name2] = () => void 0;
});
}
return logger4;
}
var PREFIX, CONSOLE_LEVELS, originalConsoleMethods, logger3;
var init_logger3 = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/logger.js"() {
init_import_meta_url();
init_debug_build();
init_worldwide();
PREFIX = "Sentry Logger ";
CONSOLE_LEVELS = [
"debug",
"info",
"warn",
"error",
"log",
"assert",
"trace"
];
originalConsoleMethods = {};
__name(consoleSandbox, "consoleSandbox");
__name(makeLogger, "makeLogger");
logger3 = makeLogger();
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/dsn.js
function isValidProtocol(protocol) {
return protocol === "http" || protocol === "https";
}
function dsnToString(dsn, withPassword = false) {
const { host, path: path72, pass: pass2, port, projectId, protocol, publicKey } = dsn;
return `${protocol}://${publicKey}${withPassword && pass2 ? `:${pass2}` : ""}@${host}${port ? `:${port}` : ""}/${path72 ? `${path72}/` : path72}${projectId}`;
}
function dsnFromString(str) {
const match2 = DSN_REGEX.exec(str);
if (!match2) {
consoleSandbox(() => {
console.error(`Invalid Sentry Dsn: ${str}`);
});
return void 0;
}
const [protocol, publicKey, pass2 = "", host, port = "", lastPath] = match2.slice(1);
let path72 = "";
let projectId = lastPath;
const split = projectId.split("/");
if (split.length > 1) {
path72 = split.slice(0, -1).join("/");
projectId = split.pop();
}
if (projectId) {
const projectMatch = projectId.match(/^\d+/);
if (projectMatch) {
projectId = projectMatch[0];
}
}
return dsnFromComponents({ host, pass: pass2, path: path72, projectId, port, protocol, publicKey });
}
function dsnFromComponents(components) {
return {
protocol: components.protocol,
publicKey: components.publicKey || "",
pass: components.pass || "",
host: components.host,
port: components.port || "",
path: components.path || "",
projectId: components.projectId
};
}
function validateDsn(dsn) {
if (!DEBUG_BUILD) {
return true;
}
const { port, projectId, protocol } = dsn;
const requiredComponents = ["protocol", "publicKey", "host", "projectId"];
const hasMissingRequiredComponent = requiredComponents.find((component) => {
if (!dsn[component]) {
logger3.error(`Invalid Sentry Dsn: ${component} missing`);
return true;
}
return false;
});
if (hasMissingRequiredComponent) {
return false;
}
if (!projectId.match(/^\d+$/)) {
logger3.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
return false;
}
if (!isValidProtocol(protocol)) {
logger3.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
return false;
}
if (port && isNaN(parseInt(port, 10))) {
logger3.error(`Invalid Sentry Dsn: Invalid port ${port}`);
return false;
}
return true;
}
function makeDsn(from) {
const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from);
if (!components || !validateDsn(components)) {
return void 0;
}
return components;
}
var DSN_REGEX;
var init_dsn = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/dsn.js"() {
init_import_meta_url();
init_debug_build();
init_logger3();
DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
__name(isValidProtocol, "isValidProtocol");
__name(dsnToString, "dsnToString");
__name(dsnFromString, "dsnFromString");
__name(dsnFromComponents, "dsnFromComponents");
__name(validateDsn, "validateDsn");
__name(makeDsn, "makeDsn");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/error.js
var SentryError;
var init_error3 = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/error.js"() {
init_import_meta_url();
SentryError = class extends Error {
static {
__name(this, "SentryError");
}
/** Display name of this error instance. */
constructor(message, logLevel = "warn") {
super(message);
this.message = message;
this.name = new.target.prototype.constructor.name;
Object.setPrototypeOf(this, new.target.prototype);
this.logLevel = logLevel;
}
};
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/object.js
function fill(source, name2, replacementFactory) {
if (!(name2 in source)) {
return;
}
const original = source[name2];
const wrapped = replacementFactory(original);
if (typeof wrapped === "function") {
markFunctionWrapped(wrapped, original);
}
source[name2] = wrapped;
}
function addNonEnumerableProperty(obj, name2, value) {
try {
Object.defineProperty(obj, name2, {
// enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
value,
writable: true,
configurable: true
});
} catch (o_O) {
DEBUG_BUILD && logger3.log(`Failed to add non-enumerable property "${name2}" to object`, obj);
}
}
function markFunctionWrapped(wrapped, original) {
try {
const proto2 = original.prototype || {};
wrapped.prototype = original.prototype = proto2;
addNonEnumerableProperty(wrapped, "__sentry_original__", original);
} catch (o_O) {
}
}
function getOriginalFunction(func) {
return func.__sentry_original__;
}
function urlEncode(object) {
return Object.keys(object).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`).join("&");
}
function convertToPlainObject(value) {
if (isError(value)) {
return {
message: value.message,
name: value.name,
stack: value.stack,
...getOwnProperties(value)
};
} else if (isEvent(value)) {
const newObj = {
type: value.type,
target: serializeEventTarget(value.target),
currentTarget: serializeEventTarget(value.currentTarget),
...getOwnProperties(value)
};
if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) {
newObj.detail = value.detail;
}
return newObj;
} else {
return value;
}
}
function serializeEventTarget(target) {
try {
return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
} catch (_oO) {
return "<unknown>";
}
}
function getOwnProperties(obj) {
if (typeof obj === "object" && obj !== null) {
const extractedProps = {};
for (const property in obj) {
if (Object.prototype.hasOwnProperty.call(obj, property)) {
extractedProps[property] = obj[property];
}
}
return extractedProps;
} else {
return {};
}
}
function extractExceptionKeysForMessage(exception, maxLength = 40) {
const keys = Object.keys(convertToPlainObject(exception));
keys.sort();
if (!keys.length) {
return "[object has no keys]";
}
if (keys[0].length >= maxLength) {
return truncate3(keys[0], maxLength);
}
for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
const serialized = keys.slice(0, includedKeys).join(", ");
if (serialized.length > maxLength) {
continue;
}
if (includedKeys === keys.length) {
return serialized;
}
return truncate3(serialized, maxLength);
}
return "";
}
function dropUndefinedKeys(inputValue) {
const memoizationMap = /* @__PURE__ */ new Map();
return _dropUndefinedKeys(inputValue, memoizationMap);
}
function _dropUndefinedKeys(inputValue, memoizationMap) {
if (isPlainObject(inputValue)) {
const memoVal = memoizationMap.get(inputValue);
if (memoVal !== void 0) {
return memoVal;
}
const returnValue = {};
memoizationMap.set(inputValue, returnValue);
for (const key of Object.keys(inputValue)) {
if (typeof inputValue[key] !== "undefined") {
returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
}
}
return returnValue;
}
if (Array.isArray(inputValue)) {
const memoVal = memoizationMap.get(inputValue);
if (memoVal !== void 0) {
return memoVal;
}
const returnValue = [];
memoizationMap.set(inputValue, returnValue);
inputValue.forEach((item) => {
returnValue.push(_dropUndefinedKeys(item, memoizationMap));
});
return returnValue;
}
return inputValue;
}
var init_object2 = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/object.js"() {
init_import_meta_url();
init_browser();
init_debug_build();
init_is();
init_logger3();
init_string();
__name(fill, "fill");
__name(addNonEnumerableProperty, "addNonEnumerableProperty");
__name(markFunctionWrapped, "markFunctionWrapped");
__name(getOriginalFunction, "getOriginalFunction");
__name(urlEncode, "urlEncode");
__name(convertToPlainObject, "convertToPlainObject");
__name(serializeEventTarget, "serializeEventTarget");
__name(getOwnProperties, "getOwnProperties");
__name(extractExceptionKeysForMessage, "extractExceptionKeysForMessage");
__name(dropUndefinedKeys, "dropUndefinedKeys");
__name(_dropUndefinedKeys, "_dropUndefinedKeys");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/node-stack-trace.js
function filenameIsInApp(filename, isNative = false) {
const isInternal = isNative || filename && // It's not internal if it's an absolute linux path
!filename.startsWith("/") && // It's not internal if it's an absolute windows path
!filename.includes(":\\") && // It's not internal if the path is starting with a dot
!filename.startsWith(".") && // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
!filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
return !isInternal && filename !== void 0 && !filename.includes("node_modules/");
}
function node(getModule) {
const FILENAME_MATCH = /^\s*[-]{4,}$/;
const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
return (line) => {
const lineMatch = line.match(FULL_MATCH);
if (lineMatch) {
let object;
let method;
let functionName;
let typeName;
let methodName;
if (lineMatch[1]) {
functionName = lineMatch[1];
let methodStart = functionName.lastIndexOf(".");
if (functionName[methodStart - 1] === ".") {
methodStart--;
}
if (methodStart > 0) {
object = functionName.slice(0, methodStart);
method = functionName.slice(methodStart + 1);
const objectEnd = object.indexOf(".Module");
if (objectEnd > 0) {
functionName = functionName.slice(objectEnd + 1);
object = object.slice(0, objectEnd);
}
}
typeName = void 0;
}
if (method) {
typeName = object;
methodName = method;
}
if (method === "<anonymous>") {
methodName = void 0;
functionName = void 0;
}
if (functionName === void 0) {
methodName = methodName || "<anonymous>";
functionName = typeName ? `${typeName}.${methodName}` : methodName;
}
let filename = lineMatch[2] && lineMatch[2].startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
const isNative = lineMatch[5] === "native";
if (!filename && lineMatch[5] && !isNative) {
filename = lineMatch[5];
}
return {
filename,
module: getModule ? getModule(filename) : void 0,
function: functionName,
lineno: parseInt(lineMatch[3], 10) || void 0,
colno: parseInt(lineMatch[4], 10) || void 0,
in_app: filenameIsInApp(filename, isNative)
};
}
if (line.match(FILENAME_MATCH)) {
return {
filename: line
};
}
return void 0;
};
}
var init_node_stack_trace = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/node-stack-trace.js"() {
init_import_meta_url();
__name(filenameIsInApp, "filenameIsInApp");
__name(node, "node");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/stacktrace.js
function createStackParser(...parsers) {
const sortedParsers = parsers.sort((a5, b6) => a5[0] - b6[0]).map((p6) => p6[1]);
return (stack, skipFirst = 0) => {
const frames = [];
const lines = stack.split("\n");
for (let i5 = skipFirst; i5 < lines.length; i5++) {
const line = lines[i5];
if (line.length > 1024) {
continue;
}
const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
if (cleanedLine.match(/\S*Error: /)) {
continue;
}
for (const parser2 of sortedParsers) {
const frame = parser2(cleanedLine);
if (frame) {
frames.push(frame);
break;
}
}
if (frames.length >= STACKTRACE_FRAME_LIMIT) {
break;
}
}
return stripSentryFramesAndReverse(frames);
};
}
function stackParserFromStackParserOptions(stackParser) {
if (Array.isArray(stackParser)) {
return createStackParser(...stackParser);
}
return stackParser;
}
function stripSentryFramesAndReverse(stack) {
if (!stack.length) {
return [];
}
const localStack = Array.from(stack);
if (/sentryWrapped/.test(localStack[localStack.length - 1].function || "")) {
localStack.pop();
}
localStack.reverse();
if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) {
localStack.pop();
if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) {
localStack.pop();
}
}
return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
...frame,
filename: frame.filename || localStack[localStack.length - 1].filename,
function: frame.function || "?"
}));
}
function getFunctionName(fn2) {
try {
if (!fn2 || typeof fn2 !== "function") {
return defaultFunctionName;
}
return fn2.name || defaultFunctionName;
} catch (e7) {
return defaultFunctionName;
}
}
function nodeStackLineParser(getModule) {
return [90, node(getModule)];
}
var STACKTRACE_FRAME_LIMIT, WEBPACK_ERROR_REGEXP, STRIP_FRAME_REGEXP, defaultFunctionName;
var init_stacktrace = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/stacktrace.js"() {
init_import_meta_url();
init_node_stack_trace();
STACKTRACE_FRAME_LIMIT = 50;
WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
STRIP_FRAME_REGEXP = /captureMessage|captureException/;
__name(createStackParser, "createStackParser");
__name(stackParserFromStackParserOptions, "stackParserFromStackParserOptions");
__name(stripSentryFramesAndReverse, "stripSentryFramesAndReverse");
defaultFunctionName = "<anonymous>";
__name(getFunctionName, "getFunctionName");
__name(nodeStackLineParser, "nodeStackLineParser");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/_handlers.js
function addHandler(type, handler) {
handlers[type] = handlers[type] || [];
handlers[type].push(handler);
}
function maybeInstrument(type, instrumentFn) {
if (!instrumented[type]) {
instrumentFn();
instrumented[type] = true;
}
}
function triggerHandlers(type, data) {
const typeHandlers = type && handlers[type];
if (!typeHandlers) {
return;
}
for (const handler of typeHandlers) {
try {
handler(data);
} catch (e7) {
DEBUG_BUILD && logger3.error(
`Error while triggering instrumentation handler.
Type: ${type}
Name: ${getFunctionName(handler)}
Error:`,
e7
);
}
}
}
var handlers, instrumented;
var init_handlers = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/_handlers.js"() {
init_import_meta_url();
init_debug_build();
init_logger3();
init_stacktrace();
handlers = {};
instrumented = {};
__name(addHandler, "addHandler");
__name(maybeInstrument, "maybeInstrument");
__name(triggerHandlers, "triggerHandlers");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/console.js
function addConsoleInstrumentationHandler(handler) {
const type = "console";
addHandler(type, handler);
maybeInstrument(type, instrumentConsole);
}
function instrumentConsole() {
if (!("console" in GLOBAL_OBJ)) {
return;
}
CONSOLE_LEVELS.forEach(function(level) {
if (!(level in GLOBAL_OBJ.console)) {
return;
}
fill(GLOBAL_OBJ.console, level, function(originalConsoleMethod) {
originalConsoleMethods[level] = originalConsoleMethod;
return function(...args) {
const handlerData = { args, level };
triggerHandlers("console", handlerData);
const log2 = originalConsoleMethods[level];
log2 && log2.apply(GLOBAL_OBJ.console, args);
};
});
});
}
var init_console = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/console.js"() {
init_import_meta_url();
init_logger3();
init_object2();
init_worldwide();
init_handlers();
__name(addConsoleInstrumentationHandler, "addConsoleInstrumentationHandler");
__name(instrumentConsole, "instrumentConsole");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/misc.js
function uuid4() {
const gbl = GLOBAL_OBJ;
const crypto8 = gbl.crypto || gbl.msCrypto;
let getRandomByte = /* @__PURE__ */ __name(() => Math.random() * 16, "getRandomByte");
try {
if (crypto8 && crypto8.randomUUID) {
return crypto8.randomUUID().replace(/-/g, "");
}
if (crypto8 && crypto8.getRandomValues) {
getRandomByte = /* @__PURE__ */ __name(() => crypto8.getRandomValues(new Uint8Array(1))[0], "getRandomByte");
}
} catch (_4) {
}
return ("10000000100040008000" + 1e11).replace(
/[018]/g,
(c6) => (
// eslint-disable-next-line no-bitwise
(c6 ^ (getRandomByte() & 15) >> c6 / 4).toString(16)
)
);
}
function getFirstException(event) {
return event.exception && event.exception.values ? event.exception.values[0] : void 0;
}
function getEventDescription(event) {
const { message, event_id: eventId } = event;
if (message) {
return message;
}
const firstException = getFirstException(event);
if (firstException) {
if (firstException.type && firstException.value) {
return `${firstException.type}: ${firstException.value}`;
}
return firstException.type || firstException.value || eventId || "<unknown>";
}
return eventId || "<unknown>";
}
function addExceptionTypeValue(event, value, type) {
const exception = event.exception = event.exception || {};
const values = exception.values = exception.values || [];
const firstException = values[0] = values[0] || {};
if (!firstException.value) {
firstException.value = value || "";
}
if (!firstException.type) {
firstException.type = type || "Error";
}
}
function addExceptionMechanism(event, newMechanism) {
const firstException = getFirstException(event);
if (!firstException) {
return;
}
const defaultMechanism = { type: "generic", handled: true };
const currentMechanism = firstException.mechanism;
firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
if (newMechanism && "data" in newMechanism) {
const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data };
firstException.mechanism.data = mergedData;
}
}
function parseSemver(input) {
const match2 = input.match(SEMVER_REGEXP) || [];
const major = parseInt(match2[1], 10);
const minor = parseInt(match2[2], 10);
const patch = parseInt(match2[3], 10);
return {
buildmetadata: match2[5],
major: isNaN(major) ? void 0 : major,
minor: isNaN(minor) ? void 0 : minor,
patch: isNaN(patch) ? void 0 : patch,
prerelease: match2[4]
};
}
function addContextToFrame(lines, frame, linesOfContext = 5) {
if (frame.lineno === void 0) {
return;
}
const maxLines = lines.length;
const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);
frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => snipLine(line, 0));
frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);
frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => snipLine(line, 0));
}
function checkOrSetAlreadyCaught(exception) {
if (exception && exception.__sentry_captured__) {
return true;
}
try {
addNonEnumerableProperty(exception, "__sentry_captured__", true);
} catch (err) {
}
return false;
}
function arrayify(maybeArray) {
return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
}
var SEMVER_REGEXP;
var init_misc = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/misc.js"() {
init_import_meta_url();
init_object2();
init_string();
init_worldwide();
__name(uuid4, "uuid4");
__name(getFirstException, "getFirstException");
__name(getEventDescription, "getEventDescription");
__name(addExceptionTypeValue, "addExceptionTypeValue");
__name(addExceptionMechanism, "addExceptionMechanism");
SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
__name(parseSemver, "parseSemver");
__name(addContextToFrame, "addContextToFrame");
__name(checkOrSetAlreadyCaught, "checkOrSetAlreadyCaught");
__name(arrayify, "arrayify");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/globalError.js
function addGlobalErrorInstrumentationHandler(handler) {
const type = "error";
addHandler(type, handler);
maybeInstrument(type, instrumentError);
}
function instrumentError() {
_oldOnErrorHandler = GLOBAL_OBJ.onerror;
GLOBAL_OBJ.onerror = function(msg, url4, line, column, error2) {
const handlerData = {
column,
error: error2,
line,
msg,
url: url4
};
triggerHandlers("error", handlerData);
if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {
return _oldOnErrorHandler.apply(this, arguments);
}
return false;
};
GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;
}
var _oldOnErrorHandler;
var init_globalError = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/globalError.js"() {
init_import_meta_url();
init_worldwide();
init_handlers();
_oldOnErrorHandler = null;
__name(addGlobalErrorInstrumentationHandler, "addGlobalErrorInstrumentationHandler");
__name(instrumentError, "instrumentError");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/globalUnhandledRejection.js
function addGlobalUnhandledRejectionInstrumentationHandler(handler) {
const type = "unhandledrejection";
addHandler(type, handler);
maybeInstrument(type, instrumentUnhandledRejection);
}
function instrumentUnhandledRejection() {
_oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;
GLOBAL_OBJ.onunhandledrejection = function(e7) {
const handlerData = e7;
triggerHandlers("unhandledrejection", handlerData);
if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {
return _oldOnUnhandledRejectionHandler.apply(this, arguments);
}
return true;
};
GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;
}
var _oldOnUnhandledRejectionHandler;
var init_globalUnhandledRejection = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/instrument/globalUnhandledRejection.js"() {
init_import_meta_url();
init_worldwide();
init_handlers();
_oldOnUnhandledRejectionHandler = null;
__name(addGlobalUnhandledRejectionInstrumentationHandler, "addGlobalUnhandledRejectionInstrumentationHandler");
__name(instrumentUnhandledRejection, "instrumentUnhandledRejection");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/env.js
function isBrowserBundle() {
return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__;
}
var init_env = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/env.js"() {
init_import_meta_url();
__name(isBrowserBundle, "isBrowserBundle");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/node.js
function isNodeEnv() {
return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
}
function dynamicRequire(mod, request4) {
return mod.require(request4);
}
function loadModule(moduleName) {
let mod;
try {
mod = dynamicRequire(module, moduleName);
} catch (e7) {
}
try {
const { cwd: cwd2 } = dynamicRequire(module, "process");
mod = dynamicRequire(module, `${cwd2()}/node_modules/${moduleName}`);
} catch (e7) {
}
return mod;
}
var init_node2 = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/node.js"() {
init_import_meta_url();
init_env();
__name(isNodeEnv, "isNodeEnv");
__name(dynamicRequire, "dynamicRequire");
__name(loadModule, "loadModule");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/memo.js
function memoBuilder() {
const hasWeakSet = typeof WeakSet === "function";
const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : [];
function memoize2(obj) {
if (hasWeakSet) {
if (inner.has(obj)) {
return true;
}
inner.add(obj);
return false;
}
for (let i5 = 0; i5 < inner.length; i5++) {
const value = inner[i5];
if (value === obj) {
return true;
}
}
inner.push(obj);
return false;
}
__name(memoize2, "memoize");
function unmemoize(obj) {
if (hasWeakSet) {
inner.delete(obj);
} else {
for (let i5 = 0; i5 < inner.length; i5++) {
if (inner[i5] === obj) {
inner.splice(i5, 1);
break;
}
}
}
}
__name(unmemoize, "unmemoize");
return [memoize2, unmemoize];
}
var init_memo = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/memo.js"() {
init_import_meta_url();
__name(memoBuilder, "memoBuilder");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/normalize.js
function normalize4(input, depth = 100, maxProperties = Infinity) {
try {
return visit2("", input, depth, maxProperties);
} catch (err) {
return { ERROR: `**non-serializable** (${err})` };
}
}
function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) {
const normalized = normalize4(object, depth);
if (jsonSize(normalized) > maxSize) {
return normalizeToSize(object, depth - 1, maxSize);
}
return normalized;
}
function visit2(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) {
const [memoize2, unmemoize] = memo;
if (value == null || // this matches null and undefined -> eqeq not eqeqeq
["number", "boolean", "string"].includes(typeof value) && !isNaN2(value)) {
return value;
}
const stringified = stringifyValue(key, value);
if (!stringified.startsWith("[object ")) {
return stringified;
}
if (value["__sentry_skip_normalization__"]) {
return value;
}
const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth;
if (remainingDepth === 0) {
return stringified.replace("object ", "");
}
if (memoize2(value)) {
return "[Circular ~]";
}
const valueWithToJSON = value;
if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") {
try {
const jsonValue = valueWithToJSON.toJSON();
return visit2("", jsonValue, remainingDepth - 1, maxProperties, memo);
} catch (err) {
}
}
const normalized = Array.isArray(value) ? [] : {};
let numAdded = 0;
const visitable = convertToPlainObject(value);
for (const visitKey in visitable) {
if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
continue;
}
if (numAdded >= maxProperties) {
normalized[visitKey] = "[MaxProperties ~]";
break;
}
const visitValue = visitable[visitKey];
normalized[visitKey] = visit2(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
numAdded++;
}
unmemoize(value);
return normalized;
}
function stringifyValue(key, value) {
try {
if (key === "domain" && value && typeof value === "object" && value._events) {
return "[Domain]";
}
if (key === "domainEmitter") {
return "[DomainEmitter]";
}
if (typeof global !== "undefined" && value === global) {
return "[Global]";
}
if (typeof window !== "undefined" && value === window) {
return "[Window]";
}
if (typeof document !== "undefined" && value === document) {
return "[Document]";
}
if (isVueViewModel(value)) {
return "[VueViewModel]";
}
if (isSyntheticEvent(value)) {
return "[SyntheticEvent]";
}
if (typeof value === "number" && value !== value) {
return "[NaN]";
}
if (typeof value === "function") {
return `[Function: ${getFunctionName(value)}]`;
}
if (typeof value === "symbol") {
return `[${String(value)}]`;
}
if (typeof value === "bigint") {
return `[BigInt: ${String(value)}]`;
}
const objName = getConstructorName(value);
if (/^HTML(\w*)Element$/.test(objName)) {
return `[HTMLElement: ${objName}]`;
}
return `[object ${objName}]`;
} catch (err) {
return `**non-serializable** (${err})`;
}
}
function getConstructorName(value) {
const prototype = Object.getPrototypeOf(value);
return prototype ? prototype.constructor.name : "null prototype";
}
function utf8Length(value) {
return ~-encodeURI(value).split(/%..|./).length;
}
function jsonSize(value) {
return utf8Length(JSON.stringify(value));
}
var init_normalize = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/normalize.js"() {
init_import_meta_url();
init_is();
init_memo();
init_object2();
init_stacktrace();
__name(normalize4, "normalize");
__name(normalizeToSize, "normalizeToSize");
__name(visit2, "visit");
__name(stringifyValue, "stringifyValue");
__name(getConstructorName, "getConstructorName");
__name(utf8Length, "utf8Length");
__name(jsonSize, "jsonSize");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/syncpromise.js
function resolvedSyncPromise(value) {
return new SyncPromise((resolve25) => {
resolve25(value);
});
}
function rejectedSyncPromise(reason) {
return new SyncPromise((_4, reject) => {
reject(reason);
});
}
var States, SyncPromise;
var init_syncpromise = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/syncpromise.js"() {
init_import_meta_url();
init_is();
(function(States2) {
const PENDING = 0;
States2[States2["PENDING"] = PENDING] = "PENDING";
const RESOLVED = 1;
States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED";
const REJECTED = 2;
States2[States2["REJECTED"] = REJECTED] = "REJECTED";
})(States || (States = {}));
__name(resolvedSyncPromise, "resolvedSyncPromise");
__name(rejectedSyncPromise, "rejectedSyncPromise");
SyncPromise = class _SyncPromise {
static {
__name(this, "SyncPromise");
}
constructor(executor) {
_SyncPromise.prototype.__init.call(this);
_SyncPromise.prototype.__init2.call(this);
_SyncPromise.prototype.__init3.call(this);
_SyncPromise.prototype.__init4.call(this);
this._state = States.PENDING;
this._handlers = [];
try {
executor(this._resolve, this._reject);
} catch (e7) {
this._reject(e7);
}
}
/** JSDoc */
then(onfulfilled, onrejected) {
return new _SyncPromise((resolve25, reject) => {
this._handlers.push([
false,
(result) => {
if (!onfulfilled) {
resolve25(result);
} else {
try {
resolve25(onfulfilled(result));
} catch (e7) {
reject(e7);
}
}
},
(reason) => {
if (!onrejected) {
reject(reason);
} else {
try {
resolve25(onrejected(reason));
} catch (e7) {
reject(e7);
}
}
}
]);
this._executeHandlers();
});
}
/** JSDoc */
catch(onrejected) {
return this.then((val2) => val2, onrejected);
}
/** JSDoc */
finally(onfinally) {
return new _SyncPromise((resolve25, reject) => {
let val2;
let isRejected;
return this.then(
(value) => {
isRejected = false;
val2 = value;
if (onfinally) {
onfinally();
}
},
(reason) => {
isRejected = true;
val2 = reason;
if (onfinally) {
onfinally();
}
}
).then(() => {
if (isRejected) {
reject(val2);
return;
}
resolve25(val2);
});
});
}
/** JSDoc */
__init() {
this._resolve = (value) => {
this._setResult(States.RESOLVED, value);
};
}
/** JSDoc */
__init2() {
this._reject = (reason) => {
this._setResult(States.REJECTED, reason);
};
}
/** JSDoc */
__init3() {
this._setResult = (state2, value) => {
if (this._state !== States.PENDING) {
return;
}
if (isThenable(value)) {
void value.then(this._resolve, this._reject);
return;
}
this._state = state2;
this._value = value;
this._executeHandlers();
};
}
/** JSDoc */
__init4() {
this._executeHandlers = () => {
if (this._state === States.PENDING) {
return;
}
const cachedHandlers = this._handlers.slice();
this._handlers = [];
cachedHandlers.forEach((handler) => {
if (handler[0]) {
return;
}
if (this._state === States.RESOLVED) {
handler[1](this._value);
}
if (this._state === States.REJECTED) {
handler[2](this._value);
}
handler[0] = true;
});
};
}
};
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/promisebuffer.js
function makePromiseBuffer(limit) {
const buffer = [];
function isReady() {
return limit === void 0 || buffer.length < limit;
}
__name(isReady, "isReady");
function remove(task) {
return buffer.splice(buffer.indexOf(task), 1)[0];
}
__name(remove, "remove");
function add(taskProducer) {
if (!isReady()) {
return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached."));
}
const task = taskProducer();
if (buffer.indexOf(task) === -1) {
buffer.push(task);
}
void task.then(() => remove(task)).then(
null,
() => remove(task).then(null, () => {
})
);
return task;
}
__name(add, "add");
function drain(timeout2) {
return new SyncPromise((resolve25, reject) => {
let counter = buffer.length;
if (!counter) {
return resolve25(true);
}
const capturedSetTimeout = setTimeout(() => {
if (timeout2 && timeout2 > 0) {
resolve25(false);
}
}, timeout2);
buffer.forEach((item) => {
void resolvedSyncPromise(item).then(() => {
if (!--counter) {
clearTimeout(capturedSetTimeout);
resolve25(true);
}
}, reject);
});
});
}
__name(drain, "drain");
return {
$: buffer,
add,
drain
};
}
var init_promisebuffer = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/promisebuffer.js"() {
init_import_meta_url();
init_error3();
init_syncpromise();
__name(makePromiseBuffer, "makePromiseBuffer");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/cookie.js
function parseCookie(str) {
const obj = {};
let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
let endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = str.slice(index, eqIdx).trim();
if (void 0 === obj[key]) {
let val2 = str.slice(eqIdx + 1, endIdx).trim();
if (val2.charCodeAt(0) === 34) {
val2 = val2.slice(1, -1);
}
try {
obj[key] = val2.indexOf("%") !== -1 ? decodeURIComponent(val2) : val2;
} catch (e7) {
obj[key] = val2;
}
}
index = endIdx + 1;
}
return obj;
}
var init_cookie = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/cookie.js"() {
init_import_meta_url();
__name(parseCookie, "parseCookie");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/url.js
function parseUrl2(url4) {
if (!url4) {
return {};
}
const match2 = url4.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
if (!match2) {
return {};
}
const query = match2[6] || "";
const fragment = match2[8] || "";
return {
host: match2[4],
path: match2[5],
protocol: match2[2],
search: query,
hash: fragment,
relative: match2[5] + query + fragment
// everything minus origin
};
}
function stripUrlQueryAndFragment(urlPath) {
return urlPath.split(/[\?#]/, 1)[0];
}
function getNumberOfUrlSegments(url4) {
return url4.split(/\\?\//).filter((s5) => s5.length > 0 && s5 !== ",").length;
}
function getSanitizedUrlString(url4) {
const { protocol, host, path: path72 } = url4;
const filteredHost = host && host.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || "";
return `${protocol ? `${protocol}://` : ""}${filteredHost}${path72}`;
}
var init_url = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/url.js"() {
init_import_meta_url();
__name(parseUrl2, "parseUrl");
__name(stripUrlQueryAndFragment, "stripUrlQueryAndFragment");
__name(getNumberOfUrlSegments, "getNumberOfUrlSegments");
__name(getSanitizedUrlString, "getSanitizedUrlString");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/requestdata.js
function extractPathForTransaction(req, options = {}) {
const method = req.method && req.method.toUpperCase();
let path72 = "";
let source = "url";
if (options.customRoute || req.route) {
path72 = options.customRoute || `${req.baseUrl || ""}${req.route && req.route.path}`;
source = "route";
} else if (req.originalUrl || req.url) {
path72 = stripUrlQueryAndFragment(req.originalUrl || req.url || "");
}
let name2 = "";
if (options.method && method) {
name2 += method;
}
if (options.method && options.path) {
name2 += " ";
}
if (options.path && path72) {
name2 += path72;
}
return [name2, source];
}
function extractTransaction(req, type) {
switch (type) {
case "path": {
return extractPathForTransaction(req, { path: true })[0];
}
case "handler": {
return req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name || "<anonymous>";
}
case "methodPath":
default: {
const customRoute = req._reconstructedRoute ? req._reconstructedRoute : void 0;
return extractPathForTransaction(req, { path: true, method: true, customRoute })[0];
}
}
}
function extractUserData(user, keys) {
const extractedUser = {};
const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES;
attributes.forEach((key) => {
if (user && key in user) {
extractedUser[key] = user[key];
}
});
return extractedUser;
}
function extractRequestData(req, options) {
const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {};
const requestData = {};
const headers = req.headers || {};
const method = req.method;
const host = req.hostname || req.host || headers.host || "<no host>";
const protocol = req.protocol === "https" || req.socket && req.socket.encrypted ? "https" : "http";
const originalUrl = req.originalUrl || req.url || "";
const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;
include.forEach((key) => {
switch (key) {
case "headers": {
requestData.headers = headers;
if (!include.includes("cookies")) {
delete requestData.headers.cookie;
}
break;
}
case "method": {
requestData.method = method;
break;
}
case "url": {
requestData.url = absoluteUrl;
break;
}
case "cookies": {
requestData.cookies = // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can
// come off in v8
req.cookies || headers.cookie && parseCookie(headers.cookie) || {};
break;
}
case "query_string": {
requestData.query_string = extractQueryParams(req, deps);
break;
}
case "data": {
if (method === "GET" || method === "HEAD") {
break;
}
if (req.body !== void 0) {
requestData.data = isString3(req.body) ? req.body : JSON.stringify(normalize4(req.body));
}
break;
}
default: {
if ({}.hasOwnProperty.call(req, key)) {
requestData[key] = req[key];
}
}
}
});
return requestData;
}
function addRequestDataToEvent(event, req, options) {
const include = {
...DEFAULT_INCLUDES,
...options && options.include
};
if (include.request) {
const extractedRequestData = Array.isArray(include.request) ? extractRequestData(req, { include: include.request, deps: options && options.deps }) : extractRequestData(req, { deps: options && options.deps });
event.request = {
...event.request,
...extractedRequestData
};
}
if (include.user) {
const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, include.user) : {};
if (Object.keys(extractedUser).length) {
event.user = {
...event.user,
...extractedUser
};
}
}
if (include.ip) {
const ip = req.ip || req.socket && req.socket.remoteAddress;
if (ip) {
event.user = {
...event.user,
ip_address: ip
};
}
}
if (include.transaction && !event.transaction) {
event.transaction = extractTransaction(req, include.transaction);
}
return event;
}
function extractQueryParams(req, deps) {
let originalUrl = req.originalUrl || req.url || "";
if (!originalUrl) {
return;
}
if (originalUrl.startsWith("/")) {
originalUrl = `http://dogs.are.great${originalUrl}`;
}
try {
return req.query || typeof URL !== void 0 && new URL(originalUrl).search.slice(1) || // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node
deps && deps.url && deps.url.parse(originalUrl).query || void 0;
} catch (e22) {
return void 0;
}
}
var DEFAULT_INCLUDES, DEFAULT_REQUEST_INCLUDES, DEFAULT_USER_INCLUDES;
var init_requestdata = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/requestdata.js"() {
init_import_meta_url();
init_cookie();
init_is();
init_normalize();
init_url();
DEFAULT_INCLUDES = {
ip: false,
request: true,
transaction: true,
user: true
};
DEFAULT_REQUEST_INCLUDES = ["cookies", "data", "headers", "method", "query_string", "url"];
DEFAULT_USER_INCLUDES = ["id", "username", "email"];
__name(extractPathForTransaction, "extractPathForTransaction");
__name(extractTransaction, "extractTransaction");
__name(extractUserData, "extractUserData");
__name(extractRequestData, "extractRequestData");
__name(addRequestDataToEvent, "addRequestDataToEvent");
__name(extractQueryParams, "extractQueryParams");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/severity.js
function severityLevelFromString(level) {
return level === "warn" ? "warning" : validSeverityLevels.includes(level) ? level : "log";
}
var validSeverityLevels;
var init_severity = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/severity.js"() {
init_import_meta_url();
validSeverityLevels = ["fatal", "error", "warning", "log", "info", "debug"];
__name(severityLevelFromString, "severityLevelFromString");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/time.js
function getBrowserPerformance() {
const { performance: performance2 } = WINDOW2;
if (!performance2 || !performance2.now) {
return void 0;
}
const timeOrigin = Date.now() - performance2.now();
return {
now: /* @__PURE__ */ __name(() => performance2.now(), "now"),
timeOrigin
};
}
function getNodePerformance() {
try {
const perfHooks = dynamicRequire(module, "perf_hooks");
return perfHooks.performance;
} catch (_4) {
return void 0;
}
}
var WINDOW2, dateTimestampSource, platformPerformance, timestampSource, dateTimestampInSeconds, timestampInSeconds, _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin;
var init_time = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/time.js"() {
init_import_meta_url();
init_node2();
init_worldwide();
WINDOW2 = getGlobalObject();
dateTimestampSource = {
nowSeconds: /* @__PURE__ */ __name(() => Date.now() / 1e3, "nowSeconds")
};
__name(getBrowserPerformance, "getBrowserPerformance");
__name(getNodePerformance, "getNodePerformance");
platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();
timestampSource = platformPerformance === void 0 ? dateTimestampSource : {
nowSeconds: /* @__PURE__ */ __name(() => (platformPerformance.timeOrigin + platformPerformance.now()) / 1e3, "nowSeconds")
};
dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);
timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);
browserPerformanceTimeOrigin = (() => {
const { performance: performance2 } = WINDOW2;
if (!performance2 || !performance2.now) {
_browserPerformanceTimeOriginMode = "none";
return void 0;
}
const threshold = 3600 * 1e3;
const performanceNow = performance2.now();
const dateNow = Date.now();
const timeOriginDelta = performance2.timeOrigin ? Math.abs(performance2.timeOrigin + performanceNow - dateNow) : threshold;
const timeOriginIsReliable = timeOriginDelta < threshold;
const navigationStart = performance2.timing && performance2.timing.navigationStart;
const hasNavigationStart = typeof navigationStart === "number";
const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;
const navigationStartIsReliable = navigationStartDelta < threshold;
if (timeOriginIsReliable || navigationStartIsReliable) {
if (timeOriginDelta <= navigationStartDelta) {
_browserPerformanceTimeOriginMode = "timeOrigin";
return performance2.timeOrigin;
} else {
_browserPerformanceTimeOriginMode = "navigationStart";
return navigationStart;
}
}
_browserPerformanceTimeOriginMode = "dateNow";
return dateNow;
})();
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/baggage.js
function baggageHeaderToDynamicSamplingContext(baggageHeader) {
if (!isString3(baggageHeader) && !Array.isArray(baggageHeader)) {
return void 0;
}
let baggageObject = {};
if (Array.isArray(baggageHeader)) {
baggageObject = baggageHeader.reduce((acc, curr) => {
const currBaggageObject = baggageHeaderToObject(curr);
return {
...acc,
...currBaggageObject
};
}, {});
} else {
if (!baggageHeader) {
return void 0;
}
baggageObject = baggageHeaderToObject(baggageHeader);
}
const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
acc[nonPrefixedKey] = value;
}
return acc;
}, {});
if (Object.keys(dynamicSamplingContext).length > 0) {
return dynamicSamplingContext;
} else {
return void 0;
}
}
function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) {
if (!dynamicSamplingContext) {
return void 0;
}
const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(
(acc, [dscKey, dscValue]) => {
if (dscValue) {
acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;
}
return acc;
},
{}
);
return objectToBaggageHeader(sentryPrefixedDSC);
}
function baggageHeaderToObject(baggageHeader) {
return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
}
function objectToBaggageHeader(object) {
if (Object.keys(object).length === 0) {
return void 0;
}
return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {
const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;
const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;
if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {
DEBUG_BUILD && logger3.warn(
`Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`
);
return baggageHeader;
} else {
return newBaggageHeader;
}
}, "");
}
var SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, MAX_BAGGAGE_STRING_LENGTH;
var init_baggage = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/baggage.js"() {
init_import_meta_url();
init_debug_build();
init_is();
init_logger3();
SENTRY_BAGGAGE_KEY_PREFIX = "sentry-";
SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
MAX_BAGGAGE_STRING_LENGTH = 8192;
__name(baggageHeaderToDynamicSamplingContext, "baggageHeaderToDynamicSamplingContext");
__name(dynamicSamplingContextToSentryBaggageHeader, "dynamicSamplingContextToSentryBaggageHeader");
__name(baggageHeaderToObject, "baggageHeaderToObject");
__name(objectToBaggageHeader, "objectToBaggageHeader");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/tracing.js
function extractTraceparentData(traceparent) {
if (!traceparent) {
return void 0;
}
const matches = traceparent.match(TRACEPARENT_REGEXP);
if (!matches) {
return void 0;
}
let parentSampled;
if (matches[3] === "1") {
parentSampled = true;
} else if (matches[3] === "0") {
parentSampled = false;
}
return {
traceId: matches[1],
parentSampled,
parentSpanId: matches[2]
};
}
function tracingContextFromHeaders(sentryTrace, baggage) {
const traceparentData = extractTraceparentData(sentryTrace);
const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);
const { traceId, parentSpanId, parentSampled } = traceparentData || {};
const propagationContext = {
traceId: traceId || uuid4(),
spanId: uuid4().substring(16),
sampled: parentSampled
};
if (parentSpanId) {
propagationContext.parentSpanId = parentSpanId;
}
if (dynamicSamplingContext) {
propagationContext.dsc = dynamicSamplingContext;
}
return {
traceparentData,
dynamicSamplingContext,
propagationContext
};
}
function generateSentryTraceHeader(traceId = uuid4(), spanId = uuid4().substring(16), sampled) {
let sampledString = "";
if (sampled !== void 0) {
sampledString = sampled ? "-1" : "-0";
}
return `${traceId}-${spanId}${sampledString}`;
}
var TRACEPARENT_REGEXP;
var init_tracing = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/tracing.js"() {
init_import_meta_url();
init_baggage();
init_misc();
TRACEPARENT_REGEXP = new RegExp(
"^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$"
// whitespace
);
__name(extractTraceparentData, "extractTraceparentData");
__name(tracingContextFromHeaders, "tracingContextFromHeaders");
__name(generateSentryTraceHeader, "generateSentryTraceHeader");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/envelope.js
function createEnvelope(headers, items = []) {
return [headers, items];
}
function addItemToEnvelope(envelope, newItem) {
const [headers, items] = envelope;
return [headers, [...items, newItem]];
}
function forEachEnvelopeItem(envelope, callback) {
const envelopeItems = envelope[1];
for (const envelopeItem of envelopeItems) {
const envelopeItemType = envelopeItem[0].type;
const result = callback(envelopeItem, envelopeItemType);
if (result) {
return true;
}
}
return false;
}
function encodeUTF8(input, textEncoder) {
const utf8 = textEncoder || new TextEncoder();
return utf8.encode(input);
}
function serializeEnvelope(envelope, textEncoder) {
const [envHeaders, items] = envelope;
let parts = JSON.stringify(envHeaders);
function append(next) {
if (typeof parts === "string") {
parts = typeof next === "string" ? parts + next : [encodeUTF8(parts, textEncoder), next];
} else {
parts.push(typeof next === "string" ? encodeUTF8(next, textEncoder) : next);
}
}
__name(append, "append");
for (const item of items) {
const [itemHeaders, payload] = item;
append(`
${JSON.stringify(itemHeaders)}
`);
if (typeof payload === "string" || payload instanceof Uint8Array) {
append(payload);
} else {
let stringifiedPayload;
try {
stringifiedPayload = JSON.stringify(payload);
} catch (e7) {
stringifiedPayload = JSON.stringify(normalize4(payload));
}
append(stringifiedPayload);
}
}
return typeof parts === "string" ? parts : concatBuffers(parts);
}
function concatBuffers(buffers) {
const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
const merged = new Uint8Array(totalLength);
let offset = 0;
for (const buffer of buffers) {
merged.set(buffer, offset);
offset += buffer.length;
}
return merged;
}
function createAttachmentEnvelopeItem(attachment, textEncoder) {
const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data, textEncoder) : attachment.data;
return [
dropUndefinedKeys({
type: "attachment",
length: buffer.length,
filename: attachment.filename,
content_type: attachment.contentType,
attachment_type: attachment.attachmentType
}),
buffer
];
}
function envelopeItemTypeToDataCategory(type) {
return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
}
function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
if (!metadataOrEvent || !metadataOrEvent.sdk) {
return;
}
const { name: name2, version: version5 } = metadataOrEvent.sdk;
return { name: name2, version: version5 };
}
function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {
const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;
return {
event_id: event.event_id,
sent_at: (/* @__PURE__ */ new Date()).toISOString(),
...sdkInfo && { sdk: sdkInfo },
...!!tunnel && dsn && { dsn: dsnToString(dsn) },
...dynamicSamplingContext && {
trace: dropUndefinedKeys({ ...dynamicSamplingContext })
}
};
}
var ITEM_TYPE_TO_DATA_CATEGORY_MAP;
var init_envelope = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/envelope.js"() {
init_import_meta_url();
init_dsn();
init_normalize();
init_object2();
__name(createEnvelope, "createEnvelope");
__name(addItemToEnvelope, "addItemToEnvelope");
__name(forEachEnvelopeItem, "forEachEnvelopeItem");
__name(encodeUTF8, "encodeUTF8");
__name(serializeEnvelope, "serializeEnvelope");
__name(concatBuffers, "concatBuffers");
__name(createAttachmentEnvelopeItem, "createAttachmentEnvelopeItem");
ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
session: "session",
sessions: "session",
attachment: "attachment",
transaction: "transaction",
event: "error",
client_report: "internal",
user_report: "default",
profile: "profile",
replay_event: "replay",
replay_recording: "replay",
check_in: "monitor",
feedback: "feedback",
// TODO: This is a temporary workaround until we have a proper data category for metrics
statsd: "unknown"
};
__name(envelopeItemTypeToDataCategory, "envelopeItemTypeToDataCategory");
__name(getSdkMetadataForEnvelopeHeader, "getSdkMetadataForEnvelopeHeader");
__name(createEventEnvelopeHeaders, "createEventEnvelopeHeaders");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/ratelimit.js
function parseRetryAfterHeader(header, now = Date.now()) {
const headerDelay = parseInt(`${header}`, 10);
if (!isNaN(headerDelay)) {
return headerDelay * 1e3;
}
const headerDate = Date.parse(`${header}`);
if (!isNaN(headerDate)) {
return headerDate - now;
}
return DEFAULT_RETRY_AFTER;
}
function disabledUntil(limits, category) {
return limits[category] || limits.all || 0;
}
function isRateLimited(limits, category, now = Date.now()) {
return disabledUntil(limits, category) > now;
}
function updateRateLimits(limits, { statusCode, headers }, now = Date.now()) {
const updatedRateLimits = {
...limits
};
const rateLimitHeader = headers && headers["x-sentry-rate-limits"];
const retryAfterHeader = headers && headers["retry-after"];
if (rateLimitHeader) {
for (const limit of rateLimitHeader.trim().split(",")) {
const [retryAfter, categories] = limit.split(":", 2);
const headerDelay = parseInt(retryAfter, 10);
const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
if (!categories) {
updatedRateLimits.all = now + delay;
} else {
for (const category of categories.split(";")) {
updatedRateLimits[category] = now + delay;
}
}
}
} else if (retryAfterHeader) {
updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);
} else if (statusCode === 429) {
updatedRateLimits.all = now + 60 * 1e3;
}
return updatedRateLimits;
}
var DEFAULT_RETRY_AFTER;
var init_ratelimit = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/ratelimit.js"() {
init_import_meta_url();
DEFAULT_RETRY_AFTER = 60 * 1e3;
__name(parseRetryAfterHeader, "parseRetryAfterHeader");
__name(disabledUntil, "disabledUntil");
__name(isRateLimited, "isRateLimited");
__name(updateRateLimits, "updateRateLimits");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/eventbuilder.js
function parseStackFrames(stackParser, error2) {
return stackParser(error2.stack || "", 1);
}
function exceptionFromError(stackParser, error2) {
const exception = {
type: error2.name || error2.constructor.name,
value: error2.message
};
const frames = parseStackFrames(stackParser, error2);
if (frames.length) {
exception.stacktrace = { frames };
}
return exception;
}
function getMessageForObject(exception) {
if ("name" in exception && typeof exception.name === "string") {
let message = `'${exception.name}' captured as exception`;
if ("message" in exception && typeof exception.message === "string") {
message += ` with message '${exception.message}'`;
}
return message;
} else if ("message" in exception && typeof exception.message === "string") {
return exception.message;
} else {
return `Object captured as exception with keys: ${extractExceptionKeysForMessage(
exception
)}`;
}
}
function eventFromUnknownInput(getCurrentHub3, stackParser, exception, hint) {
let ex = exception;
const providedMechanism = hint && hint.data && hint.data.mechanism;
const mechanism = providedMechanism || {
handled: true,
type: "generic"
};
if (!isError(exception)) {
if (isPlainObject(exception)) {
const hub = getCurrentHub3();
const client = hub.getClient();
const normalizeDepth = client && client.getOptions().normalizeDepth;
hub.configureScope((scope) => {
scope.setExtra("__serialized__", normalizeToSize(exception, normalizeDepth));
});
const message = getMessageForObject(exception);
ex = hint && hint.syntheticException || new Error(message);
ex.message = message;
} else {
ex = hint && hint.syntheticException || new Error(exception);
ex.message = exception;
}
mechanism.synthetic = true;
}
const event = {
exception: {
values: [exceptionFromError(stackParser, ex)]
}
};
addExceptionTypeValue(event, void 0, void 0);
addExceptionMechanism(event, mechanism);
return {
...event,
event_id: hint && hint.event_id
};
}
function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) {
const event = {
event_id: hint && hint.event_id,
level,
message
};
if (attachStacktrace && hint && hint.syntheticException) {
const frames = parseStackFrames(stackParser, hint.syntheticException);
if (frames.length) {
event.exception = {
values: [
{
value: message,
stacktrace: { frames }
}
]
};
}
}
return event;
}
var init_eventbuilder = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/eventbuilder.js"() {
init_import_meta_url();
init_is();
init_misc();
init_normalize();
init_object2();
__name(parseStackFrames, "parseStackFrames");
__name(exceptionFromError, "exceptionFromError");
__name(getMessageForObject, "getMessageForObject");
__name(eventFromUnknownInput, "eventFromUnknownInput");
__name(eventFromMessage, "eventFromMessage");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/lru.js
var LRUMap;
var init_lru = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/lru.js"() {
init_import_meta_url();
LRUMap = class {
static {
__name(this, "LRUMap");
}
constructor(_maxSize) {
this._maxSize = _maxSize;
this._cache = /* @__PURE__ */ new Map();
}
/** Get the current size of the cache */
get size() {
return this._cache.size;
}
/** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
get(key) {
const value = this._cache.get(key);
if (value === void 0) {
return void 0;
}
this._cache.delete(key);
this._cache.set(key, value);
return value;
}
/** Insert an entry and evict an older entry if we've reached maxSize */
set(key, value) {
if (this._cache.size >= this._maxSize) {
this._cache.delete(this._cache.keys().next().value);
}
this._cache.set(key, value);
}
/** Remove an entry and return the entry if it was in the cache */
remove(key) {
const value = this._cache.get(key);
if (value) {
this._cache.delete(key);
}
return value;
}
/** Clear all entries */
clear() {
this._cache.clear();
}
/** Get all the keys */
keys() {
return Array.from(this._cache.keys());
}
/** Get all the values */
values() {
const values = [];
this._cache.forEach((value) => values.push(value));
return values;
}
};
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/buildPolyfills/_nullishCoalesce.js
function _nullishCoalesce(lhs, rhsFn) {
return lhs != null ? lhs : rhsFn();
}
var init_nullishCoalesce = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/buildPolyfills/_nullishCoalesce.js"() {
init_import_meta_url();
__name(_nullishCoalesce, "_nullishCoalesce");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/buildPolyfills/_optionalChain.js
function _optionalChain(ops) {
let lastAccessLHS = void 0;
let value = ops[0];
let i5 = 1;
while (i5 < ops.length) {
const op = ops[i5];
const fn2 = ops[i5 + 1];
i5 += 2;
if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
return;
}
if (op === "access" || op === "optionalAccess") {
lastAccessLHS = value;
value = fn2(value);
} else if (op === "call" || op === "optionalCall") {
value = fn2((...args) => value.call(lastAccessLHS, ...args));
lastAccessLHS = void 0;
}
}
return value;
}
var init_optionalChain = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/buildPolyfills/_optionalChain.js"() {
init_import_meta_url();
__name(_optionalChain, "_optionalChain");
}
});
// ../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/index.js
var init_esm6 = __esm({
"../../node_modules/.pnpm/@sentry+utils@7.87.0/node_modules/@sentry/utils/esm/index.js"() {
init_import_meta_url();
init_aggregate_errors();
init_dsn();
init_error3();
init_worldwide();
init_is();
init_logger3();
init_misc();
init_node2();
init_normalize();
init_object2();
init_promisebuffer();
init_requestdata();
init_severity();
init_stacktrace();
init_string();
init_syncpromise();
init_time();
init_tracing();
init_envelope();
init_ratelimit();
init_baggage();
init_url();
init_eventbuilder();
init_lru();
init_nullishCoalesce();
init_optionalChain();
init_console();
init_globalError();
init_globalUnhandledRejection();
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/debug-build.js
var DEBUG_BUILD2;
var init_debug_build2 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/debug-build.js"() {
init_import_meta_url();
DEBUG_BUILD2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/constants.js
var DEFAULT_ENVIRONMENT;
var init_constants18 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/constants.js"() {
init_import_meta_url();
DEFAULT_ENVIRONMENT = "production";
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/eventProcessors.js
function getGlobalEventProcessors() {
return getGlobalSingleton("globalEventProcessors", () => []);
}
function addGlobalEventProcessor(callback) {
getGlobalEventProcessors().push(callback);
}
function notifyEventProcessors(processors, event, hint, index = 0) {
return new SyncPromise((resolve25, reject) => {
const processor = processors[index];
if (event === null || typeof processor !== "function") {
resolve25(event);
} else {
const result = processor({ ...event }, hint);
DEBUG_BUILD2 && processor.id && result === null && logger3.log(`Event processor "${processor.id}" dropped event`);
if (isThenable(result)) {
void result.then((final) => notifyEventProcessors(processors, final, hint, index + 1).then(resolve25)).then(null, reject);
} else {
void notifyEventProcessors(processors, result, hint, index + 1).then(resolve25).then(null, reject);
}
}
});
}
var init_eventProcessors = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/eventProcessors.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
__name(getGlobalEventProcessors, "getGlobalEventProcessors");
__name(addGlobalEventProcessor, "addGlobalEventProcessor");
__name(notifyEventProcessors, "notifyEventProcessors");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/session.js
function makeSession(context2) {
const startingTime = timestampInSeconds();
const session = {
sid: uuid4(),
init: true,
timestamp: startingTime,
started: startingTime,
duration: 0,
status: "ok",
errors: 0,
ignoreDuration: false,
toJSON: /* @__PURE__ */ __name(() => sessionToJSON(session), "toJSON")
};
if (context2) {
updateSession(session, context2);
}
return session;
}
function updateSession(session, context2 = {}) {
if (context2.user) {
if (!session.ipAddress && context2.user.ip_address) {
session.ipAddress = context2.user.ip_address;
}
if (!session.did && !context2.did) {
session.did = context2.user.id || context2.user.email || context2.user.username;
}
}
session.timestamp = context2.timestamp || timestampInSeconds();
if (context2.abnormal_mechanism) {
session.abnormal_mechanism = context2.abnormal_mechanism;
}
if (context2.ignoreDuration) {
session.ignoreDuration = context2.ignoreDuration;
}
if (context2.sid) {
session.sid = context2.sid.length === 32 ? context2.sid : uuid4();
}
if (context2.init !== void 0) {
session.init = context2.init;
}
if (!session.did && context2.did) {
session.did = `${context2.did}`;
}
if (typeof context2.started === "number") {
session.started = context2.started;
}
if (session.ignoreDuration) {
session.duration = void 0;
} else if (typeof context2.duration === "number") {
session.duration = context2.duration;
} else {
const duration = session.timestamp - session.started;
session.duration = duration >= 0 ? duration : 0;
}
if (context2.release) {
session.release = context2.release;
}
if (context2.environment) {
session.environment = context2.environment;
}
if (!session.ipAddress && context2.ipAddress) {
session.ipAddress = context2.ipAddress;
}
if (!session.userAgent && context2.userAgent) {
session.userAgent = context2.userAgent;
}
if (typeof context2.errors === "number") {
session.errors = context2.errors;
}
if (context2.status) {
session.status = context2.status;
}
}
function closeSession(session, status2) {
let context2 = {};
if (status2) {
context2 = { status: status2 };
} else if (session.status === "ok") {
context2 = { status: "exited" };
}
updateSession(session, context2);
}
function sessionToJSON(session) {
return dropUndefinedKeys({
sid: `${session.sid}`,
init: session.init,
// Make sure that sec is converted to ms for date constructor
started: new Date(session.started * 1e3).toISOString(),
timestamp: new Date(session.timestamp * 1e3).toISOString(),
status: session.status,
errors: session.errors,
did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
duration: session.duration,
abnormal_mechanism: session.abnormal_mechanism,
attrs: {
release: session.release,
environment: session.environment,
ip_address: session.ipAddress,
user_agent: session.userAgent
}
});
}
var init_session = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/session.js"() {
init_import_meta_url();
init_esm6();
__name(makeSession, "makeSession");
__name(updateSession, "updateSession");
__name(closeSession, "closeSession");
__name(sessionToJSON, "sessionToJSON");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/scope.js
function generatePropagationContext() {
return {
traceId: uuid4(),
spanId: uuid4().substring(16)
};
}
var DEFAULT_MAX_BREADCRUMBS, Scope;
var init_scope = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/scope.js"() {
init_import_meta_url();
init_esm6();
init_eventProcessors();
init_session();
DEFAULT_MAX_BREADCRUMBS = 100;
Scope = class _Scope {
static {
__name(this, "Scope");
}
/** Flag if notifying is happening. */
/** Callback for client to receive scope changes. */
/** Callback list that will be called after {@link applyToEvent}. */
/** Array of breadcrumbs. */
/** User */
/** Tags */
/** Extra */
/** Contexts */
/** Attachments */
/** Propagation Context for distributed tracing */
/**
* A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
* sent to Sentry
*/
/** Fingerprint */
/** Severity */
// eslint-disable-next-line deprecation/deprecation
/** Transaction Name */
/** Span */
/** Session */
/** Request Mode Session Status */
// NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
constructor() {
this._notifyingListeners = false;
this._scopeListeners = [];
this._eventProcessors = [];
this._breadcrumbs = [];
this._attachments = [];
this._user = {};
this._tags = {};
this._extra = {};
this._contexts = {};
this._sdkProcessingMetadata = {};
this._propagationContext = generatePropagationContext();
}
/**
* Inherit values from the parent scope.
* @deprecated Use `scope.clone()` and `new Scope()` instead.
*/
static clone(scope) {
return scope ? scope.clone() : new _Scope();
}
/**
* Clone this scope instance.
*/
clone() {
const newScope = new _Scope();
newScope._breadcrumbs = [...this._breadcrumbs];
newScope._tags = { ...this._tags };
newScope._extra = { ...this._extra };
newScope._contexts = { ...this._contexts };
newScope._user = this._user;
newScope._level = this._level;
newScope._span = this._span;
newScope._session = this._session;
newScope._transactionName = this._transactionName;
newScope._fingerprint = this._fingerprint;
newScope._eventProcessors = [...this._eventProcessors];
newScope._requestSession = this._requestSession;
newScope._attachments = [...this._attachments];
newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
newScope._propagationContext = { ...this._propagationContext };
return newScope;
}
/**
* Add internal on change listener. Used for sub SDKs that need to store the scope.
* @hidden
*/
addScopeListener(callback) {
this._scopeListeners.push(callback);
}
/**
* @inheritDoc
*/
addEventProcessor(callback) {
this._eventProcessors.push(callback);
return this;
}
/**
* @inheritDoc
*/
setUser(user) {
this._user = user || {};
if (this._session) {
updateSession(this._session, { user });
}
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
getUser() {
return this._user;
}
/**
* @inheritDoc
*/
getRequestSession() {
return this._requestSession;
}
/**
* @inheritDoc
*/
setRequestSession(requestSession) {
this._requestSession = requestSession;
return this;
}
/**
* @inheritDoc
*/
setTags(tags) {
this._tags = {
...this._tags,
...tags
};
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setTag(key, value) {
this._tags = { ...this._tags, [key]: value };
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setExtras(extras) {
this._extra = {
...this._extra,
...extras
};
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setExtra(key, extra) {
this._extra = { ...this._extra, [key]: extra };
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setFingerprint(fingerprint) {
this._fingerprint = fingerprint;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setLevel(level) {
this._level = level;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setTransactionName(name2) {
this._transactionName = name2;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setContext(key, context2) {
if (context2 === null) {
delete this._contexts[key];
} else {
this._contexts[key] = context2;
}
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
setSpan(span) {
this._span = span;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
getSpan() {
return this._span;
}
/**
* @inheritDoc
*/
getTransaction() {
const span = this.getSpan();
return span && span.transaction;
}
/**
* @inheritDoc
*/
setSession(session) {
if (!session) {
delete this._session;
} else {
this._session = session;
}
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
getSession() {
return this._session;
}
/**
* @inheritDoc
*/
update(captureContext) {
if (!captureContext) {
return this;
}
if (typeof captureContext === "function") {
const updatedScope = captureContext(this);
return updatedScope instanceof _Scope ? updatedScope : this;
}
if (captureContext instanceof _Scope) {
this._tags = { ...this._tags, ...captureContext._tags };
this._extra = { ...this._extra, ...captureContext._extra };
this._contexts = { ...this._contexts, ...captureContext._contexts };
if (captureContext._user && Object.keys(captureContext._user).length) {
this._user = captureContext._user;
}
if (captureContext._level) {
this._level = captureContext._level;
}
if (captureContext._fingerprint) {
this._fingerprint = captureContext._fingerprint;
}
if (captureContext._requestSession) {
this._requestSession = captureContext._requestSession;
}
if (captureContext._propagationContext) {
this._propagationContext = captureContext._propagationContext;
}
} else if (isPlainObject(captureContext)) {
captureContext = captureContext;
this._tags = { ...this._tags, ...captureContext.tags };
this._extra = { ...this._extra, ...captureContext.extra };
this._contexts = { ...this._contexts, ...captureContext.contexts };
if (captureContext.user) {
this._user = captureContext.user;
}
if (captureContext.level) {
this._level = captureContext.level;
}
if (captureContext.fingerprint) {
this._fingerprint = captureContext.fingerprint;
}
if (captureContext.requestSession) {
this._requestSession = captureContext.requestSession;
}
if (captureContext.propagationContext) {
this._propagationContext = captureContext.propagationContext;
}
}
return this;
}
/**
* @inheritDoc
*/
clear() {
this._breadcrumbs = [];
this._tags = {};
this._extra = {};
this._user = {};
this._contexts = {};
this._level = void 0;
this._transactionName = void 0;
this._fingerprint = void 0;
this._requestSession = void 0;
this._span = void 0;
this._session = void 0;
this._notifyScopeListeners();
this._attachments = [];
this._propagationContext = generatePropagationContext();
return this;
}
/**
* @inheritDoc
*/
addBreadcrumb(breadcrumb, maxBreadcrumbs) {
const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
if (maxCrumbs <= 0) {
return this;
}
const mergedBreadcrumb = {
timestamp: dateTimestampInSeconds(),
...breadcrumb
};
const breadcrumbs = this._breadcrumbs;
breadcrumbs.push(mergedBreadcrumb);
this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
getLastBreadcrumb() {
return this._breadcrumbs[this._breadcrumbs.length - 1];
}
/**
* @inheritDoc
*/
clearBreadcrumbs() {
this._breadcrumbs = [];
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
addAttachment(attachment) {
this._attachments.push(attachment);
return this;
}
/**
* @inheritDoc
*/
getAttachments() {
return this._attachments;
}
/**
* @inheritDoc
*/
clearAttachments() {
this._attachments = [];
return this;
}
/**
* Applies data from the scope to the event and runs all event processors on it.
*
* @param event Event
* @param hint Object containing additional information about the original exception, for use by the event processors.
* @hidden
*/
applyToEvent(event, hint = {}, additionalEventProcessors) {
if (this._extra && Object.keys(this._extra).length) {
event.extra = { ...this._extra, ...event.extra };
}
if (this._tags && Object.keys(this._tags).length) {
event.tags = { ...this._tags, ...event.tags };
}
if (this._user && Object.keys(this._user).length) {
event.user = { ...this._user, ...event.user };
}
if (this._contexts && Object.keys(this._contexts).length) {
event.contexts = { ...this._contexts, ...event.contexts };
}
if (this._level) {
event.level = this._level;
}
if (this._transactionName) {
event.transaction = this._transactionName;
}
if (this._span) {
event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };
const transaction = this._span.transaction;
if (transaction) {
event.sdkProcessingMetadata = {
dynamicSamplingContext: transaction.getDynamicSamplingContext(),
...event.sdkProcessingMetadata
};
const transactionName = transaction.name;
if (transactionName) {
event.tags = { transaction: transactionName, ...event.tags };
}
}
}
this._applyFingerprint(event);
const scopeBreadcrumbs = this._getBreadcrumbs();
const breadcrumbs = [...event.breadcrumbs || [], ...scopeBreadcrumbs];
event.breadcrumbs = breadcrumbs.length > 0 ? breadcrumbs : void 0;
event.sdkProcessingMetadata = {
...event.sdkProcessingMetadata,
...this._sdkProcessingMetadata,
propagationContext: this._propagationContext
};
return notifyEventProcessors(
[
...additionalEventProcessors || [],
// eslint-disable-next-line deprecation/deprecation
...getGlobalEventProcessors(),
...this._eventProcessors
],
event,
hint
);
}
/**
* Add data which will be accessible during event processing but won't get sent to Sentry
*/
setSDKProcessingMetadata(newData) {
this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };
return this;
}
/**
* @inheritDoc
*/
setPropagationContext(context2) {
this._propagationContext = context2;
return this;
}
/**
* @inheritDoc
*/
getPropagationContext() {
return this._propagationContext;
}
/**
* Get the breadcrumbs for this scope.
*/
_getBreadcrumbs() {
return this._breadcrumbs;
}
/**
* This will be called on every set call.
*/
_notifyScopeListeners() {
if (!this._notifyingListeners) {
this._notifyingListeners = true;
this._scopeListeners.forEach((callback) => {
callback(this);
});
this._notifyingListeners = false;
}
}
/**
* Applies fingerprint from the scope to the event if there's one,
* uses message if there's one instead or get rid of empty fingerprint
*/
_applyFingerprint(event) {
event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];
if (this._fingerprint) {
event.fingerprint = event.fingerprint.concat(this._fingerprint);
}
if (event.fingerprint && !event.fingerprint.length) {
delete event.fingerprint;
}
}
};
__name(generatePropagationContext, "generatePropagationContext");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/version.js
var SDK_VERSION;
var init_version = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/version.js"() {
init_import_meta_url();
SDK_VERSION = "7.87.0";
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/hub.js
function getMainCarrier() {
GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {
extensions: {},
hub: void 0
};
return GLOBAL_OBJ;
}
function makeMain(hub) {
const registry = getMainCarrier();
const oldHub = getHubFromCarrier(registry);
setHubOnCarrier(registry, hub);
return oldHub;
}
function getCurrentHub() {
const registry = getMainCarrier();
if (registry.__SENTRY__ && registry.__SENTRY__.acs) {
const hub = registry.__SENTRY__.acs.getCurrentHub();
if (hub) {
return hub;
}
}
return getGlobalHub(registry);
}
function getGlobalHub(registry = getMainCarrier()) {
if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {
setHubOnCarrier(registry, new Hub());
}
return getHubFromCarrier(registry);
}
function ensureHubOnCarrier(carrier, parent = getGlobalHub()) {
if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {
const globalHubTopStack = parent.getStackTop();
setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, globalHubTopStack.scope.clone()));
}
}
function setAsyncContextStrategy(strategy) {
const registry = getMainCarrier();
registry.__SENTRY__ = registry.__SENTRY__ || {};
registry.__SENTRY__.acs = strategy;
}
function hasHubOnCarrier(carrier) {
return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
}
function getHubFromCarrier(carrier) {
return getGlobalSingleton("hub", () => new Hub(), carrier);
}
function setHubOnCarrier(carrier, hub) {
if (!carrier) return false;
const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
__SENTRY__.hub = hub;
return true;
}
var API_VERSION, DEFAULT_BREADCRUMBS, Hub;
var init_hub = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/hub.js"() {
init_import_meta_url();
init_esm6();
init_constants18();
init_debug_build2();
init_scope();
init_session();
init_version();
API_VERSION = parseFloat(SDK_VERSION);
DEFAULT_BREADCRUMBS = 100;
Hub = class {
static {
__name(this, "Hub");
}
/** Is a {@link Layer}[] containing the client and scope */
/** Contains the last event id of a captured event. */
/**
* Creates a new instance of the hub, will push one {@link Layer} into the
* internal stack on creation.
*
* @param client bound to the hub.
* @param scope bound to the hub.
* @param version number, higher number means higher priority.
*/
constructor(client, scope = new Scope(), _version = API_VERSION) {
this._version = _version;
this._stack = [{ scope }];
if (client) {
this.bindClient(client);
}
}
/**
* @inheritDoc
*/
isOlderThan(version5) {
return this._version < version5;
}
/**
* @inheritDoc
*/
bindClient(client) {
const top2 = this.getStackTop();
top2.client = client;
if (client && client.setupIntegrations) {
client.setupIntegrations();
}
}
/**
* @inheritDoc
*/
pushScope() {
const scope = this.getScope().clone();
this.getStack().push({
client: this.getClient(),
scope
});
return scope;
}
/**
* @inheritDoc
*/
popScope() {
if (this.getStack().length <= 1) return false;
return !!this.getStack().pop();
}
/**
* @inheritDoc
*/
withScope(callback) {
const scope = this.pushScope();
try {
callback(scope);
} finally {
this.popScope();
}
}
/**
* @inheritDoc
*/
getClient() {
return this.getStackTop().client;
}
/** Returns the scope of the top stack. */
getScope() {
return this.getStackTop().scope;
}
/** Returns the scope stack for domains or the process. */
getStack() {
return this._stack;
}
/** Returns the topmost scope layer in the order domain > local > process. */
getStackTop() {
return this._stack[this._stack.length - 1];
}
/**
* @inheritDoc
*/
captureException(exception, hint) {
const eventId = this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4();
const syntheticException = new Error("Sentry syntheticException");
this._withClient((client, scope) => {
client.captureException(
exception,
{
originalException: exception,
syntheticException,
...hint,
event_id: eventId
},
scope
);
});
return eventId;
}
/**
* @inheritDoc
*/
captureMessage(message, level, hint) {
const eventId = this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4();
const syntheticException = new Error(message);
this._withClient((client, scope) => {
client.captureMessage(
message,
level,
{
originalException: message,
syntheticException,
...hint,
event_id: eventId
},
scope
);
});
return eventId;
}
/**
* @inheritDoc
*/
captureEvent(event, hint) {
const eventId = hint && hint.event_id ? hint.event_id : uuid4();
if (!event.type) {
this._lastEventId = eventId;
}
this._withClient((client, scope) => {
client.captureEvent(event, { ...hint, event_id: eventId }, scope);
});
return eventId;
}
/**
* @inheritDoc
*/
lastEventId() {
return this._lastEventId;
}
/**
* @inheritDoc
*/
addBreadcrumb(breadcrumb, hint) {
const { scope, client } = this.getStackTop();
if (!client) return;
const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions && client.getOptions() || {};
if (maxBreadcrumbs <= 0) return;
const timestamp = dateTimestampInSeconds();
const mergedBreadcrumb = { timestamp, ...breadcrumb };
const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;
if (finalBreadcrumb === null) return;
if (client.emit) {
client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
}
scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
}
/**
* @inheritDoc
*/
setUser(user) {
this.getScope().setUser(user);
}
/**
* @inheritDoc
*/
setTags(tags) {
this.getScope().setTags(tags);
}
/**
* @inheritDoc
*/
setExtras(extras) {
this.getScope().setExtras(extras);
}
/**
* @inheritDoc
*/
setTag(key, value) {
this.getScope().setTag(key, value);
}
/**
* @inheritDoc
*/
setExtra(key, extra) {
this.getScope().setExtra(key, extra);
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setContext(name2, context2) {
this.getScope().setContext(name2, context2);
}
/**
* @inheritDoc
*/
configureScope(callback) {
const { scope, client } = this.getStackTop();
if (client) {
callback(scope);
}
}
/**
* @inheritDoc
*/
run(callback) {
const oldHub = makeMain(this);
try {
callback(this);
} finally {
makeMain(oldHub);
}
}
/**
* @inheritDoc
*/
getIntegration(integration) {
const client = this.getClient();
if (!client) return null;
try {
return client.getIntegration(integration);
} catch (_oO) {
DEBUG_BUILD2 && logger3.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);
return null;
}
}
/**
* @inheritDoc
*/
startTransaction(context2, customSamplingContext) {
const result = this._callExtensionMethod("startTransaction", context2, customSamplingContext);
if (DEBUG_BUILD2 && !result) {
const client = this.getClient();
if (!client) {
logger3.warn(
"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'"
);
} else {
logger3.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':
Sentry.addTracingExtensions();
Sentry.init({...});
`);
}
}
return result;
}
/**
* @inheritDoc
*/
traceHeaders() {
return this._callExtensionMethod("traceHeaders");
}
/**
* @inheritDoc
*/
captureSession(endSession = false) {
if (endSession) {
return this.endSession();
}
this._sendSessionUpdate();
}
/**
* @inheritDoc
*/
endSession() {
const layer = this.getStackTop();
const scope = layer.scope;
const session = scope.getSession();
if (session) {
closeSession(session);
}
this._sendSessionUpdate();
scope.setSession();
}
/**
* @inheritDoc
*/
startSession(context2) {
const { scope, client } = this.getStackTop();
const { release: release3, environment = DEFAULT_ENVIRONMENT } = client && client.getOptions() || {};
const { userAgent } = GLOBAL_OBJ.navigator || {};
const session = makeSession({
release: release3,
environment,
user: scope.getUser(),
...userAgent && { userAgent },
...context2
});
const currentSession = scope.getSession && scope.getSession();
if (currentSession && currentSession.status === "ok") {
updateSession(currentSession, { status: "exited" });
}
this.endSession();
scope.setSession(session);
return session;
}
/**
* Returns if default PII should be sent to Sentry and propagated in ourgoing requests
* when Tracing is used.
*/
shouldSendDefaultPii() {
const client = this.getClient();
const options = client && client.getOptions();
return Boolean(options && options.sendDefaultPii);
}
/**
* Sends the current Session on the scope
*/
_sendSessionUpdate() {
const { scope, client } = this.getStackTop();
const session = scope.getSession();
if (session && client && client.captureSession) {
client.captureSession(session);
}
}
/**
* Internal helper function to call a method on the top client if it exists.
*
* @param method The method to call on the client.
* @param args Arguments to pass to the client function.
*/
_withClient(callback) {
const { scope, client } = this.getStackTop();
if (client) {
callback(client, scope);
}
}
/**
* Calls global extension method and binding current instance to the function call
*/
// @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_callExtensionMethod(method, ...args) {
const carrier = getMainCarrier();
const sentry = carrier.__SENTRY__;
if (sentry && sentry.extensions && typeof sentry.extensions[method] === "function") {
return sentry.extensions[method].apply(this, args);
}
DEBUG_BUILD2 && logger3.warn(`Extension method ${method} couldn't be found, doing nothing.`);
}
};
__name(getMainCarrier, "getMainCarrier");
__name(makeMain, "makeMain");
__name(getCurrentHub, "getCurrentHub");
__name(getGlobalHub, "getGlobalHub");
__name(ensureHubOnCarrier, "ensureHubOnCarrier");
__name(setAsyncContextStrategy, "setAsyncContextStrategy");
__name(hasHubOnCarrier, "hasHubOnCarrier");
__name(getHubFromCarrier, "getHubFromCarrier");
__name(setHubOnCarrier, "setHubOnCarrier");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/utils.js
function getActiveTransaction(maybeHub) {
const hub = maybeHub || getCurrentHub();
const scope = hub.getScope();
return scope.getTransaction();
}
var init_utils13 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/utils.js"() {
init_import_meta_url();
init_hub();
__name(getActiveTransaction, "getActiveTransaction");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/errors.js
function registerErrorInstrumentation() {
if (errorsInstrumented) {
return;
}
errorsInstrumented = true;
addGlobalErrorInstrumentationHandler(errorCallback);
addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);
}
function errorCallback() {
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
const status2 = "internal_error";
DEBUG_BUILD2 && logger3.log(`[Tracing] Transaction: ${status2} -> Global error occured`);
activeTransaction.setStatus(status2);
}
}
var errorsInstrumented;
var init_errors4 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/errors.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_utils13();
errorsInstrumented = false;
__name(registerErrorInstrumentation, "registerErrorInstrumentation");
__name(errorCallback, "errorCallback");
errorCallback.tag = "sentry_tracingErrorCallback";
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/span.js
function spanStatusfromHttpCode(httpStatus) {
if (httpStatus < 400 && httpStatus >= 100) {
return "ok";
}
if (httpStatus >= 400 && httpStatus < 500) {
switch (httpStatus) {
case 401:
return "unauthenticated";
case 403:
return "permission_denied";
case 404:
return "not_found";
case 409:
return "already_exists";
case 413:
return "failed_precondition";
case 429:
return "resource_exhausted";
default:
return "invalid_argument";
}
}
if (httpStatus >= 500 && httpStatus < 600) {
switch (httpStatus) {
case 501:
return "unimplemented";
case 503:
return "unavailable";
case 504:
return "deadline_exceeded";
default:
return "internal_error";
}
}
return "unknown_error";
}
var SpanRecorder, Span;
var init_span = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/span.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
SpanRecorder = class {
static {
__name(this, "SpanRecorder");
}
constructor(maxlen = 1e3) {
this._maxlen = maxlen;
this.spans = [];
}
/**
* This is just so that we don't run out of memory while recording a lot
* of spans. At some point we just stop and flush out the start of the
* trace tree (i.e.the first n spans with the smallest
* start_timestamp).
*/
add(span) {
if (this.spans.length > this._maxlen) {
span.spanRecorder = void 0;
} else {
this.spans.push(span);
}
}
};
Span = class _Span {
static {
__name(this, "Span");
}
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
/**
* Internal keeper of the status
*/
/**
* @inheritDoc
*/
/**
* Timestamp in seconds when the span was created.
*/
/**
* Timestamp in seconds when the span ended.
*/
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
/**
* List of spans that were finalized
*/
/**
* @inheritDoc
*/
/**
* The instrumenter that created this span.
*/
/**
* The origin of the span, giving context about what created the span.
*/
/**
* You should never call the constructor manually, always use `Sentry.startTransaction()`
* or call `startChild()` on an existing span.
* @internal
* @hideconstructor
* @hidden
*/
constructor(spanContext = {}) {
this.traceId = spanContext.traceId || uuid4();
this.spanId = spanContext.spanId || uuid4().substring(16);
this.startTimestamp = spanContext.startTimestamp || timestampInSeconds();
this.tags = spanContext.tags || {};
this.data = spanContext.data || {};
this.instrumenter = spanContext.instrumenter || "sentry";
this.origin = spanContext.origin || "manual";
if (spanContext.parentSpanId) {
this.parentSpanId = spanContext.parentSpanId;
}
if ("sampled" in spanContext) {
this.sampled = spanContext.sampled;
}
if (spanContext.op) {
this.op = spanContext.op;
}
if (spanContext.description) {
this.description = spanContext.description;
}
if (spanContext.name) {
this.description = spanContext.name;
}
if (spanContext.status) {
this.status = spanContext.status;
}
if (spanContext.endTimestamp) {
this.endTimestamp = spanContext.endTimestamp;
}
}
/** An alias for `description` of the Span. */
get name() {
return this.description || "";
}
/** Update the name of the span. */
set name(name2) {
this.setName(name2);
}
/**
* @inheritDoc
*/
startChild(spanContext) {
const childSpan = new _Span({
...spanContext,
parentSpanId: this.spanId,
sampled: this.sampled,
traceId: this.traceId
});
childSpan.spanRecorder = this.spanRecorder;
if (childSpan.spanRecorder) {
childSpan.spanRecorder.add(childSpan);
}
childSpan.transaction = this.transaction;
if (DEBUG_BUILD2 && childSpan.transaction) {
const opStr = spanContext && spanContext.op || "< unknown op >";
const nameStr = childSpan.transaction.name || "< unknown name >";
const idStr = childSpan.transaction.spanId;
const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;
childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };
logger3.log(logMessage);
}
return childSpan;
}
/**
* @inheritDoc
*/
setTag(key, value) {
this.tags = { ...this.tags, [key]: value };
return this;
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
setData(key, value) {
this.data = { ...this.data, [key]: value };
return this;
}
/**
* @inheritDoc
*/
setStatus(value) {
this.status = value;
return this;
}
/**
* @inheritDoc
*/
setHttpStatus(httpStatus) {
this.setTag("http.status_code", String(httpStatus));
this.setData("http.response.status_code", httpStatus);
const spanStatus = spanStatusfromHttpCode(httpStatus);
if (spanStatus !== "unknown_error") {
this.setStatus(spanStatus);
}
return this;
}
/**
* @inheritDoc
*/
setName(name2) {
this.description = name2;
}
/**
* @inheritDoc
*/
isSuccess() {
return this.status === "ok";
}
/**
* @inheritDoc
*/
finish(endTimestamp) {
if (DEBUG_BUILD2 && // Don't call this for transactions
this.transaction && this.transaction.spanId !== this.spanId) {
const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];
if (logMessage) {
logger3.log(logMessage.replace("Starting", "Finishing"));
}
}
this.endTimestamp = typeof endTimestamp === "number" ? endTimestamp : timestampInSeconds();
}
/**
* @inheritDoc
*/
toTraceparent() {
return generateSentryTraceHeader(this.traceId, this.spanId, this.sampled);
}
/**
* @inheritDoc
*/
toContext() {
return dropUndefinedKeys({
data: this.data,
description: this.description,
endTimestamp: this.endTimestamp,
op: this.op,
parentSpanId: this.parentSpanId,
sampled: this.sampled,
spanId: this.spanId,
startTimestamp: this.startTimestamp,
status: this.status,
tags: this.tags,
traceId: this.traceId
});
}
/**
* @inheritDoc
*/
updateWithContext(spanContext) {
this.data = spanContext.data || {};
this.description = spanContext.description;
this.endTimestamp = spanContext.endTimestamp;
this.op = spanContext.op;
this.parentSpanId = spanContext.parentSpanId;
this.sampled = spanContext.sampled;
this.spanId = spanContext.spanId || this.spanId;
this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;
this.status = spanContext.status;
this.tags = spanContext.tags || {};
this.traceId = spanContext.traceId || this.traceId;
return this;
}
/**
* @inheritDoc
*/
getTraceContext() {
return dropUndefinedKeys({
data: Object.keys(this.data).length > 0 ? this.data : void 0,
description: this.description,
op: this.op,
parent_span_id: this.parentSpanId,
span_id: this.spanId,
status: this.status,
tags: Object.keys(this.tags).length > 0 ? this.tags : void 0,
trace_id: this.traceId,
origin: this.origin
});
}
/**
* @inheritDoc
*/
toJSON() {
return dropUndefinedKeys({
data: Object.keys(this.data).length > 0 ? this.data : void 0,
description: this.description,
op: this.op,
parent_span_id: this.parentSpanId,
span_id: this.spanId,
start_timestamp: this.startTimestamp,
status: this.status,
tags: Object.keys(this.tags).length > 0 ? this.tags : void 0,
timestamp: this.endTimestamp,
trace_id: this.traceId,
origin: this.origin
});
}
};
__name(spanStatusfromHttpCode, "spanStatusfromHttpCode");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/dynamicSamplingContext.js
function getDynamicSamplingContextFromClient(trace_id, client, scope) {
const options = client.getOptions();
const { publicKey: public_key } = client.getDsn() || {};
const { segment: user_segment } = scope && scope.getUser() || {};
const dsc = dropUndefinedKeys({
environment: options.environment || DEFAULT_ENVIRONMENT,
release: options.release,
user_segment,
public_key,
trace_id
});
client.emit && client.emit("createDsc", dsc);
return dsc;
}
var init_dynamicSamplingContext = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/dynamicSamplingContext.js"() {
init_import_meta_url();
init_esm6();
init_constants18();
__name(getDynamicSamplingContextFromClient, "getDynamicSamplingContextFromClient");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/transaction.js
var Transaction;
var init_transaction = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/transaction.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_hub();
init_dynamicSamplingContext();
init_span();
Transaction = class extends Span {
static {
__name(this, "Transaction");
}
/**
* The reference to the current hub.
*/
/**
* This constructor should never be called manually. Those instrumenting tracing should use
* `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.
* @internal
* @hideconstructor
* @hidden
*/
constructor(transactionContext, hub) {
super(transactionContext);
delete this.description;
this._measurements = {};
this._contexts = {};
this._hub = hub || getCurrentHub();
this._name = transactionContext.name || "";
this.metadata = {
source: "custom",
...transactionContext.metadata,
spanMetadata: {}
};
this._trimEnd = transactionContext.trimEnd;
this.transaction = this;
const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;
if (incomingDynamicSamplingContext) {
this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };
}
}
/** Getter for `name` property */
get name() {
return this._name;
}
/** Setter for `name` property, which also sets `source` as custom */
set name(newName) {
this.setName(newName);
}
/**
* JSDoc
*/
setName(name2, source = "custom") {
this._name = name2;
this.metadata.source = source;
}
/**
* Attaches SpanRecorder to the span itself
* @param maxlen maximum number of spans that can be recorded
*/
initSpanRecorder(maxlen = 1e3) {
if (!this.spanRecorder) {
this.spanRecorder = new SpanRecorder(maxlen);
}
this.spanRecorder.add(this);
}
/**
* @inheritDoc
*/
setContext(key, context2) {
if (context2 === null) {
delete this._contexts[key];
} else {
this._contexts[key] = context2;
}
}
/**
* @inheritDoc
*/
setMeasurement(name2, value, unit = "") {
this._measurements[name2] = { value, unit };
}
/**
* @inheritDoc
*/
setMetadata(newMetadata) {
this.metadata = { ...this.metadata, ...newMetadata };
}
/**
* @inheritDoc
*/
finish(endTimestamp) {
const transaction = this._finishTransaction(endTimestamp);
if (!transaction) {
return void 0;
}
return this._hub.captureEvent(transaction);
}
/**
* @inheritDoc
*/
toContext() {
const spanContext = super.toContext();
return dropUndefinedKeys({
...spanContext,
name: this.name,
trimEnd: this._trimEnd
});
}
/**
* @inheritDoc
*/
updateWithContext(transactionContext) {
super.updateWithContext(transactionContext);
this.name = transactionContext.name || "";
this._trimEnd = transactionContext.trimEnd;
return this;
}
/**
* @inheritdoc
*
* @experimental
*/
getDynamicSamplingContext() {
if (this._frozenDynamicSamplingContext) {
return this._frozenDynamicSamplingContext;
}
const hub = this._hub || getCurrentHub();
const client = hub.getClient();
if (!client) return {};
const scope = hub.getScope();
const dsc = getDynamicSamplingContextFromClient(this.traceId, client, scope);
const maybeSampleRate = this.metadata.sampleRate;
if (maybeSampleRate !== void 0) {
dsc.sample_rate = `${maybeSampleRate}`;
}
const source = this.metadata.source;
if (source && source !== "url") {
dsc.transaction = this.name;
}
if (this.sampled !== void 0) {
dsc.sampled = String(this.sampled);
}
return dsc;
}
/**
* Override the current hub with a new one.
* Used if you want another hub to finish the transaction.
*
* @internal
*/
setHub(hub) {
this._hub = hub;
}
/**
* Finish the transaction & prepare the event to send to Sentry.
*/
_finishTransaction(endTimestamp) {
if (this.endTimestamp !== void 0) {
return void 0;
}
if (!this.name) {
DEBUG_BUILD2 && logger3.warn("Transaction has no name, falling back to `<unlabeled transaction>`.");
this.name = "<unlabeled transaction>";
}
super.finish(endTimestamp);
const client = this._hub.getClient();
if (client && client.emit) {
client.emit("finishTransaction", this);
}
if (this.sampled !== true) {
DEBUG_BUILD2 && logger3.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled.");
if (client) {
client.recordDroppedEvent("sample_rate", "transaction");
}
return void 0;
}
const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter((s5) => s5 !== this && s5.endTimestamp) : [];
if (this._trimEnd && finishedSpans.length > 0) {
this.endTimestamp = finishedSpans.reduce((prev, current) => {
if (prev.endTimestamp && current.endTimestamp) {
return prev.endTimestamp > current.endTimestamp ? prev : current;
}
return prev;
}).endTimestamp;
}
const metadata = this.metadata;
const transaction = {
contexts: {
...this._contexts,
// We don't want to override trace context
trace: this.getTraceContext()
},
spans: finishedSpans,
start_timestamp: this.startTimestamp,
tags: this.tags,
timestamp: this.endTimestamp,
transaction: this.name,
type: "transaction",
sdkProcessingMetadata: {
...metadata,
dynamicSamplingContext: this.getDynamicSamplingContext()
},
...metadata.source && {
transaction_info: {
source: metadata.source
}
}
};
const hasMeasurements = Object.keys(this._measurements).length > 0;
if (hasMeasurements) {
DEBUG_BUILD2 && logger3.log(
"[Measurements] Adding measurements to transaction",
JSON.stringify(this._measurements, void 0, 2)
);
transaction.measurements = this._measurements;
}
DEBUG_BUILD2 && logger3.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);
return transaction;
}
};
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/utils/prepareEvent.js
function prepareEvent(options, event, hint, scope, client) {
const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options;
const prepared = {
...event,
event_id: event.event_id || hint.event_id || uuid4(),
timestamp: event.timestamp || dateTimestampInSeconds()
};
const integrations = hint.integrations || options.integrations.map((i5) => i5.name);
applyClientOptions(prepared, options);
applyIntegrationsMetadata(prepared, integrations);
if (event.type === void 0) {
applyDebugIds(prepared, options.stackParser);
}
const finalScope = getFinalScope(scope, hint.captureContext);
if (hint.mechanism) {
addExceptionMechanism(prepared, hint.mechanism);
}
let result = resolvedSyncPromise(prepared);
const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];
if (finalScope) {
if (finalScope.getAttachments) {
const attachments = [...hint.attachments || [], ...finalScope.getAttachments()];
if (attachments.length) {
hint.attachments = attachments;
}
}
result = finalScope.applyToEvent(prepared, hint, clientEventProcessors);
} else {
result = notifyEventProcessors(
[
...clientEventProcessors,
// eslint-disable-next-line deprecation/deprecation
...getGlobalEventProcessors()
],
prepared,
hint
);
}
return result.then((evt) => {
if (evt) {
applyDebugMeta(evt);
}
if (typeof normalizeDepth === "number" && normalizeDepth > 0) {
return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
}
return evt;
});
}
function applyClientOptions(event, options) {
const { environment, release: release3, dist, maxValueLength = 250 } = options;
if (!("environment" in event)) {
event.environment = "environment" in options ? environment : DEFAULT_ENVIRONMENT;
}
if (event.release === void 0 && release3 !== void 0) {
event.release = release3;
}
if (event.dist === void 0 && dist !== void 0) {
event.dist = dist;
}
if (event.message) {
event.message = truncate3(event.message, maxValueLength);
}
const exception = event.exception && event.exception.values && event.exception.values[0];
if (exception && exception.value) {
exception.value = truncate3(exception.value, maxValueLength);
}
const request4 = event.request;
if (request4 && request4.url) {
request4.url = truncate3(request4.url, maxValueLength);
}
}
function applyDebugIds(event, stackParser) {
const debugIdMap = GLOBAL_OBJ._sentryDebugIds;
if (!debugIdMap) {
return;
}
let debugIdStackFramesCache;
const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);
if (cachedDebugIdStackFrameCache) {
debugIdStackFramesCache = cachedDebugIdStackFrameCache;
} else {
debugIdStackFramesCache = /* @__PURE__ */ new Map();
debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);
}
const filenameDebugIdMap = Object.keys(debugIdMap).reduce((acc, debugIdStackTrace) => {
let parsedStack;
const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);
if (cachedParsedStack) {
parsedStack = cachedParsedStack;
} else {
parsedStack = stackParser(debugIdStackTrace);
debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);
}
for (let i5 = parsedStack.length - 1; i5 >= 0; i5--) {
const stackFrame = parsedStack[i5];
if (stackFrame.filename) {
acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];
break;
}
}
return acc;
}, {});
try {
event.exception.values.forEach((exception) => {
exception.stacktrace.frames.forEach((frame) => {
if (frame.filename) {
frame.debug_id = filenameDebugIdMap[frame.filename];
}
});
});
} catch (e7) {
}
}
function applyDebugMeta(event) {
const filenameDebugIdMap = {};
try {
event.exception.values.forEach((exception) => {
exception.stacktrace.frames.forEach((frame) => {
if (frame.debug_id) {
if (frame.abs_path) {
filenameDebugIdMap[frame.abs_path] = frame.debug_id;
} else if (frame.filename) {
filenameDebugIdMap[frame.filename] = frame.debug_id;
}
delete frame.debug_id;
}
});
});
} catch (e7) {
}
if (Object.keys(filenameDebugIdMap).length === 0) {
return;
}
event.debug_meta = event.debug_meta || {};
event.debug_meta.images = event.debug_meta.images || [];
const images = event.debug_meta.images;
Object.keys(filenameDebugIdMap).forEach((filename) => {
images.push({
type: "sourcemap",
code_file: filename,
debug_id: filenameDebugIdMap[filename]
});
});
}
function applyIntegrationsMetadata(event, integrationNames) {
if (integrationNames.length > 0) {
event.sdk = event.sdk || {};
event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames];
}
}
function normalizeEvent(event, depth, maxBreadth) {
if (!event) {
return null;
}
const normalized = {
...event,
...event.breadcrumbs && {
breadcrumbs: event.breadcrumbs.map((b6) => ({
...b6,
...b6.data && {
data: normalize4(b6.data, depth, maxBreadth)
}
}))
},
...event.user && {
user: normalize4(event.user, depth, maxBreadth)
},
...event.contexts && {
contexts: normalize4(event.contexts, depth, maxBreadth)
},
...event.extra && {
extra: normalize4(event.extra, depth, maxBreadth)
}
};
if (event.contexts && event.contexts.trace && normalized.contexts) {
normalized.contexts.trace = event.contexts.trace;
if (event.contexts.trace.data) {
normalized.contexts.trace.data = normalize4(event.contexts.trace.data, depth, maxBreadth);
}
}
if (event.spans) {
normalized.spans = event.spans.map((span) => {
if (span.data) {
span.data = normalize4(span.data, depth, maxBreadth);
}
return span;
});
}
return normalized;
}
function getFinalScope(scope, captureContext) {
if (!captureContext) {
return scope;
}
const finalScope = scope ? scope.clone() : new Scope();
finalScope.update(captureContext);
return finalScope;
}
function parseEventHintOrCaptureContext(hint) {
if (!hint) {
return void 0;
}
if (hintIsScopeOrFunction(hint)) {
return { captureContext: hint };
}
if (hintIsScopeContext(hint)) {
return {
captureContext: hint
};
}
return hint;
}
function hintIsScopeOrFunction(hint) {
return hint instanceof Scope || typeof hint === "function";
}
function hintIsScopeContext(hint) {
return Object.keys(hint).some((key) => captureContextKeys.includes(key));
}
var debugIdStackParserCache, captureContextKeys;
var init_prepareEvent = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/utils/prepareEvent.js"() {
init_import_meta_url();
init_esm6();
init_constants18();
init_eventProcessors();
init_scope();
__name(prepareEvent, "prepareEvent");
__name(applyClientOptions, "applyClientOptions");
debugIdStackParserCache = /* @__PURE__ */ new WeakMap();
__name(applyDebugIds, "applyDebugIds");
__name(applyDebugMeta, "applyDebugMeta");
__name(applyIntegrationsMetadata, "applyIntegrationsMetadata");
__name(normalizeEvent, "normalizeEvent");
__name(getFinalScope, "getFinalScope");
__name(parseEventHintOrCaptureContext, "parseEventHintOrCaptureContext");
__name(hintIsScopeOrFunction, "hintIsScopeOrFunction");
captureContextKeys = [
"user",
"level",
"extra",
"contexts",
"tags",
"fingerprint",
"requestSession",
"propagationContext"
];
__name(hintIsScopeContext, "hintIsScopeContext");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/exports.js
function captureException(exception, hint) {
return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));
}
function addBreadcrumb(breadcrumb) {
getCurrentHub().addBreadcrumb(breadcrumb);
}
async function close(timeout2) {
const client = getClient();
if (client) {
return client.close(timeout2);
}
DEBUG_BUILD2 && logger3.warn("Cannot flush events and disable SDK. No client defined.");
return Promise.resolve(false);
}
function getClient() {
return getCurrentHub().getClient();
}
var init_exports = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/exports.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_hub();
init_prepareEvent();
__name(captureException, "captureException");
__name(addBreadcrumb, "addBreadcrumb");
__name(close, "close");
__name(getClient, "getClient");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/utils/hasTracingEnabled.js
function hasTracingEnabled(maybeOptions) {
if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) {
return false;
}
const client = getClient();
const options = maybeOptions || client && client.getOptions();
return !!options && (options.enableTracing || "tracesSampleRate" in options || "tracesSampler" in options);
}
var init_hasTracingEnabled = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/utils/hasTracingEnabled.js"() {
init_import_meta_url();
init_exports();
__name(hasTracingEnabled, "hasTracingEnabled");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/sampling.js
function sampleTransaction(transaction, options, samplingContext) {
if (!hasTracingEnabled(options)) {
transaction.sampled = false;
return transaction;
}
if (transaction.sampled !== void 0) {
transaction.setMetadata({
sampleRate: Number(transaction.sampled)
});
return transaction;
}
let sampleRate;
if (typeof options.tracesSampler === "function") {
sampleRate = options.tracesSampler(samplingContext);
transaction.setMetadata({
sampleRate: Number(sampleRate)
});
} else if (samplingContext.parentSampled !== void 0) {
sampleRate = samplingContext.parentSampled;
} else if (typeof options.tracesSampleRate !== "undefined") {
sampleRate = options.tracesSampleRate;
transaction.setMetadata({
sampleRate: Number(sampleRate)
});
} else {
sampleRate = 1;
transaction.setMetadata({
sampleRate
});
}
if (!isValidSampleRate(sampleRate)) {
DEBUG_BUILD2 && logger3.warn("[Tracing] Discarding transaction because of invalid sample rate.");
transaction.sampled = false;
return transaction;
}
if (!sampleRate) {
DEBUG_BUILD2 && logger3.log(
`[Tracing] Discarding transaction because ${typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`
);
transaction.sampled = false;
return transaction;
}
transaction.sampled = Math.random() < sampleRate;
if (!transaction.sampled) {
DEBUG_BUILD2 && logger3.log(
`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(
sampleRate
)})`
);
return transaction;
}
DEBUG_BUILD2 && logger3.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);
return transaction;
}
function isValidSampleRate(rate) {
if (isNaN2(rate) || !(typeof rate === "number" || typeof rate === "boolean")) {
DEBUG_BUILD2 && logger3.warn(
`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
rate
)} of type ${JSON.stringify(typeof rate)}.`
);
return false;
}
if (rate < 0 || rate > 1) {
DEBUG_BUILD2 && logger3.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
return false;
}
return true;
}
var init_sampling = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/sampling.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_hasTracingEnabled();
__name(sampleTransaction, "sampleTransaction");
__name(isValidSampleRate, "isValidSampleRate");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/hubextensions.js
function traceHeaders() {
const scope = this.getScope();
const span = scope.getSpan();
return span ? {
"sentry-trace": span.toTraceparent()
} : {};
}
function _startTransaction(transactionContext, customSamplingContext) {
const client = this.getClient();
const options = client && client.getOptions() || {};
const configInstrumenter = options.instrumenter || "sentry";
const transactionInstrumenter = transactionContext.instrumenter || "sentry";
if (configInstrumenter !== transactionInstrumenter) {
DEBUG_BUILD2 && logger3.error(
`A transaction was started with instrumenter=\`${transactionInstrumenter}\`, but the SDK is configured with the \`${configInstrumenter}\` instrumenter.
The transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`
);
transactionContext.sampled = false;
}
let transaction = new Transaction(transactionContext, this);
transaction = sampleTransaction(transaction, options, {
parentSampled: transactionContext.parentSampled,
transactionContext,
...customSamplingContext
});
if (transaction.sampled) {
transaction.initSpanRecorder(options._experiments && options._experiments.maxSpans);
}
if (client && client.emit) {
client.emit("startTransaction", transaction);
}
return transaction;
}
function addTracingExtensions() {
const carrier = getMainCarrier();
if (!carrier.__SENTRY__) {
return;
}
carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};
if (!carrier.__SENTRY__.extensions.startTransaction) {
carrier.__SENTRY__.extensions.startTransaction = _startTransaction;
}
if (!carrier.__SENTRY__.extensions.traceHeaders) {
carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;
}
registerErrorInstrumentation();
}
var init_hubextensions = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/hubextensions.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_hub();
init_errors4();
init_sampling();
init_transaction();
__name(traceHeaders, "traceHeaders");
__name(_startTransaction, "_startTransaction");
__name(addTracingExtensions, "addTracingExtensions");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/trace.js
function trace(context2, callback, onError = () => {
}) {
const ctx = normalizeContext(context2);
const hub = getCurrentHub();
const scope = hub.getScope();
const parentSpan = scope.getSpan();
const activeSpan = createChildSpanOrTransaction(hub, parentSpan, ctx);
scope.setSpan(activeSpan);
function finishAndSetSpan() {
activeSpan && activeSpan.finish();
hub.getScope().setSpan(parentSpan);
}
__name(finishAndSetSpan, "finishAndSetSpan");
let maybePromiseResult;
try {
maybePromiseResult = callback(activeSpan);
} catch (e7) {
activeSpan && activeSpan.setStatus("internal_error");
onError(e7);
finishAndSetSpan();
throw e7;
}
if (isThenable(maybePromiseResult)) {
Promise.resolve(maybePromiseResult).then(
() => {
finishAndSetSpan();
},
(e7) => {
activeSpan && activeSpan.setStatus("internal_error");
onError(e7);
finishAndSetSpan();
}
);
} else {
finishAndSetSpan();
}
return maybePromiseResult;
}
function createChildSpanOrTransaction(hub, parentSpan, ctx) {
if (!hasTracingEnabled()) {
return void 0;
}
return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);
}
function normalizeContext(context2) {
const ctx = { ...context2 };
if (ctx.name !== void 0 && ctx.description === void 0) {
ctx.description = ctx.name;
}
return ctx;
}
var init_trace = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/tracing/trace.js"() {
init_import_meta_url();
init_esm6();
init_hub();
init_hasTracingEnabled();
__name(trace, "trace");
__name(createChildSpanOrTransaction, "createChildSpanOrTransaction");
__name(normalizeContext, "normalizeContext");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/envelope.js
function enhanceEventWithSdkInfo(event, sdkInfo) {
if (!sdkInfo) {
return event;
}
event.sdk = event.sdk || {};
event.sdk.name = event.sdk.name || sdkInfo.name;
event.sdk.version = event.sdk.version || sdkInfo.version;
event.sdk.integrations = [...event.sdk.integrations || [], ...sdkInfo.integrations || []];
event.sdk.packages = [...event.sdk.packages || [], ...sdkInfo.packages || []];
return event;
}
function createSessionEnvelope(session, dsn, metadata, tunnel) {
const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
const envelopeHeaders = {
sent_at: (/* @__PURE__ */ new Date()).toISOString(),
...sdkInfo && { sdk: sdkInfo },
...!!tunnel && dsn && { dsn: dsnToString(dsn) }
};
const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()];
return createEnvelope(envelopeHeaders, [envelopeItem]);
}
function createEventEnvelope(event, dsn, metadata, tunnel) {
const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
enhanceEventWithSdkInfo(event, metadata && metadata.sdk);
const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);
delete event.sdkProcessingMetadata;
const eventItem = [{ type: eventType }, event];
return createEnvelope(envelopeHeaders, [eventItem]);
}
var init_envelope2 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/envelope.js"() {
init_import_meta_url();
init_esm6();
__name(enhanceEventWithSdkInfo, "enhanceEventWithSdkInfo");
__name(createSessionEnvelope, "createSessionEnvelope");
__name(createEventEnvelope, "createEventEnvelope");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/sessionflusher.js
var SessionFlusher;
var init_sessionflusher = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/sessionflusher.js"() {
init_import_meta_url();
init_esm6();
init_hub();
SessionFlusher = class {
static {
__name(this, "SessionFlusher");
}
constructor(client, attrs) {
this._client = client;
this.flushTimeout = 60;
this._pendingAggregates = {};
this._isEnabled = true;
this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1e3);
this._sessionAttrs = attrs;
}
/** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */
flush() {
const sessionAggregates = this.getSessionAggregates();
if (sessionAggregates.aggregates.length === 0) {
return;
}
this._pendingAggregates = {};
this._client.sendSession(sessionAggregates);
}
/** Massages the entries in `pendingAggregates` and returns aggregated sessions */
getSessionAggregates() {
const aggregates = Object.keys(this._pendingAggregates).map((key) => {
return this._pendingAggregates[parseInt(key)];
});
const sessionAggregates = {
attrs: this._sessionAttrs,
aggregates
};
return dropUndefinedKeys(sessionAggregates);
}
/** JSDoc */
close() {
clearInterval(this._intervalId);
this._isEnabled = false;
this.flush();
}
/**
* Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then
* fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to
* `_incrementSessionStatusCount` along with the start date
*/
incrementSessionStatusCount() {
if (!this._isEnabled) {
return;
}
const scope = getCurrentHub().getScope();
const requestSession = scope.getRequestSession();
if (requestSession && requestSession.status) {
this._incrementSessionStatusCount(requestSession.status, /* @__PURE__ */ new Date());
scope.setRequestSession(void 0);
}
}
/**
* Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of
* the session received
*/
_incrementSessionStatusCount(status2, date) {
const sessionStartedTrunc = new Date(date).setSeconds(0, 0);
this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};
const aggregationCounts = this._pendingAggregates[sessionStartedTrunc];
if (!aggregationCounts.started) {
aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();
}
switch (status2) {
case "errored":
aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;
return aggregationCounts.errored;
case "ok":
aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;
return aggregationCounts.exited;
default:
aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;
return aggregationCounts.crashed;
}
}
};
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/api.js
function getBaseApiEndpoint(dsn) {
const protocol = dsn.protocol ? `${dsn.protocol}:` : "";
const port = dsn.port ? `:${dsn.port}` : "";
return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`;
}
function _getIngestEndpoint(dsn) {
return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;
}
function _encodedAuth(dsn, sdkInfo) {
return urlEncode({
// We send only the minimum set of required information. See
// https://github.com/getsentry/sentry-javascript/issues/2572.
sentry_key: dsn.publicKey,
sentry_version: SENTRY_API_VERSION,
...sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }
});
}
function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnelOrOptions = {}) {
const tunnel = typeof tunnelOrOptions === "string" ? tunnelOrOptions : tunnelOrOptions.tunnel;
const sdkInfo = typeof tunnelOrOptions === "string" || !tunnelOrOptions._metadata ? void 0 : tunnelOrOptions._metadata.sdk;
return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;
}
var SENTRY_API_VERSION;
var init_api2 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/api.js"() {
init_import_meta_url();
init_esm6();
SENTRY_API_VERSION = "7";
__name(getBaseApiEndpoint, "getBaseApiEndpoint");
__name(_getIngestEndpoint, "_getIngestEndpoint");
__name(_encodedAuth, "_encodedAuth");
__name(getEnvelopeEndpointWithUrlEncodedAuth, "getEnvelopeEndpointWithUrlEncodedAuth");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integration.js
function filterDuplicates(integrations) {
const integrationsByName = {};
integrations.forEach((currentInstance) => {
const { name: name2 } = currentInstance;
const existingInstance = integrationsByName[name2];
if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {
return;
}
integrationsByName[name2] = currentInstance;
});
return Object.keys(integrationsByName).map((k6) => integrationsByName[k6]);
}
function getIntegrationsToSetup(options) {
const defaultIntegrations2 = options.defaultIntegrations || [];
const userIntegrations = options.integrations;
defaultIntegrations2.forEach((integration) => {
integration.isDefaultInstance = true;
});
let integrations;
if (Array.isArray(userIntegrations)) {
integrations = [...defaultIntegrations2, ...userIntegrations];
} else if (typeof userIntegrations === "function") {
integrations = arrayify(userIntegrations(defaultIntegrations2));
} else {
integrations = defaultIntegrations2;
}
const finalIntegrations = filterDuplicates(integrations);
const debugIndex = findIndex(finalIntegrations, (integration) => integration.name === "Debug");
if (debugIndex !== -1) {
const [debugInstance] = finalIntegrations.splice(debugIndex, 1);
finalIntegrations.push(debugInstance);
}
return finalIntegrations;
}
function setupIntegrations(client, integrations) {
const integrationIndex = {};
integrations.forEach((integration) => {
if (integration) {
setupIntegration(client, integration, integrationIndex);
}
});
return integrationIndex;
}
function setupIntegration(client, integration, integrationIndex) {
integrationIndex[integration.name] = integration;
if (installedIntegrations.indexOf(integration.name) === -1) {
integration.setupOnce(addGlobalEventProcessor, getCurrentHub);
installedIntegrations.push(integration.name);
}
if (integration.setup && typeof integration.setup === "function") {
integration.setup(client);
}
if (client.on && typeof integration.preprocessEvent === "function") {
const callback = integration.preprocessEvent.bind(integration);
client.on("preprocessEvent", (event, hint) => callback(event, hint, client));
}
if (client.addEventProcessor && typeof integration.processEvent === "function") {
const callback = integration.processEvent.bind(integration);
const processor = Object.assign((event, hint) => callback(event, hint, client), {
id: integration.name
});
client.addEventProcessor(processor);
}
DEBUG_BUILD2 && logger3.log(`Integration installed: ${integration.name}`);
}
function findIndex(arr, callback) {
for (let i5 = 0; i5 < arr.length; i5++) {
if (callback(arr[i5]) === true) {
return i5;
}
}
return -1;
}
var installedIntegrations;
var init_integration = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integration.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_eventProcessors();
init_hub();
installedIntegrations = [];
__name(filterDuplicates, "filterDuplicates");
__name(getIntegrationsToSetup, "getIntegrationsToSetup");
__name(setupIntegrations, "setupIntegrations");
__name(setupIntegration, "setupIntegration");
__name(findIndex, "findIndex");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/baseclient.js
function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) {
const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`;
if (isThenable(beforeSendResult)) {
return beforeSendResult.then(
(event) => {
if (!isPlainObject(event) && event !== null) {
throw new SentryError(invalidValueError);
}
return event;
},
(e7) => {
throw new SentryError(`${beforeSendLabel} rejected with ${e7}`);
}
);
} else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {
throw new SentryError(invalidValueError);
}
return beforeSendResult;
}
function processBeforeSend(options, event, hint) {
const { beforeSend, beforeSendTransaction } = options;
if (isErrorEvent2(event) && beforeSend) {
return beforeSend(event, hint);
}
if (isTransactionEvent(event) && beforeSendTransaction) {
return beforeSendTransaction(event, hint);
}
return event;
}
function isErrorEvent2(event) {
return event.type === void 0;
}
function isTransactionEvent(event) {
return event.type === "transaction";
}
var ALREADY_SEEN_ERROR, BaseClient;
var init_baseclient = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/baseclient.js"() {
init_import_meta_url();
init_esm6();
init_api2();
init_debug_build2();
init_envelope2();
init_integration();
init_session();
init_dynamicSamplingContext();
init_prepareEvent();
ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
BaseClient = class {
static {
__name(this, "BaseClient");
}
/** Options passed to the SDK. */
/** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */
/** Array of set up integrations. */
/** Indicates whether this client's integrations have been set up. */
/** Number of calls being processed */
/** Holds flushable */
// eslint-disable-next-line @typescript-eslint/ban-types
/**
* Initializes this client instance.
*
* @param options Options for the client.
*/
constructor(options) {
this._options = options;
this._integrations = {};
this._integrationsInitialized = false;
this._numProcessing = 0;
this._outcomes = {};
this._hooks = {};
this._eventProcessors = [];
if (options.dsn) {
this._dsn = makeDsn(options.dsn);
} else {
DEBUG_BUILD2 && logger3.warn("No DSN provided, client will not send events.");
}
if (this._dsn) {
const url4 = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);
this._transport = options.transport({
recordDroppedEvent: this.recordDroppedEvent.bind(this),
...options.transportOptions,
url: url4
});
}
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
captureException(exception, hint, scope) {
if (checkOrSetAlreadyCaught(exception)) {
DEBUG_BUILD2 && logger3.log(ALREADY_SEEN_ERROR);
return;
}
let eventId = hint && hint.event_id;
this._process(
this.eventFromException(exception, hint).then((event) => this._captureEvent(event, hint, scope)).then((result) => {
eventId = result;
})
);
return eventId;
}
/**
* @inheritDoc
*/
captureMessage(message, level, hint, scope) {
let eventId = hint && hint.event_id;
const promisedEvent = isPrimitive(message) ? this.eventFromMessage(String(message), level, hint) : this.eventFromException(message, hint);
this._process(
promisedEvent.then((event) => this._captureEvent(event, hint, scope)).then((result) => {
eventId = result;
})
);
return eventId;
}
/**
* @inheritDoc
*/
captureEvent(event, hint, scope) {
if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {
DEBUG_BUILD2 && logger3.log(ALREADY_SEEN_ERROR);
return;
}
let eventId = hint && hint.event_id;
this._process(
this._captureEvent(event, hint, scope).then((result) => {
eventId = result;
})
);
return eventId;
}
/**
* @inheritDoc
*/
captureSession(session) {
if (!(typeof session.release === "string")) {
DEBUG_BUILD2 && logger3.warn("Discarded session because of missing or non-string release");
} else {
this.sendSession(session);
updateSession(session, { init: false });
}
}
/**
* @inheritDoc
*/
getDsn() {
return this._dsn;
}
/**
* @inheritDoc
*/
getOptions() {
return this._options;
}
/**
* @see SdkMetadata in @sentry/types
*
* @return The metadata of the SDK
*/
getSdkMetadata() {
return this._options._metadata;
}
/**
* @inheritDoc
*/
getTransport() {
return this._transport;
}
/**
* @inheritDoc
*/
flush(timeout2) {
const transport = this._transport;
if (transport) {
return this._isClientDoneProcessing(timeout2).then((clientFinished) => {
return transport.flush(timeout2).then((transportFlushed) => clientFinished && transportFlushed);
});
} else {
return resolvedSyncPromise(true);
}
}
/**
* @inheritDoc
*/
close(timeout2) {
return this.flush(timeout2).then((result) => {
this.getOptions().enabled = false;
return result;
});
}
/** Get all installed event processors. */
getEventProcessors() {
return this._eventProcessors;
}
/** @inheritDoc */
addEventProcessor(eventProcessor) {
this._eventProcessors.push(eventProcessor);
}
/**
* Sets up the integrations
*/
setupIntegrations(forceInitialize) {
if (forceInitialize && !this._integrationsInitialized || this._isEnabled() && !this._integrationsInitialized) {
this._integrations = setupIntegrations(this, this._options.integrations);
this._integrationsInitialized = true;
}
}
/**
* Gets an installed integration by its `id`.
*
* @returns The installed integration or `undefined` if no integration with that `id` was installed.
*/
getIntegrationById(integrationId) {
return this._integrations[integrationId];
}
/**
* @inheritDoc
*/
getIntegration(integration) {
try {
return this._integrations[integration.id] || null;
} catch (_oO) {
DEBUG_BUILD2 && logger3.warn(`Cannot retrieve integration ${integration.id} from the current Client`);
return null;
}
}
/**
* @inheritDoc
*/
addIntegration(integration) {
setupIntegration(this, integration, this._integrations);
}
/**
* @inheritDoc
*/
sendEvent(event, hint = {}) {
this.emit("beforeSendEvent", event, hint);
let env6 = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);
for (const attachment of hint.attachments || []) {
env6 = addItemToEnvelope(
env6,
createAttachmentEnvelopeItem(
attachment,
this._options.transportOptions && this._options.transportOptions.textEncoder
)
);
}
const promise = this._sendEnvelope(env6);
if (promise) {
promise.then((sendResponse) => this.emit("afterSendEvent", event, sendResponse), null);
}
}
/**
* @inheritDoc
*/
sendSession(session) {
const env6 = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);
void this._sendEnvelope(env6);
}
/**
* @inheritDoc
*/
recordDroppedEvent(reason, category, _event) {
if (this._options.sendClientReports) {
const key = `${reason}:${category}`;
DEBUG_BUILD2 && logger3.log(`Adding outcome: "${key}"`);
this._outcomes[key] = this._outcomes[key] + 1 || 1;
}
}
// Keep on() & emit() signatures in sync with types' client.ts interface
/* eslint-disable @typescript-eslint/unified-signatures */
/** @inheritdoc */
/** @inheritdoc */
on(hook, callback) {
if (!this._hooks[hook]) {
this._hooks[hook] = [];
}
this._hooks[hook].push(callback);
}
/** @inheritdoc */
/** @inheritdoc */
emit(hook, ...rest) {
if (this._hooks[hook]) {
this._hooks[hook].forEach((callback) => callback(...rest));
}
}
/* eslint-enable @typescript-eslint/unified-signatures */
/** Updates existing session based on the provided event */
_updateSessionFromEvent(session, event) {
let crashed = false;
let errored = false;
const exceptions = event.exception && event.exception.values;
if (exceptions) {
errored = true;
for (const ex of exceptions) {
const mechanism = ex.mechanism;
if (mechanism && mechanism.handled === false) {
crashed = true;
break;
}
}
}
const sessionNonTerminal = session.status === "ok";
const shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed;
if (shouldUpdateAndSend) {
updateSession(session, {
...crashed && { status: "crashed" },
errors: session.errors || Number(errored || crashed)
});
this.captureSession(session);
}
}
/**
* Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying
* "no" (resolving to `false`) in order to give the client a chance to potentially finish first.
*
* @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not
* passing anything) will make the promise wait as long as it takes for processing to finish before resolving to
* `true`.
* @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and
* `false` otherwise
*/
_isClientDoneProcessing(timeout2) {
return new SyncPromise((resolve25) => {
let ticked = 0;
const tick = 1;
const interval = setInterval(() => {
if (this._numProcessing == 0) {
clearInterval(interval);
resolve25(true);
} else {
ticked += tick;
if (timeout2 && ticked >= timeout2) {
clearInterval(interval);
resolve25(false);
}
}
}, tick);
});
}
/** Determines whether this SDK is enabled and a transport is present. */
_isEnabled() {
return this.getOptions().enabled !== false && this._transport !== void 0;
}
/**
* Adds common information to events.
*
* The information includes release and environment from `options`,
* breadcrumbs and context (extra, tags and user) from the scope.
*
* Information that is already present in the event is never overwritten. For
* nested objects, such as the context, keys are merged.
*
* @param event The original event.
* @param hint May contain additional information about the original exception.
* @param scope A scope containing event metadata.
* @returns A new event with more information.
*/
_prepareEvent(event, hint, scope) {
const options = this.getOptions();
const integrations = Object.keys(this._integrations);
if (!hint.integrations && integrations.length > 0) {
hint.integrations = integrations;
}
this.emit("preprocessEvent", event, hint);
return prepareEvent(options, event, hint, scope, this).then((evt) => {
if (evt === null) {
return evt;
}
const { propagationContext } = evt.sdkProcessingMetadata || {};
const trace2 = evt.contexts && evt.contexts.trace;
if (!trace2 && propagationContext) {
const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;
evt.contexts = {
trace: {
trace_id,
span_id: spanId,
parent_span_id: parentSpanId
},
...evt.contexts
};
const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);
evt.sdkProcessingMetadata = {
dynamicSamplingContext,
...evt.sdkProcessingMetadata
};
}
return evt;
});
}
/**
* Processes the event and logs an error in case of rejection
* @param event
* @param hint
* @param scope
*/
_captureEvent(event, hint = {}, scope) {
return this._processEvent(event, hint, scope).then(
(finalEvent) => {
return finalEvent.event_id;
},
(reason) => {
if (DEBUG_BUILD2) {
const sentryError = reason;
if (sentryError.logLevel === "log") {
logger3.log(sentryError.message);
} else {
logger3.warn(sentryError);
}
}
return void 0;
}
);
}
/**
* Processes an event (either error or message) and sends it to Sentry.
*
* This also adds breadcrumbs and context information to the event. However,
* platform specific meta data (such as the User's IP address) must be added
* by the SDK implementor.
*
*
* @param event The event to send to Sentry.
* @param hint May contain additional information about the original exception.
* @param scope A scope containing event metadata.
* @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
*/
_processEvent(event, hint, scope) {
const options = this.getOptions();
const { sampleRate } = options;
const isTransaction = isTransactionEvent(event);
const isError2 = isErrorEvent2(event);
const eventType = event.type || "error";
const beforeSendLabel = `before send for type \`${eventType}\``;
if (isError2 && typeof sampleRate === "number" && Math.random() > sampleRate) {
this.recordDroppedEvent("sample_rate", "error", event);
return rejectedSyncPromise(
new SentryError(
`Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,
"log"
)
);
}
const dataCategory = eventType === "replay_event" ? "replay" : eventType;
return this._prepareEvent(event, hint, scope).then((prepared) => {
if (prepared === null) {
this.recordDroppedEvent("event_processor", dataCategory, event);
throw new SentryError("An event processor returned `null`, will not send event.", "log");
}
const isInternalException = hint.data && hint.data.__sentry__ === true;
if (isInternalException) {
return prepared;
}
const result = processBeforeSend(options, prepared, hint);
return _validateBeforeSendResult(result, beforeSendLabel);
}).then((processedEvent) => {
if (processedEvent === null) {
this.recordDroppedEvent("before_send", dataCategory, event);
throw new SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, "log");
}
const session = scope && scope.getSession();
if (!isTransaction && session) {
this._updateSessionFromEvent(session, processedEvent);
}
const transactionInfo = processedEvent.transaction_info;
if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {
const source = "custom";
processedEvent.transaction_info = {
...transactionInfo,
source
};
}
this.sendEvent(processedEvent, hint);
return processedEvent;
}).then(null, (reason) => {
if (reason instanceof SentryError) {
throw reason;
}
this.captureException(reason, {
data: {
__sentry__: true
},
originalException: reason
});
throw new SentryError(
`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
Reason: ${reason}`
);
});
}
/**
* Occupies the client with processing and event
*/
_process(promise) {
this._numProcessing++;
void promise.then(
(value) => {
this._numProcessing--;
return value;
},
(reason) => {
this._numProcessing--;
return reason;
}
);
}
/**
* @inheritdoc
*/
_sendEnvelope(envelope) {
this.emit("beforeEnvelope", envelope);
if (this._isEnabled() && this._transport) {
return this._transport.send(envelope).then(null, (reason) => {
DEBUG_BUILD2 && logger3.error("Error while sending event:", reason);
});
} else {
DEBUG_BUILD2 && logger3.error("Transport disabled");
}
}
/**
* Clears outcomes on this client and returns them.
*/
_clearOutcomes() {
const outcomes = this._outcomes;
this._outcomes = {};
return Object.keys(outcomes).map((key) => {
const [reason, category] = key.split(":");
return {
reason,
category,
quantity: outcomes[key]
};
});
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
};
__name(_validateBeforeSendResult, "_validateBeforeSendResult");
__name(processBeforeSend, "processBeforeSend");
__name(isErrorEvent2, "isErrorEvent");
__name(isTransactionEvent, "isTransactionEvent");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/checkin.js
function createCheckInEnvelope(checkIn, dynamicSamplingContext, metadata, tunnel, dsn) {
const headers = {
sent_at: (/* @__PURE__ */ new Date()).toISOString()
};
if (metadata && metadata.sdk) {
headers.sdk = {
name: metadata.sdk.name,
version: metadata.sdk.version
};
}
if (!!tunnel && !!dsn) {
headers.dsn = dsnToString(dsn);
}
if (dynamicSamplingContext) {
headers.trace = dropUndefinedKeys(dynamicSamplingContext);
}
const item = createCheckInEnvelopeItem(checkIn);
return createEnvelope(headers, [item]);
}
function createCheckInEnvelopeItem(checkIn) {
const checkInHeaders = {
type: "check_in"
};
return [checkInHeaders, checkIn];
}
var init_checkin = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/checkin.js"() {
init_import_meta_url();
init_esm6();
__name(createCheckInEnvelope, "createCheckInEnvelope");
__name(createCheckInEnvelopeItem, "createCheckInEnvelopeItem");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/server-runtime-client.js
var ServerRuntimeClient;
var init_server_runtime_client = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/server-runtime-client.js"() {
init_import_meta_url();
init_esm6();
init_baseclient();
init_checkin();
init_debug_build2();
init_hub();
init_sessionflusher();
init_hubextensions();
init_dynamicSamplingContext();
ServerRuntimeClient = class extends BaseClient {
static {
__name(this, "ServerRuntimeClient");
}
/**
* Creates a new Edge SDK instance.
* @param options Configuration options for this SDK.
*/
constructor(options) {
addTracingExtensions();
super(options);
}
/**
* @inheritDoc
*/
eventFromException(exception, hint) {
return resolvedSyncPromise(eventFromUnknownInput(getCurrentHub, this._options.stackParser, exception, hint));
}
/**
* @inheritDoc
*/
eventFromMessage(message, level = "info", hint) {
return resolvedSyncPromise(
eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace)
);
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
captureException(exception, hint, scope) {
if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
const requestSession = scope.getRequestSession();
if (requestSession && requestSession.status === "ok") {
requestSession.status = "errored";
}
}
return super.captureException(exception, hint, scope);
}
/**
* @inheritDoc
*/
captureEvent(event, hint, scope) {
if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
const eventType = event.type || "exception";
const isException = eventType === "exception" && event.exception && event.exception.values && event.exception.values.length > 0;
if (isException) {
const requestSession = scope.getRequestSession();
if (requestSession && requestSession.status === "ok") {
requestSession.status = "errored";
}
}
}
return super.captureEvent(event, hint, scope);
}
/**
*
* @inheritdoc
*/
close(timeout2) {
if (this._sessionFlusher) {
this._sessionFlusher.close();
}
return super.close(timeout2);
}
/** Method that initialises an instance of SessionFlusher on Client */
initSessionFlusher() {
const { release: release3, environment } = this._options;
if (!release3) {
DEBUG_BUILD2 && logger3.warn("Cannot initialise an instance of SessionFlusher if no release is provided!");
} else {
this._sessionFlusher = new SessionFlusher(this, {
release: release3,
environment
});
}
}
/**
* Create a cron monitor check in and send it to Sentry.
*
* @param checkIn An object that describes a check in.
* @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
* to create a monitor automatically when sending a check in.
*/
captureCheckIn(checkIn, monitorConfig, scope) {
const id = "checkInId" in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();
if (!this._isEnabled()) {
DEBUG_BUILD2 && logger3.warn("SDK not enabled, will not capture checkin.");
return id;
}
const options = this.getOptions();
const { release: release3, environment, tunnel } = options;
const serializedCheckIn = {
check_in_id: id,
monitor_slug: checkIn.monitorSlug,
status: checkIn.status,
release: release3,
environment
};
if ("duration" in checkIn) {
serializedCheckIn.duration = checkIn.duration;
}
if (monitorConfig) {
serializedCheckIn.monitor_config = {
schedule: monitorConfig.schedule,
checkin_margin: monitorConfig.checkinMargin,
max_runtime: monitorConfig.maxRuntime,
timezone: monitorConfig.timezone
};
}
const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope);
if (traceContext) {
serializedCheckIn.contexts = {
trace: traceContext
};
}
const envelope = createCheckInEnvelope(
serializedCheckIn,
dynamicSamplingContext,
this.getSdkMetadata(),
tunnel,
this.getDsn()
);
DEBUG_BUILD2 && logger3.info("Sending checkin:", checkIn.monitorSlug, checkIn.status);
void this._sendEnvelope(envelope);
return id;
}
/**
* Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment
* appropriate session aggregates bucket
*/
_captureRequestSession() {
if (!this._sessionFlusher) {
DEBUG_BUILD2 && logger3.warn("Discarded request mode session because autoSessionTracking option was disabled");
} else {
this._sessionFlusher.incrementSessionStatusCount();
}
}
/**
* @inheritDoc
*/
_prepareEvent(event, hint, scope) {
if (this._options.platform) {
event.platform = event.platform || this._options.platform;
}
if (this._options.runtime) {
event.contexts = {
...event.contexts,
runtime: (event.contexts || {}).runtime || this._options.runtime
};
}
if (this._options.serverName) {
event.server_name = event.server_name || this._options.serverName;
}
return super._prepareEvent(event, hint, scope);
}
/** Extract trace information from scope */
_getTraceInfoFromScope(scope) {
if (!scope) {
return [void 0, void 0];
}
const span = scope.getSpan();
if (span) {
const samplingContext = span.transaction ? span.transaction.getDynamicSamplingContext() : void 0;
return [samplingContext, span.getTraceContext()];
}
const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext();
const traceContext = {
trace_id: traceId,
span_id: spanId,
parent_span_id: parentSpanId
};
if (dsc) {
return [dsc, traceContext];
}
return [getDynamicSamplingContextFromClient(traceId, this, scope), traceContext];
}
};
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/sdk.js
function initAndBind(clientClass, options) {
if (options.debug === true) {
if (DEBUG_BUILD2) {
logger3.enable();
} else {
consoleSandbox(() => {
console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.");
});
}
}
const hub = getCurrentHub();
const scope = hub.getScope();
scope.update(options.initialScope);
const client = new clientClass(options);
hub.bindClient(client);
}
var init_sdk = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/sdk.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
init_hub();
__name(initAndBind, "initAndBind");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/transports/base.js
function createTransport(options, makeRequest, buffer = makePromiseBuffer(
options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE
)) {
let rateLimits = {};
const flush2 = /* @__PURE__ */ __name((timeout2) => buffer.drain(timeout2), "flush");
function send(envelope) {
const filteredEnvelopeItems = [];
forEachEnvelopeItem(envelope, (item, type) => {
const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);
if (isRateLimited(rateLimits, envelopeItemDataCategory)) {
const event = getEventForEnvelopeItem(item, type);
options.recordDroppedEvent("ratelimit_backoff", envelopeItemDataCategory, event);
} else {
filteredEnvelopeItems.push(item);
}
});
if (filteredEnvelopeItems.length === 0) {
return resolvedSyncPromise();
}
const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems);
const recordEnvelopeLoss = /* @__PURE__ */ __name((reason) => {
forEachEnvelopeItem(filteredEnvelope, (item, type) => {
const event = getEventForEnvelopeItem(item, type);
options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);
});
}, "recordEnvelopeLoss");
const requestTask = /* @__PURE__ */ __name(() => makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(
(response) => {
if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) {
DEBUG_BUILD2 && logger3.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
}
rateLimits = updateRateLimits(rateLimits, response);
return response;
},
(error2) => {
recordEnvelopeLoss("network_error");
throw error2;
}
), "requestTask");
return buffer.add(requestTask).then(
(result) => result,
(error2) => {
if (error2 instanceof SentryError) {
DEBUG_BUILD2 && logger3.error("Skipped sending event because buffer is full.");
recordEnvelopeLoss("queue_overflow");
return resolvedSyncPromise();
} else {
throw error2;
}
}
);
}
__name(send, "send");
send.__sentry__baseTransport__ = true;
return {
send,
flush: flush2
};
}
function getEventForEnvelopeItem(item, type) {
if (type !== "event" && type !== "transaction") {
return void 0;
}
return Array.isArray(item) ? item[1] : void 0;
}
var DEFAULT_TRANSPORT_BUFFER_SIZE;
var init_base = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/transports/base.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
DEFAULT_TRANSPORT_BUFFER_SIZE = 30;
__name(createTransport, "createTransport");
__name(getEventForEnvelopeItem, "getEventForEnvelopeItem");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/functiontostring.js
var originalFunctionToString, FunctionToString;
var init_functiontostring = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/functiontostring.js"() {
init_import_meta_url();
init_esm6();
FunctionToString = class _FunctionToString {
static {
__name(this, "FunctionToString");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "FunctionToString";
}
/**
* @inheritDoc
*/
constructor() {
this.name = _FunctionToString.id;
}
/**
* @inheritDoc
*/
setupOnce() {
originalFunctionToString = Function.prototype.toString;
try {
Function.prototype.toString = function(...args) {
const context2 = getOriginalFunction(this) || this;
return originalFunctionToString.apply(context2, args);
};
} catch (e7) {
}
}
};
FunctionToString.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/inboundfilters.js
function _mergeOptions(internalOptions = {}, clientOptions = {}) {
return {
allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []],
denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []],
ignoreErrors: [
...internalOptions.ignoreErrors || [],
...clientOptions.ignoreErrors || [],
...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS
],
ignoreTransactions: [
...internalOptions.ignoreTransactions || [],
...clientOptions.ignoreTransactions || [],
...internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS
],
ignoreInternal: internalOptions.ignoreInternal !== void 0 ? internalOptions.ignoreInternal : true
};
}
function _shouldDropEvent(event, options) {
if (options.ignoreInternal && _isSentryError(event)) {
DEBUG_BUILD2 && logger3.warn(`Event dropped due to being internal Sentry Error.
Event: ${getEventDescription(event)}`);
return true;
}
if (_isIgnoredError(event, options.ignoreErrors)) {
DEBUG_BUILD2 && logger3.warn(
`Event dropped due to being matched by \`ignoreErrors\` option.
Event: ${getEventDescription(event)}`
);
return true;
}
if (_isIgnoredTransaction(event, options.ignoreTransactions)) {
DEBUG_BUILD2 && logger3.warn(
`Event dropped due to being matched by \`ignoreTransactions\` option.
Event: ${getEventDescription(event)}`
);
return true;
}
if (_isDeniedUrl(event, options.denyUrls)) {
DEBUG_BUILD2 && logger3.warn(
`Event dropped due to being matched by \`denyUrls\` option.
Event: ${getEventDescription(
event
)}.
Url: ${_getEventFilterUrl(event)}`
);
return true;
}
if (!_isAllowedUrl(event, options.allowUrls)) {
DEBUG_BUILD2 && logger3.warn(
`Event dropped due to not being matched by \`allowUrls\` option.
Event: ${getEventDescription(
event
)}.
Url: ${_getEventFilterUrl(event)}`
);
return true;
}
return false;
}
function _isIgnoredError(event, ignoreErrors) {
if (event.type || !ignoreErrors || !ignoreErrors.length) {
return false;
}
return _getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors));
}
function _isIgnoredTransaction(event, ignoreTransactions) {
if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) {
return false;
}
const name2 = event.transaction;
return name2 ? stringMatchesSomePattern(name2, ignoreTransactions) : false;
}
function _isDeniedUrl(event, denyUrls) {
if (!denyUrls || !denyUrls.length) {
return false;
}
const url4 = _getEventFilterUrl(event);
return !url4 ? false : stringMatchesSomePattern(url4, denyUrls);
}
function _isAllowedUrl(event, allowUrls) {
if (!allowUrls || !allowUrls.length) {
return true;
}
const url4 = _getEventFilterUrl(event);
return !url4 ? true : stringMatchesSomePattern(url4, allowUrls);
}
function _getPossibleEventMessages(event) {
const possibleMessages = [];
if (event.message) {
possibleMessages.push(event.message);
}
let lastException;
try {
lastException = event.exception.values[event.exception.values.length - 1];
} catch (e7) {
}
if (lastException) {
if (lastException.value) {
possibleMessages.push(lastException.value);
if (lastException.type) {
possibleMessages.push(`${lastException.type}: ${lastException.value}`);
}
}
}
if (DEBUG_BUILD2 && possibleMessages.length === 0) {
logger3.error(`Could not extract message for event ${getEventDescription(event)}`);
}
return possibleMessages;
}
function _isSentryError(event) {
try {
return event.exception.values[0].type === "SentryError";
} catch (e7) {
}
return false;
}
function _getLastValidUrl(frames = []) {
for (let i5 = frames.length - 1; i5 >= 0; i5--) {
const frame = frames[i5];
if (frame && frame.filename !== "<anonymous>" && frame.filename !== "[native code]") {
return frame.filename || null;
}
}
return null;
}
function _getEventFilterUrl(event) {
try {
let frames;
try {
frames = event.exception.values[0].stacktrace.frames;
} catch (e7) {
}
return frames ? _getLastValidUrl(frames) : null;
} catch (oO) {
DEBUG_BUILD2 && logger3.error(`Cannot extract url for event ${getEventDescription(event)}`);
return null;
}
}
var DEFAULT_IGNORE_ERRORS, DEFAULT_IGNORE_TRANSACTIONS, InboundFilters;
var init_inboundfilters = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/inboundfilters.js"() {
init_import_meta_url();
init_esm6();
init_debug_build2();
DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/];
DEFAULT_IGNORE_TRANSACTIONS = [
/^.*\/healthcheck$/,
/^.*\/healthy$/,
/^.*\/live$/,
/^.*\/ready$/,
/^.*\/heartbeat$/,
/^.*\/health$/,
/^.*\/healthz$/
];
InboundFilters = class _InboundFilters {
static {
__name(this, "InboundFilters");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "InboundFilters";
}
/**
* @inheritDoc
*/
constructor(options = {}) {
this.name = _InboundFilters.id;
this._options = options;
}
/**
* @inheritDoc
*/
setupOnce(_addGlobalEventProcessor, _getCurrentHub) {
}
/** @inheritDoc */
processEvent(event, _eventHint, client) {
const clientOptions = client.getOptions();
const options = _mergeOptions(this._options, clientOptions);
return _shouldDropEvent(event, options) ? null : event;
}
};
InboundFilters.__initStatic();
__name(_mergeOptions, "_mergeOptions");
__name(_shouldDropEvent, "_shouldDropEvent");
__name(_isIgnoredError, "_isIgnoredError");
__name(_isIgnoredTransaction, "_isIgnoredTransaction");
__name(_isDeniedUrl, "_isDeniedUrl");
__name(_isAllowedUrl, "_isAllowedUrl");
__name(_getPossibleEventMessages, "_getPossibleEventMessages");
__name(_isSentryError, "_isSentryError");
__name(_getLastValidUrl, "_getLastValidUrl");
__name(_getEventFilterUrl, "_getEventFilterUrl");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/linkederrors.js
var DEFAULT_KEY, DEFAULT_LIMIT, LinkedErrors;
var init_linkederrors = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/linkederrors.js"() {
init_import_meta_url();
init_esm6();
DEFAULT_KEY = "cause";
DEFAULT_LIMIT = 5;
LinkedErrors = class _LinkedErrors {
static {
__name(this, "LinkedErrors");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "LinkedErrors";
}
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
constructor(options = {}) {
this._key = options.key || DEFAULT_KEY;
this._limit = options.limit || DEFAULT_LIMIT;
this.name = _LinkedErrors.id;
}
/** @inheritdoc */
setupOnce() {
}
/**
* @inheritDoc
*/
preprocessEvent(event, hint, client) {
const options = client.getOptions();
applyAggregateErrorsToEvent(
exceptionFromError,
options.stackParser,
options.maxValueLength,
this._key,
this._limit,
event,
hint
);
}
};
LinkedErrors.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/index.js
var integrations_exports = {};
__export(integrations_exports, {
FunctionToString: () => FunctionToString,
InboundFilters: () => InboundFilters,
LinkedErrors: () => LinkedErrors
});
var init_integrations = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/index.js"() {
init_import_meta_url();
init_functiontostring();
init_inboundfilters();
init_linkederrors();
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/utils/isSentryRequestUrl.js
function isSentryRequestUrl(url4, hub) {
const client = hub.getClient();
const dsn = client && client.getDsn();
const tunnel = client && client.getOptions().tunnel;
return checkDsn(url4, dsn) || checkTunnel(url4, tunnel);
}
function checkTunnel(url4, tunnel) {
if (!tunnel) {
return false;
}
return removeTrailingSlash(url4) === removeTrailingSlash(tunnel);
}
function checkDsn(url4, dsn) {
return dsn ? url4.includes(dsn.host) : false;
}
function removeTrailingSlash(str) {
return str[str.length - 1] === "/" ? str.slice(0, -1) : str;
}
var init_isSentryRequestUrl = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/utils/isSentryRequestUrl.js"() {
init_import_meta_url();
__name(isSentryRequestUrl, "isSentryRequestUrl");
__name(checkTunnel, "checkTunnel");
__name(checkDsn, "checkDsn");
__name(removeTrailingSlash, "removeTrailingSlash");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/requestdata.js
function convertReqDataIntegrationOptsToAddReqDataOpts(integrationOptions) {
const {
transactionNamingScheme,
include: { ip, user, ...requestOptions }
} = integrationOptions;
const requestIncludeKeys = [];
for (const [key, value] of Object.entries(requestOptions)) {
if (value) {
requestIncludeKeys.push(key);
}
}
let addReqDataUserOpt;
if (user === void 0) {
addReqDataUserOpt = true;
} else if (typeof user === "boolean") {
addReqDataUserOpt = user;
} else {
const userIncludeKeys = [];
for (const [key, value] of Object.entries(user)) {
if (value) {
userIncludeKeys.push(key);
}
}
addReqDataUserOpt = userIncludeKeys;
}
return {
include: {
ip,
user: addReqDataUserOpt,
request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : void 0,
transaction: transactionNamingScheme
}
};
}
function getSDKName(hub) {
try {
return hub.getClient().getOptions()._metadata.sdk.name;
} catch (err) {
return void 0;
}
}
var DEFAULT_OPTIONS, RequestData;
var init_requestdata2 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/integrations/requestdata.js"() {
init_import_meta_url();
init_esm6();
DEFAULT_OPTIONS = {
include: {
cookies: true,
data: true,
headers: true,
ip: false,
query_string: true,
url: true,
user: {
id: true,
username: true,
email: true
}
},
transactionNamingScheme: "methodPath"
};
RequestData = class _RequestData {
static {
__name(this, "RequestData");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "RequestData";
}
/**
* @inheritDoc
*/
/**
* Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but
* left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use
* something similar in browser-based SDKs in the future.
*/
/**
* @inheritDoc
*/
constructor(options = {}) {
this.name = _RequestData.id;
this._addRequestData = addRequestDataToEvent;
this._options = {
...DEFAULT_OPTIONS,
...options,
include: {
// @ts-expect-error It's mad because `method` isn't a known `include` key. (It's only here and not set by default in
// `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.)
method: true,
...DEFAULT_OPTIONS.include,
...options.include,
user: options.include && typeof options.include.user === "boolean" ? options.include.user : {
...DEFAULT_OPTIONS.include.user,
// Unclear why TS still thinks `options.include.user` could be a boolean at this point
...(options.include || {}).user
}
}
};
}
/**
* @inheritDoc
*/
setupOnce(addGlobalEventProcessor2, getCurrentHub3) {
const { transactionNamingScheme } = this._options;
addGlobalEventProcessor2((event) => {
const hub = getCurrentHub3();
const self2 = hub.getIntegration(_RequestData);
const { sdkProcessingMetadata = {} } = event;
const req = sdkProcessingMetadata.request;
if (!self2 || !req) {
return event;
}
const addRequestDataOptions = sdkProcessingMetadata.requestDataOptionsFromExpressHandler || sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || convertReqDataIntegrationOptsToAddReqDataOpts(this._options);
const processedEvent = this._addRequestData(event, req, addRequestDataOptions);
if (event.type === "transaction" || transactionNamingScheme === "handler") {
return processedEvent;
}
const reqWithTransaction = req;
const transaction = reqWithTransaction._sentryTransaction;
if (transaction) {
const shouldIncludeMethodInTransactionName = getSDKName(hub) === "sentry.javascript.nextjs" ? transaction.name.startsWith("/api") : transactionNamingScheme !== "path";
const [transactionValue] = extractPathForTransaction(req, {
path: true,
method: shouldIncludeMethodInTransactionName,
customRoute: transaction.name
});
processedEvent.transaction = transactionValue;
}
return processedEvent;
});
}
};
RequestData.__initStatic();
__name(convertReqDataIntegrationOptsToAddReqDataOpts, "convertReqDataIntegrationOptsToAddReqDataOpts");
__name(getSDKName, "getSDKName");
}
});
// ../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/index.js
var init_esm7 = __esm({
"../../node_modules/.pnpm/@sentry+core@7.87.0/node_modules/@sentry/core/esm/index.js"() {
init_import_meta_url();
init_trace();
init_dynamicSamplingContext();
init_exports();
init_hub();
init_server_runtime_client();
init_sdk();
init_base();
init_version();
init_integration();
init_integrations();
init_isSentryRequestUrl();
init_requestdata2();
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/common/debug-build.js
var DEBUG_BUILD3;
var init_debug_build3 = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/common/debug-build.js"() {
init_import_meta_url();
DEBUG_BUILD3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/utils/node-utils.js
function shouldDisableAutoInstrumentation(getCurrentHub3) {
const clientOptions = _optionalChain([getCurrentHub3, "call", (_4) => _4(), "access", (_22) => _22.getClient, "call", (_32) => _32(), "optionalAccess", (_4) => _4.getOptions, "call", (_5) => _5()]);
const instrumenter = _optionalChain([clientOptions, "optionalAccess", (_6) => _6.instrumenter]) || "sentry";
return instrumenter !== "sentry";
}
var init_node_utils = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/utils/node-utils.js"() {
init_import_meta_url();
init_esm6();
__name(shouldDisableAutoInstrumentation, "shouldDisableAutoInstrumentation");
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/express.js
function wrap3(fn2, method) {
const arity = fn2.length;
switch (arity) {
case 2: {
return function(req, res) {
const transaction = res.__sentry_transaction;
if (transaction) {
const span = transaction.startChild({
description: fn2.name,
op: `middleware.express.${method}`,
origin: "auto.middleware.express"
});
res.once("finish", () => {
span.finish();
});
}
return fn2.call(this, req, res);
};
}
case 3: {
return function(req, res, next) {
const transaction = res.__sentry_transaction;
const span = _optionalChain([transaction, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32({
description: fn2.name,
op: `middleware.express.${method}`,
origin: "auto.middleware.express"
})]);
fn2.call(this, req, res, function(...args) {
_optionalChain([span, "optionalAccess", (_4) => _4.finish, "call", (_5) => _5()]);
next.call(this, ...args);
});
};
}
case 4: {
return function(err, req, res, next) {
const transaction = res.__sentry_transaction;
const span = _optionalChain([transaction, "optionalAccess", (_6) => _6.startChild, "call", (_7) => _7({
description: fn2.name,
op: `middleware.express.${method}`,
origin: "auto.middleware.express"
})]);
fn2.call(this, err, req, res, function(...args) {
_optionalChain([span, "optionalAccess", (_8) => _8.finish, "call", (_9) => _9()]);
next.call(this, ...args);
});
};
}
default: {
throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);
}
}
}
function wrapMiddlewareArgs(args, method) {
return args.map((arg) => {
if (typeof arg === "function") {
return wrap3(arg, method);
}
if (Array.isArray(arg)) {
return arg.map((a5) => {
if (typeof a5 === "function") {
return wrap3(a5, method);
}
return a5;
});
}
return arg;
});
}
function patchMiddleware(router, method) {
const originalCallback = router[method];
router[method] = function(...args) {
return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));
};
return router;
}
function instrumentMiddlewares(router, methods = []) {
methods.forEach((method) => patchMiddleware(router, method));
}
function instrumentRouter(appOrRouter) {
const isApp = "settings" in appOrRouter;
if (isApp && appOrRouter._router === void 0 && appOrRouter.lazyrouter) {
appOrRouter.lazyrouter();
}
const router = isApp ? appOrRouter._router : appOrRouter;
if (!router) {
DEBUG_BUILD3 && logger3.debug("Cannot instrument router for URL Parameterization (did not find a valid router).");
DEBUG_BUILD3 && logger3.debug("Routing instrumentation is currently only supported in Express 4.");
return;
}
const routerProto = Object.getPrototypeOf(router);
const originalProcessParams = routerProto.process_params;
routerProto.process_params = /* @__PURE__ */ __name(function process_params(layer, called, req, res, done) {
if (!req._reconstructedRoute) {
req._reconstructedRoute = "";
}
const { layerRoutePath, isRegex, isArray, numExtraSegments } = getLayerRoutePathInfo(layer);
if (layerRoutePath || isRegex || isArray) {
req._hasParameters = true;
}
let partialRoute;
if (layerRoutePath) {
partialRoute = layerRoutePath;
} else {
partialRoute = preventDuplicateSegments(req.originalUrl, req._reconstructedRoute, layer.path) || "";
}
const finalPartialRoute = partialRoute.split("/").filter((segment) => segment.length > 0 && (isRegex || isArray || !segment.includes("*"))).join("/");
if (finalPartialRoute && finalPartialRoute.length > 0) {
req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? "/" : ""}`;
}
const urlLength = getNumberOfUrlSegments(stripUrlQueryAndFragment(req.originalUrl || "")) + numExtraSegments;
const routeLength = getNumberOfUrlSegments(req._reconstructedRoute);
if (urlLength === routeLength) {
if (!req._hasParameters) {
if (req._reconstructedRoute !== req.originalUrl) {
req._reconstructedRoute = req.originalUrl ? stripUrlQueryAndFragment(req.originalUrl) : req.originalUrl;
}
}
const transaction = res.__sentry_transaction;
if (transaction && transaction.metadata.source !== "custom") {
const finalRoute = req._reconstructedRoute || "/";
transaction.setName(...extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute }));
}
}
return originalProcessParams.call(this, layer, called, req, res, done);
}, "process_params");
}
function getLayerRoutePathInfo(layer) {
let lrp = _optionalChain([layer, "access", (_12) => _12.route, "optionalAccess", (_13) => _13.path]);
const isRegex = isRegExp(lrp);
const isArray = Array.isArray(lrp);
if (!lrp) {
const [major] = GLOBAL_OBJ.process.versions.node.split(".").map(Number);
if (major >= 16) {
lrp = extractOriginalRoute(layer.path, layer.regexp, layer.keys);
}
}
if (!lrp) {
return { isRegex, isArray, numExtraSegments: 0 };
}
const numExtraSegments = isArray ? Math.max(getNumberOfArrayUrlSegments(lrp) - getNumberOfUrlSegments(layer.path || ""), 0) : 0;
const layerRoutePath = getLayerRoutePathString(isArray, lrp);
return { layerRoutePath, isRegex, isArray, numExtraSegments };
}
function getNumberOfArrayUrlSegments(routesArray) {
return routesArray.reduce((accNumSegments, currentRoute) => {
return accNumSegments + getNumberOfUrlSegments(currentRoute.toString());
}, 0);
}
function getLayerRoutePathString(isArray, lrp) {
if (isArray) {
return lrp.map((r7) => r7.toString()).join(",");
}
return lrp && lrp.toString();
}
function preventDuplicateSegments(originalUrl, reconstructedRoute, layerPath) {
const normalizeURL = stripUrlQueryAndFragment(originalUrl || "");
const originalUrlSplit = _optionalChain([normalizeURL, "optionalAccess", (_14) => _14.split, "call", (_15) => _15("/"), "access", (_16) => _16.filter, "call", (_17) => _17((v7) => !!v7)]);
let tempCounter = 0;
const currentOffset = _optionalChain([reconstructedRoute, "optionalAccess", (_18) => _18.split, "call", (_19) => _19("/"), "access", (_20) => _20.filter, "call", (_21) => _21((v7) => !!v7), "access", (_22) => _22.length]) || 0;
const result = _optionalChain([
layerPath,
"optionalAccess",
(_23) => _23.split,
"call",
(_24) => _24("/"),
"access",
(_25) => _25.filter,
"call",
(_26) => _26((segment) => {
if (_optionalChain([originalUrlSplit, "optionalAccess", (_27) => _27[currentOffset + tempCounter]]) === segment) {
tempCounter += 1;
return true;
}
return false;
}),
"access",
(_28) => _28.join,
"call",
(_29) => _29("/")
]);
return result;
}
var Express, extractOriginalRoute;
var init_express = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/express.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_debug_build3();
init_node_utils();
Express = class _Express {
static {
__name(this, "Express");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Express";
}
/**
* @inheritDoc
*/
/**
* Express App instance
*/
/**
* @inheritDoc
*/
constructor(options = {}) {
this.name = _Express.id;
this._router = options.router || options.app;
this._methods = (Array.isArray(options.methods) ? options.methods : []).concat("use");
}
/**
* @inheritDoc
*/
setupOnce(_4, getCurrentHub3) {
if (!this._router) {
DEBUG_BUILD3 && logger3.error("ExpressIntegration is missing an Express instance");
return;
}
if (shouldDisableAutoInstrumentation(getCurrentHub3)) {
DEBUG_BUILD3 && logger3.log("Express Integration is skipped because of instrumenter configuration.");
return;
}
instrumentMiddlewares(this._router, this._methods);
instrumentRouter(this._router);
}
};
Express.__initStatic();
__name(wrap3, "wrap");
__name(wrapMiddlewareArgs, "wrapMiddlewareArgs");
__name(patchMiddleware, "patchMiddleware");
__name(instrumentMiddlewares, "instrumentMiddlewares");
__name(instrumentRouter, "instrumentRouter");
extractOriginalRoute = /* @__PURE__ */ __name((path72, regexp, keys) => {
if (!path72 || !regexp || !keys || Object.keys(keys).length === 0 || !_optionalChain([keys, "access", (_10) => _10[0], "optionalAccess", (_11) => _11.offset])) {
return void 0;
}
const orderedKeys = keys.sort((a5, b6) => a5.offset - b6.offset);
const pathRegex = new RegExp(regexp, `${regexp.flags}d`);
const execResult = pathRegex.exec(path72);
if (!execResult || !execResult.indices) {
return void 0;
}
const [, ...paramIndices] = execResult.indices;
if (paramIndices.length !== orderedKeys.length) {
return void 0;
}
let resultPath = path72;
let indexShift = 0;
paramIndices.forEach((item, index) => {
if (item) {
const [startOffset, endOffset] = item;
const substr1 = resultPath.substring(0, startOffset - indexShift);
const replacement = `:${orderedKeys[index].name}`;
const substr2 = resultPath.substring(endOffset - indexShift);
resultPath = substr1 + replacement + substr2;
indexShift = indexShift + (endOffset - startOffset - replacement.length);
}
});
return resultPath;
}, "extractOriginalRoute");
__name(getLayerRoutePathInfo, "getLayerRoutePathInfo");
__name(getNumberOfArrayUrlSegments, "getNumberOfArrayUrlSegments");
__name(getLayerRoutePathString, "getLayerRoutePathString");
__name(preventDuplicateSegments, "preventDuplicateSegments");
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/postgres.js
var Postgres;
var init_postgres = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/postgres.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_debug_build3();
init_node_utils();
Postgres = class _Postgres {
static {
__name(this, "Postgres");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Postgres";
}
/**
* @inheritDoc
*/
constructor(options = {}) {
this.name = _Postgres.id;
this._usePgNative = !!options.usePgNative;
this._module = options.module;
}
/** @inheritdoc */
loadDependency() {
return this._module = this._module || loadModule("pg");
}
/**
* @inheritDoc
*/
setupOnce(_4, getCurrentHub3) {
if (shouldDisableAutoInstrumentation(getCurrentHub3)) {
DEBUG_BUILD3 && logger3.log("Postgres Integration is skipped because of instrumenter configuration.");
return;
}
const pkg = this.loadDependency();
if (!pkg) {
DEBUG_BUILD3 && logger3.error("Postgres Integration was unable to require `pg` package.");
return;
}
const Client2 = this._usePgNative ? _optionalChain([pkg, "access", (_22) => _22.native, "optionalAccess", (_32) => _32.Client]) : pkg.Client;
if (!Client2) {
DEBUG_BUILD3 && logger3.error("Postgres Integration was unable to access 'pg-native' bindings.");
return;
}
fill(Client2.prototype, "query", function(orig) {
return function(config, values, callback) {
const scope = getCurrentHub3().getScope();
const parentSpan = scope.getSpan();
const data = {
"db.system": "postgresql"
};
try {
if (this.database) {
data["db.name"] = this.database;
}
if (this.host) {
data["server.address"] = this.host;
}
if (this.port) {
data["server.port"] = this.port;
}
if (this.user) {
data["db.user"] = this.user;
}
} catch (e7) {
}
const span = _optionalChain([parentSpan, "optionalAccess", (_42) => _42.startChild, "call", (_5) => _5({
description: typeof config === "string" ? config : config.text,
op: "db",
origin: "auto.db.postgres",
data
})]);
if (typeof callback === "function") {
return orig.call(this, config, values, function(err, result) {
_optionalChain([span, "optionalAccess", (_6) => _6.finish, "call", (_7) => _7()]);
callback(err, result);
});
}
if (typeof values === "function") {
return orig.call(this, config, function(err, result) {
_optionalChain([span, "optionalAccess", (_8) => _8.finish, "call", (_9) => _9()]);
values(err, result);
});
}
const rv = typeof values !== "undefined" ? orig.call(this, config, values) : orig.call(this, config);
if (isThenable(rv)) {
return rv.then((res) => {
_optionalChain([span, "optionalAccess", (_10) => _10.finish, "call", (_11) => _11()]);
return res;
});
}
_optionalChain([span, "optionalAccess", (_12) => _12.finish, "call", (_13) => _13()]);
return rv;
};
});
}
};
Postgres.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/mysql.js
var Mysql;
var init_mysql = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/mysql.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_debug_build3();
init_node_utils();
Mysql = class _Mysql {
static {
__name(this, "Mysql");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Mysql";
}
/**
* @inheritDoc
*/
constructor() {
this.name = _Mysql.id;
}
/** @inheritdoc */
loadDependency() {
return this._module = this._module || loadModule("mysql/lib/Connection.js");
}
/**
* @inheritDoc
*/
setupOnce(_4, getCurrentHub3) {
if (shouldDisableAutoInstrumentation(getCurrentHub3)) {
DEBUG_BUILD3 && logger3.log("Mysql Integration is skipped because of instrumenter configuration.");
return;
}
const pkg = this.loadDependency();
if (!pkg) {
DEBUG_BUILD3 && logger3.error("Mysql Integration was unable to require `mysql` package.");
return;
}
let mySqlConfig = void 0;
try {
pkg.prototype.connect = new Proxy(pkg.prototype.connect, {
apply(wrappingTarget, thisArg, args) {
if (!mySqlConfig) {
mySqlConfig = thisArg.config;
}
return wrappingTarget.apply(thisArg, args);
}
});
} catch (e7) {
DEBUG_BUILD3 && logger3.error("Mysql Integration was unable to instrument `mysql` config.");
}
function spanDataFromConfig() {
if (!mySqlConfig) {
return {};
}
return {
"server.address": mySqlConfig.host,
"server.port": mySqlConfig.port,
"db.user": mySqlConfig.user
};
}
__name(spanDataFromConfig, "spanDataFromConfig");
function finishSpan(span) {
if (!span || span.endTimestamp) {
return;
}
const data = spanDataFromConfig();
Object.keys(data).forEach((key) => {
span.setData(key, data[key]);
});
span.finish();
}
__name(finishSpan, "finishSpan");
fill(pkg, "createQuery", function(orig) {
return function(options, values, callback) {
const scope = getCurrentHub3().getScope();
const parentSpan = scope.getSpan();
const span = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32({
description: typeof options === "string" ? options : options.sql,
op: "db",
origin: "auto.db.mysql",
data: {
"db.system": "mysql"
}
})]);
if (typeof callback === "function") {
return orig.call(this, options, values, function(err, result, fields) {
finishSpan(span);
callback(err, result, fields);
});
}
if (typeof values === "function") {
return orig.call(this, options, function(err, result, fields) {
finishSpan(span);
values(err, result, fields);
});
}
const query = orig.call(this, options, values);
query.on("end", () => {
finishSpan(span);
});
return query;
};
});
}
};
Mysql.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/mongo.js
function isCursor(maybeCursor) {
return maybeCursor && typeof maybeCursor === "object" && maybeCursor.once && typeof maybeCursor.once === "function";
}
var OPERATIONS, OPERATION_SIGNATURES, Mongo;
var init_mongo = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/mongo.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_debug_build3();
init_node_utils();
OPERATIONS = [
"aggregate",
// aggregate(pipeline, options, callback)
"bulkWrite",
// bulkWrite(operations, options, callback)
"countDocuments",
// countDocuments(query, options, callback)
"createIndex",
// createIndex(fieldOrSpec, options, callback)
"createIndexes",
// createIndexes(indexSpecs, options, callback)
"deleteMany",
// deleteMany(filter, options, callback)
"deleteOne",
// deleteOne(filter, options, callback)
"distinct",
// distinct(key, query, options, callback)
"drop",
// drop(options, callback)
"dropIndex",
// dropIndex(indexName, options, callback)
"dropIndexes",
// dropIndexes(options, callback)
"estimatedDocumentCount",
// estimatedDocumentCount(options, callback)
"find",
// find(query, options, callback)
"findOne",
// findOne(query, options, callback)
"findOneAndDelete",
// findOneAndDelete(filter, options, callback)
"findOneAndReplace",
// findOneAndReplace(filter, replacement, options, callback)
"findOneAndUpdate",
// findOneAndUpdate(filter, update, options, callback)
"indexes",
// indexes(options, callback)
"indexExists",
// indexExists(indexes, options, callback)
"indexInformation",
// indexInformation(options, callback)
"initializeOrderedBulkOp",
// initializeOrderedBulkOp(options, callback)
"insertMany",
// insertMany(docs, options, callback)
"insertOne",
// insertOne(doc, options, callback)
"isCapped",
// isCapped(options, callback)
"mapReduce",
// mapReduce(map, reduce, options, callback)
"options",
// options(options, callback)
"parallelCollectionScan",
// parallelCollectionScan(options, callback)
"rename",
// rename(newName, options, callback)
"replaceOne",
// replaceOne(filter, doc, options, callback)
"stats",
// stats(options, callback)
"updateMany",
// updateMany(filter, update, options, callback)
"updateOne"
// updateOne(filter, update, options, callback)
];
OPERATION_SIGNATURES = {
// aggregate intentionally not included because `pipeline` arguments are too complex to serialize well
// see https://github.com/getsentry/sentry-javascript/pull/3102
bulkWrite: ["operations"],
countDocuments: ["query"],
createIndex: ["fieldOrSpec"],
createIndexes: ["indexSpecs"],
deleteMany: ["filter"],
deleteOne: ["filter"],
distinct: ["key", "query"],
dropIndex: ["indexName"],
find: ["query"],
findOne: ["query"],
findOneAndDelete: ["filter"],
findOneAndReplace: ["filter", "replacement"],
findOneAndUpdate: ["filter", "update"],
indexExists: ["indexes"],
insertMany: ["docs"],
insertOne: ["doc"],
mapReduce: ["map", "reduce"],
rename: ["newName"],
replaceOne: ["filter", "doc"],
updateMany: ["filter", "update"],
updateOne: ["filter", "update"]
};
__name(isCursor, "isCursor");
Mongo = class _Mongo {
static {
__name(this, "Mongo");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Mongo";
}
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
constructor(options = {}) {
this.name = _Mongo.id;
this._operations = Array.isArray(options.operations) ? options.operations : OPERATIONS;
this._describeOperations = "describeOperations" in options ? options.describeOperations : true;
this._useMongoose = !!options.useMongoose;
}
/** @inheritdoc */
loadDependency() {
const moduleName = this._useMongoose ? "mongoose" : "mongodb";
return this._module = this._module || loadModule(moduleName);
}
/**
* @inheritDoc
*/
setupOnce(_4, getCurrentHub3) {
if (shouldDisableAutoInstrumentation(getCurrentHub3)) {
DEBUG_BUILD3 && logger3.log("Mongo Integration is skipped because of instrumenter configuration.");
return;
}
const pkg = this.loadDependency();
if (!pkg) {
const moduleName = this._useMongoose ? "mongoose" : "mongodb";
DEBUG_BUILD3 && logger3.error(`Mongo Integration was unable to require \`${moduleName}\` package.`);
return;
}
this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub3);
}
/**
* Patches original collection methods
*/
_instrumentOperations(collection, operations, getCurrentHub3) {
operations.forEach((operation) => this._patchOperation(collection, operation, getCurrentHub3));
}
/**
* Patches original collection to utilize our tracing functionality
*/
_patchOperation(collection, operation, getCurrentHub3) {
if (!(operation in collection.prototype)) return;
const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);
fill(collection.prototype, operation, function(orig) {
return function(...args) {
const lastArg = args[args.length - 1];
const scope = getCurrentHub3().getScope();
const parentSpan = scope.getSpan();
if (typeof lastArg !== "function" || operation === "mapReduce" && args.length === 2) {
const span2 = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32(getSpanContext(this, operation, args))]);
const maybePromiseOrCursor = orig.call(this, ...args);
if (isThenable(maybePromiseOrCursor)) {
return maybePromiseOrCursor.then((res) => {
_optionalChain([span2, "optionalAccess", (_4) => _4.finish, "call", (_5) => _5()]);
return res;
});
} else if (isCursor(maybePromiseOrCursor)) {
const cursor = maybePromiseOrCursor;
try {
cursor.once("close", () => {
_optionalChain([span2, "optionalAccess", (_6) => _6.finish, "call", (_7) => _7()]);
});
} catch (e7) {
_optionalChain([span2, "optionalAccess", (_8) => _8.finish, "call", (_9) => _9()]);
}
return cursor;
} else {
_optionalChain([span2, "optionalAccess", (_10) => _10.finish, "call", (_11) => _11()]);
return maybePromiseOrCursor;
}
}
const span = _optionalChain([parentSpan, "optionalAccess", (_12) => _12.startChild, "call", (_13) => _13(getSpanContext(this, operation, args.slice(0, -1)))]);
return orig.call(this, ...args.slice(0, -1), function(err, result) {
_optionalChain([span, "optionalAccess", (_14) => _14.finish, "call", (_15) => _15()]);
lastArg(err, result);
});
};
});
}
/**
* Form a SpanContext based on the user input to a given operation.
*/
_getSpanContextFromOperationArguments(collection, operation, args) {
const data = {
"db.system": "mongodb",
"db.name": collection.dbName,
"db.operation": operation,
"db.mongodb.collection": collection.collectionName
};
const spanContext = {
op: "db",
// TODO v8: Use `${collection.collectionName}.${operation}`
origin: "auto.db.mongo",
description: operation,
data
};
const signature = OPERATION_SIGNATURES[operation];
const shouldDescribe = Array.isArray(this._describeOperations) ? this._describeOperations.includes(operation) : this._describeOperations;
if (!signature || !shouldDescribe) {
return spanContext;
}
try {
if (operation === "mapReduce") {
const [map2, reduce] = args;
data[signature[0]] = typeof map2 === "string" ? map2 : map2.name || "<anonymous>";
data[signature[1]] = typeof reduce === "string" ? reduce : reduce.name || "<anonymous>";
} else {
for (let i5 = 0; i5 < signature.length; i5++) {
data[`db.mongodb.${signature[i5]}`] = JSON.stringify(args[i5]);
}
}
} catch (_oO) {
}
return spanContext;
}
};
Mongo.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/prisma.js
function isValidPrismaClient(possibleClient) {
return !!possibleClient && !!possibleClient["$use"];
}
var Prisma;
var init_prisma = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/prisma.js"() {
init_import_meta_url();
init_esm7();
init_esm6();
init_debug_build3();
init_node_utils();
__name(isValidPrismaClient, "isValidPrismaClient");
Prisma = class _Prisma {
static {
__name(this, "Prisma");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Prisma";
}
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
constructor(options = {}) {
this.name = _Prisma.id;
if (isValidPrismaClient(options.client) && !options.client._sentryInstrumented) {
addNonEnumerableProperty(options.client, "_sentryInstrumented", true);
const clientData = {};
try {
const engineConfig = options.client._engineConfig;
if (engineConfig) {
const { activeProvider, clientVersion } = engineConfig;
if (activeProvider) {
clientData["db.system"] = activeProvider;
}
if (clientVersion) {
clientData["db.prisma.version"] = clientVersion;
}
}
} catch (e7) {
}
options.client.$use((params, next) => {
if (shouldDisableAutoInstrumentation(getCurrentHub)) {
return next(params);
}
const action = params.action;
const model = params.model;
return trace(
{
name: model ? `${model} ${action}` : action,
op: "db.prisma",
origin: "auto.db.prisma",
data: { ...clientData, "db.operation": action }
},
() => next(params)
);
});
} else {
DEBUG_BUILD3 && logger3.warn("Unsupported Prisma client provided to PrismaIntegration. Provided client:", options.client);
}
}
/**
* @inheritDoc
*/
setupOnce() {
}
};
Prisma.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/graphql.js
var GraphQL;
var init_graphql = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/graphql.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_debug_build3();
init_node_utils();
GraphQL = class _GraphQL {
static {
__name(this, "GraphQL");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "GraphQL";
}
/**
* @inheritDoc
*/
constructor() {
this.name = _GraphQL.id;
}
/** @inheritdoc */
loadDependency() {
return this._module = this._module || loadModule("graphql/execution/execute.js");
}
/**
* @inheritDoc
*/
setupOnce(_4, getCurrentHub3) {
if (shouldDisableAutoInstrumentation(getCurrentHub3)) {
DEBUG_BUILD3 && logger3.log("GraphQL Integration is skipped because of instrumenter configuration.");
return;
}
const pkg = this.loadDependency();
if (!pkg) {
DEBUG_BUILD3 && logger3.error("GraphQL Integration was unable to require graphql/execution package.");
return;
}
fill(pkg, "execute", function(orig) {
return function(...args) {
const scope = getCurrentHub3().getScope();
const parentSpan = scope.getSpan();
const span = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32({
description: "execute",
op: "graphql.execute",
origin: "auto.graphql.graphql"
})]);
_optionalChain([scope, "optionalAccess", (_42) => _42.setSpan, "call", (_5) => _5(span)]);
const rv = orig.call(this, ...args);
if (isThenable(rv)) {
return rv.then((res) => {
_optionalChain([span, "optionalAccess", (_6) => _6.finish, "call", (_7) => _7()]);
_optionalChain([scope, "optionalAccess", (_8) => _8.setSpan, "call", (_9) => _9(parentSpan)]);
return res;
});
}
_optionalChain([span, "optionalAccess", (_10) => _10.finish, "call", (_11) => _11()]);
_optionalChain([scope, "optionalAccess", (_12) => _12.setSpan, "call", (_13) => _13(parentSpan)]);
return rv;
};
});
}
};
GraphQL.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/apollo.js
function instrumentResolvers(resolvers, getCurrentHub3) {
return resolvers.map((model) => {
Object.keys(model).forEach((resolverGroupName) => {
Object.keys(model[resolverGroupName]).forEach((resolverName) => {
if (typeof model[resolverGroupName][resolverName] !== "function") {
return;
}
wrapResolver(model, resolverGroupName, resolverName, getCurrentHub3);
});
});
return model;
});
}
function wrapResolver(model, resolverGroupName, resolverName, getCurrentHub3) {
fill(model[resolverGroupName], resolverName, function(orig) {
return function(...args) {
const scope = getCurrentHub3().getScope();
const parentSpan = scope.getSpan();
const span = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32({
description: `${resolverGroupName}.${resolverName}`,
op: "graphql.resolve",
origin: "auto.graphql.apollo"
})]);
const rv = orig.call(this, ...args);
if (isThenable(rv)) {
return rv.then((res) => {
_optionalChain([span, "optionalAccess", (_4) => _4.finish, "call", (_5) => _5()]);
return res;
});
}
_optionalChain([span, "optionalAccess", (_6) => _6.finish, "call", (_7) => _7()]);
return rv;
};
});
}
var Apollo;
var init_apollo = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/node/integrations/apollo.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_debug_build3();
init_node_utils();
Apollo = class _Apollo {
static {
__name(this, "Apollo");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Apollo";
}
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
constructor(options = {
useNestjs: false
}) {
this.name = _Apollo.id;
this._useNest = !!options.useNestjs;
}
/** @inheritdoc */
loadDependency() {
if (this._useNest) {
this._module = this._module || loadModule("@nestjs/graphql");
} else {
this._module = this._module || loadModule("apollo-server-core");
}
return this._module;
}
/**
* @inheritDoc
*/
setupOnce(_4, getCurrentHub3) {
if (shouldDisableAutoInstrumentation(getCurrentHub3)) {
DEBUG_BUILD3 && logger3.log("Apollo Integration is skipped because of instrumenter configuration.");
return;
}
if (this._useNest) {
const pkg = this.loadDependency();
if (!pkg) {
DEBUG_BUILD3 && logger3.error("Apollo-NestJS Integration was unable to require @nestjs/graphql package.");
return;
}
fill(
pkg.GraphQLFactory.prototype,
"mergeWithSchema",
function(orig) {
return function(...args) {
fill(this.resolversExplorerService, "explore", function(orig2) {
return function() {
const resolvers = arrayify(orig2.call(this));
const instrumentedResolvers = instrumentResolvers(resolvers, getCurrentHub3);
return instrumentedResolvers;
};
});
return orig.call(this, ...args);
};
}
);
} else {
const pkg = this.loadDependency();
if (!pkg) {
DEBUG_BUILD3 && logger3.error("Apollo Integration was unable to require apollo-server-core package.");
return;
}
fill(pkg.ApolloServerBase.prototype, "constructSchema", function(orig) {
return function() {
if (!this.config.resolvers) {
if (DEBUG_BUILD3) {
if (this.config.schema) {
logger3.warn(
"Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead."
);
logger3.warn();
} else if (this.config.modules) {
logger3.warn(
"Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property."
);
}
logger3.error("Skipping tracing as no resolvers found on the `ApolloServer` instance.");
}
return orig.call(this);
}
const resolvers = arrayify(this.config.resolvers);
this.config.resolvers = instrumentResolvers(resolvers, getCurrentHub3);
return orig.call(this);
};
});
}
}
};
Apollo.__initStatic();
__name(instrumentResolvers, "instrumentResolvers");
__name(wrapResolver, "wrapResolver");
}
});
// ../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/index.js
var init_esm8 = __esm({
"../../node_modules/.pnpm/@sentry-internal+tracing@7.87.0/node_modules/@sentry-internal/tracing/esm/index.js"() {
init_import_meta_url();
init_express();
init_postgres();
init_mysql();
init_mongo();
init_prisma();
init_graphql();
init_apollo();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/client.js
var os8, import_util15, NodeClient;
var init_client9 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/client.js"() {
init_import_meta_url();
os8 = __toESM(require("os"));
import_util15 = require("util");
init_esm7();
NodeClient = class extends ServerRuntimeClient {
static {
__name(this, "NodeClient");
}
/**
* Creates a new Node SDK instance.
* @param options Configuration options for this SDK.
*/
constructor(options) {
options._metadata = options._metadata || {};
options._metadata.sdk = options._metadata.sdk || {
name: "sentry.javascript.node",
packages: [
{
name: "npm:@sentry/node",
version: SDK_VERSION
}
],
version: SDK_VERSION
};
options.transportOptions = {
textEncoder: new import_util15.TextEncoder(),
...options.transportOptions
};
const clientOptions = {
...options,
platform: "node",
runtime: { name: "node", version: global.process.version },
serverName: options.serverName || global.process.env.SENTRY_NAME || os8.hostname()
};
super(clientOptions);
}
};
}
});
// ../../node_modules/.pnpm/agent-base@6.0.2_supports-color@9.2.2/node_modules/agent-base/dist/src/promisify.js
var require_promisify = __commonJS({
"../../node_modules/.pnpm/agent-base@6.0.2_supports-color@9.2.2/node_modules/agent-base/dist/src/promisify.js"(exports2) {
"use strict";
init_import_meta_url();
Object.defineProperty(exports2, "__esModule", { value: true });
function promisify3(fn2) {
return function(req, opts) {
return new Promise((resolve25, reject) => {
fn2.call(this, req, opts, (err, rtn) => {
if (err) {
reject(err);
} else {
resolve25(rtn);
}
});
});
};
}
__name(promisify3, "promisify");
exports2.default = promisify3;
}
});
// ../../node_modules/.pnpm/agent-base@6.0.2_supports-color@9.2.2/node_modules/agent-base/dist/src/index.js
var require_src4 = __commonJS({
"../../node_modules/.pnpm/agent-base@6.0.2_supports-color@9.2.2/node_modules/agent-base/dist/src/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
var events_1 = require("events");
var debug_1 = __importDefault(require_src3());
var promisify_1 = __importDefault(require_promisify());
var debug = debug_1.default("agent-base");
function isAgent(v7) {
return Boolean(v7) && typeof v7.addRequest === "function";
}
__name(isAgent, "isAgent");
function isSecureEndpoint() {
const { stack } = new Error();
if (typeof stack !== "string")
return false;
return stack.split("\n").some((l6) => l6.indexOf("(https.js:") !== -1 || l6.indexOf("node:https:") !== -1);
}
__name(isSecureEndpoint, "isSecureEndpoint");
function createAgent(callback, opts) {
return new createAgent.Agent(callback, opts);
}
__name(createAgent, "createAgent");
(function(createAgent2) {
class Agent extends events_1.EventEmitter {
static {
__name(this, "Agent");
}
constructor(callback, _opts) {
super();
let opts = _opts;
if (typeof callback === "function") {
this.callback = callback;
} else if (callback) {
opts = callback;
}
this.timeout = null;
if (opts && typeof opts.timeout === "number") {
this.timeout = opts.timeout;
}
this.maxFreeSockets = 1;
this.maxSockets = 1;
this.maxTotalSockets = Infinity;
this.sockets = {};
this.freeSockets = {};
this.requests = {};
this.options = {};
}
get defaultPort() {
if (typeof this.explicitDefaultPort === "number") {
return this.explicitDefaultPort;
}
return isSecureEndpoint() ? 443 : 80;
}
set defaultPort(v7) {
this.explicitDefaultPort = v7;
}
get protocol() {
if (typeof this.explicitProtocol === "string") {
return this.explicitProtocol;
}
return isSecureEndpoint() ? "https:" : "http:";
}
set protocol(v7) {
this.explicitProtocol = v7;
}
callback(req, opts, fn2) {
throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');
}
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req, _opts) {
const opts = Object.assign({}, _opts);
if (typeof opts.secureEndpoint !== "boolean") {
opts.secureEndpoint = isSecureEndpoint();
}
if (opts.host == null) {
opts.host = "localhost";
}
if (opts.port == null) {
opts.port = opts.secureEndpoint ? 443 : 80;
}
if (opts.protocol == null) {
opts.protocol = opts.secureEndpoint ? "https:" : "http:";
}
if (opts.host && opts.path) {
delete opts.path;
}
delete opts.agent;
delete opts.hostname;
delete opts._defaultAgent;
delete opts.defaultPort;
delete opts.createConnection;
req._last = true;
req.shouldKeepAlive = false;
let timedOut = false;
let timeoutId = null;
const timeoutMs = opts.timeout || this.timeout;
const onerror = /* @__PURE__ */ __name((err) => {
if (req._hadError)
return;
req.emit("error", err);
req._hadError = true;
}, "onerror");
const ontimeout = /* @__PURE__ */ __name(() => {
timeoutId = null;
timedOut = true;
const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);
err.code = "ETIMEOUT";
onerror(err);
}, "ontimeout");
const callbackError = /* @__PURE__ */ __name((err) => {
if (timedOut)
return;
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
onerror(err);
}, "callbackError");
const onsocket = /* @__PURE__ */ __name((socket) => {
if (timedOut)
return;
if (timeoutId != null) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (isAgent(socket)) {
debug("Callback returned another Agent instance %o", socket.constructor.name);
socket.addRequest(req, opts);
return;
}
if (socket) {
socket.once("free", () => {
this.freeSocket(socket, opts);
});
req.onSocket(socket);
return;
}
const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);
onerror(err);
}, "onsocket");
if (typeof this.callback !== "function") {
onerror(new Error("`callback` is not defined"));
return;
}
if (!this.promisifiedCallback) {
if (this.callback.length >= 3) {
debug("Converting legacy callback function to promise");
this.promisifiedCallback = promisify_1.default(this.callback);
} else {
this.promisifiedCallback = this.callback;
}
}
if (typeof timeoutMs === "number" && timeoutMs > 0) {
timeoutId = setTimeout(ontimeout, timeoutMs);
}
if ("port" in opts && typeof opts.port !== "number") {
opts.port = Number(opts.port);
}
try {
debug("Resolving socket for %o request: %o", opts.protocol, `${req.method} ${req.path}`);
Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);
} catch (err) {
Promise.reject(err).catch(callbackError);
}
}
freeSocket(socket, opts) {
debug("Freeing socket %o %o", socket.constructor.name, opts);
socket.destroy();
}
destroy() {
debug("Destroying agent %o", this.constructor.name);
}
}
createAgent2.Agent = Agent;
createAgent2.prototype = createAgent2.Agent.prototype;
})(createAgent || (createAgent = {}));
module3.exports = createAgent;
}
});
// ../../node_modules/.pnpm/https-proxy-agent@5.0.1_supports-color@9.2.2/node_modules/https-proxy-agent/dist/parse-proxy-response.js
var require_parse_proxy_response2 = __commonJS({
"../../node_modules/.pnpm/https-proxy-agent@5.0.1_supports-color@9.2.2/node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
"use strict";
init_import_meta_url();
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
var debug_1 = __importDefault(require_src3());
var debug = debug_1.default("https-proxy-agent:parse-proxy-response");
function parseProxyResponse(socket) {
return new Promise((resolve25, reject) => {
let buffersLength = 0;
const buffers = [];
function read2() {
const b6 = socket.read();
if (b6)
ondata(b6);
else
socket.once("readable", read2);
}
__name(read2, "read");
function cleanup() {
socket.removeListener("end", onend);
socket.removeListener("error", onerror);
socket.removeListener("close", onclose);
socket.removeListener("readable", read2);
}
__name(cleanup, "cleanup");
function onclose(err) {
debug("onclose had error %o", err);
}
__name(onclose, "onclose");
function onend() {
debug("onend");
}
__name(onend, "onend");
function onerror(err) {
cleanup();
debug("onerror %o", err);
reject(err);
}
__name(onerror, "onerror");
function ondata(b6) {
buffers.push(b6);
buffersLength += b6.length;
const buffered = Buffer.concat(buffers, buffersLength);
const endOfHeaders = buffered.indexOf("\r\n\r\n");
if (endOfHeaders === -1) {
debug("have not received end of HTTP headers yet...");
read2();
return;
}
const firstLine = buffered.toString("ascii", 0, buffered.indexOf("\r\n"));
const statusCode = +firstLine.split(" ")[1];
debug("got proxy server response: %o", firstLine);
resolve25({
statusCode,
buffered
});
}
__name(ondata, "ondata");
socket.on("error", onerror);
socket.on("close", onclose);
socket.on("end", onend);
read2();
});
}
__name(parseProxyResponse, "parseProxyResponse");
exports2.default = parseProxyResponse;
}
});
// ../../node_modules/.pnpm/https-proxy-agent@5.0.1_supports-color@9.2.2/node_modules/https-proxy-agent/dist/agent.js
var require_agent2 = __commonJS({
"../../node_modules/.pnpm/https-proxy-agent@5.0.1_supports-color@9.2.2/node_modules/https-proxy-agent/dist/agent.js"(exports2) {
"use strict";
init_import_meta_url();
var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P3, generator) {
function adopt(value) {
return value instanceof P3 ? value : new P3(function(resolve25) {
resolve25(value);
});
}
__name(adopt, "adopt");
return new (P3 || (P3 = Promise))(function(resolve25, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e7) {
reject(e7);
}
}
__name(fulfilled, "fulfilled");
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e7) {
reject(e7);
}
}
__name(rejected, "rejected");
function step(result) {
result.done ? resolve25(result.value) : adopt(result.value).then(fulfilled, rejected);
}
__name(step, "step");
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
var net_1 = __importDefault(require("net"));
var tls_1 = __importDefault(require("tls"));
var url_1 = __importDefault(require("url"));
var assert_1 = __importDefault(require("assert"));
var debug_1 = __importDefault(require_src3());
var agent_base_1 = require_src4();
var parse_proxy_response_1 = __importDefault(require_parse_proxy_response2());
var debug = debug_1.default("https-proxy-agent:agent");
var HttpsProxyAgent3 = class extends agent_base_1.Agent {
static {
__name(this, "HttpsProxyAgent");
}
constructor(_opts) {
let opts;
if (typeof _opts === "string") {
opts = url_1.default.parse(_opts);
} else {
opts = _opts;
}
if (!opts) {
throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");
}
debug("creating new HttpsProxyAgent instance: %o", opts);
super(opts);
const proxy2 = Object.assign({}, opts);
this.secureProxy = opts.secureProxy || isHTTPS(proxy2.protocol);
proxy2.host = proxy2.hostname || proxy2.host;
if (typeof proxy2.port === "string") {
proxy2.port = parseInt(proxy2.port, 10);
}
if (!proxy2.port && proxy2.host) {
proxy2.port = this.secureProxy ? 443 : 80;
}
if (this.secureProxy && !("ALPNProtocols" in proxy2)) {
proxy2.ALPNProtocols = ["http 1.1"];
}
if (proxy2.host && proxy2.path) {
delete proxy2.path;
delete proxy2.pathname;
}
this.proxy = proxy2;
}
/**
* Called when the node-core HTTP client library is creating a
* new HTTP request.
*
* @api protected
*/
callback(req, opts) {
return __awaiter2(this, void 0, void 0, function* () {
const { proxy: proxy2, secureProxy } = this;
let socket;
if (secureProxy) {
debug("Creating `tls.Socket`: %o", proxy2);
socket = tls_1.default.connect(proxy2);
} else {
debug("Creating `net.Socket`: %o", proxy2);
socket = net_1.default.connect(proxy2);
}
const headers = Object.assign({}, proxy2.headers);
const hostname2 = `${opts.host}:${opts.port}`;
let payload = `CONNECT ${hostname2} HTTP/1.1\r
`;
if (proxy2.auth) {
headers["Proxy-Authorization"] = `Basic ${Buffer.from(proxy2.auth).toString("base64")}`;
}
let { host, port, secureEndpoint } = opts;
if (!isDefaultPort(port, secureEndpoint)) {
host += `:${port}`;
}
headers.Host = host;
headers.Connection = "close";
for (const name2 of Object.keys(headers)) {
payload += `${name2}: ${headers[name2]}\r
`;
}
const proxyResponsePromise = parse_proxy_response_1.default(socket);
socket.write(`${payload}\r
`);
const { statusCode, buffered } = yield proxyResponsePromise;
if (statusCode === 200) {
req.once("socket", resume);
if (opts.secureEndpoint) {
debug("Upgrading socket connection to TLS");
const servername = opts.servername || opts.host;
return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, "host", "hostname", "path", "port")), {
socket,
servername
}));
}
return socket;
}
socket.destroy();
const fakeSocket = new net_1.default.Socket({ writable: false });
fakeSocket.readable = true;
req.once("socket", (s5) => {
debug("replaying proxy buffer for failed request");
assert_1.default(s5.listenerCount("data") > 0);
s5.push(buffered);
s5.push(null);
});
return fakeSocket;
});
}
};
exports2.default = HttpsProxyAgent3;
function resume(socket) {
socket.resume();
}
__name(resume, "resume");
function isDefaultPort(port, secure) {
return Boolean(!secure && port === 80 || secure && port === 443);
}
__name(isDefaultPort, "isDefaultPort");
function isHTTPS(protocol) {
return typeof protocol === "string" ? /^https:?$/i.test(protocol) : false;
}
__name(isHTTPS, "isHTTPS");
function omit(obj, ...keys) {
const ret = {};
let key;
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key];
}
}
return ret;
}
__name(omit, "omit");
}
});
// ../../node_modules/.pnpm/https-proxy-agent@5.0.1_supports-color@9.2.2/node_modules/https-proxy-agent/dist/index.js
var require_dist5 = __commonJS({
"../../node_modules/.pnpm/https-proxy-agent@5.0.1_supports-color@9.2.2/node_modules/https-proxy-agent/dist/index.js"(exports2, module3) {
"use strict";
init_import_meta_url();
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
var agent_1 = __importDefault(require_agent2());
function createHttpsProxyAgent(opts) {
return new agent_1.default(opts);
}
__name(createHttpsProxyAgent, "createHttpsProxyAgent");
(function(createHttpsProxyAgent2) {
createHttpsProxyAgent2.HttpsProxyAgent = agent_1.default;
createHttpsProxyAgent2.prototype = agent_1.default.prototype;
})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));
module3.exports = createHttpsProxyAgent;
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/transports/http.js
function streamFromBody(body) {
return new import_stream15.Readable({
read() {
this.push(body);
this.push(null);
}
});
}
function makeNodeTransport(options) {
let urlSegments;
try {
urlSegments = new import_url6.URL(options.url);
} catch (e7) {
consoleSandbox(() => {
console.warn(
"[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used."
);
});
return createTransport(options, () => Promise.resolve({}));
}
const isHttps = urlSegments.protocol === "https:";
const proxy2 = applyNoProxyOption(
urlSegments,
options.proxy || (isHttps ? process.env.https_proxy : void 0) || process.env.http_proxy
);
const nativeHttpModule = isHttps ? https : http3;
const keepAlive = options.keepAlive === void 0 ? false : options.keepAlive;
const agent = proxy2 ? new import_https_proxy_agent2.HttpsProxyAgent(proxy2) : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2e3 });
const requestExecutor = createRequestExecutor(options, _nullishCoalesce(options.httpModule, () => nativeHttpModule), agent);
return createTransport(options, requestExecutor);
}
function applyNoProxyOption(transportUrlSegments, proxy2) {
const { no_proxy } = process.env;
const urlIsExemptFromProxy = no_proxy && no_proxy.split(",").some(
(exemption) => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption)
);
if (urlIsExemptFromProxy) {
return void 0;
} else {
return proxy2;
}
}
function createRequestExecutor(options, httpModule, agent) {
const { hostname: hostname2, pathname, port, protocol, search } = new import_url6.URL(options.url);
return /* @__PURE__ */ __name(function makeRequest(request4) {
return new Promise((resolve25, reject) => {
let body = streamFromBody(request4.body);
const headers = { ...options.headers };
if (request4.body.length > GZIP_THRESHOLD) {
headers["content-encoding"] = "gzip";
body = body.pipe((0, import_zlib.createGzip)());
}
const req = httpModule.request(
{
method: "POST",
agent,
headers,
hostname: hostname2,
path: `${pathname}${search}`,
port,
protocol,
ca: options.caCerts
},
(res) => {
res.on("data", () => {
});
res.on("end", () => {
});
res.setEncoding("utf8");
const retryAfterHeader = _nullishCoalesce(res.headers["retry-after"], () => null);
const rateLimitsHeader = _nullishCoalesce(res.headers["x-sentry-rate-limits"], () => null);
resolve25({
statusCode: res.statusCode,
headers: {
"retry-after": retryAfterHeader,
"x-sentry-rate-limits": Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader
}
});
}
);
req.on("error", reject);
body.pipe(req);
});
}, "makeRequest");
}
var http3, https, import_stream15, import_url6, import_zlib, import_https_proxy_agent2, GZIP_THRESHOLD;
var init_http2 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/transports/http.js"() {
init_import_meta_url();
init_esm6();
http3 = __toESM(require("http"));
https = __toESM(require("https"));
import_stream15 = require("stream");
import_url6 = require("url");
import_zlib = require("zlib");
init_esm7();
init_esm6();
import_https_proxy_agent2 = __toESM(require_dist5());
GZIP_THRESHOLD = 1024 * 32;
__name(streamFromBody, "streamFromBody");
__name(makeNodeTransport, "makeNodeTransport");
__name(applyNoProxyOption, "applyNoProxyOption");
__name(createRequestExecutor, "createRequestExecutor");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/module.js
function normalizeWindowsPath(path72) {
return path72.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
}
function getModuleFromFilename(filename, normalizeWindowsPathSeparator = isWindowsPlatform) {
if (!filename) {
return;
}
const normalizedFilename = normalizeWindowsPathSeparator ? normalizeWindowsPath(filename) : filename;
let { root, dir, base: basename7, ext } = import_path23.posix.parse(normalizedFilename);
const base = require && require.main && require.main.filename && dir || global.process.cwd();
const normalizedBase = `${base}/`;
let file = basename7;
if (ext === ".js" || ext === ".mjs" || ext === ".cjs") {
file = file.slice(0, ext.length * -1);
}
if (!root && !dir) {
dir = ".";
}
let n6 = dir.lastIndexOf("/node_modules/");
if (n6 > -1) {
return `${dir.slice(n6 + 14).replace(/\//g, ".")}:${file}`;
}
n6 = `${dir}/`.lastIndexOf(normalizedBase, 0);
if (n6 === 0) {
let moduleName = dir.slice(normalizedBase.length).replace(/\//g, ".");
if (moduleName) {
moduleName += ":";
}
moduleName += file;
return moduleName;
}
return file;
}
var import_path23, isWindowsPlatform;
var init_module4 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/module.js"() {
init_import_meta_url();
import_path23 = require("path");
isWindowsPlatform = import_path23.sep === "\\";
__name(normalizeWindowsPath, "normalizeWindowsPath");
__name(getModuleFromFilename, "getModuleFromFilename");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/anr/index.js
function isAnrChildProcess() {
return !!process.send && !!process.env.SENTRY_ANR_CHILD_PROCESS;
}
var init_anr = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/anr/index.js"() {
init_import_meta_url();
__name(isAnrChildProcess, "isAnrChildProcess");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/nodeVersion.js
var NODE_VERSION;
var init_nodeVersion = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/nodeVersion.js"() {
init_import_meta_url();
init_esm6();
NODE_VERSION = parseSemver(process.versions.node);
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/async/domain.js
function getActiveDomain() {
return domain.active;
}
function getCurrentHub2() {
const activeDomain = getActiveDomain();
if (!activeDomain) {
return void 0;
}
ensureHubOnCarrier(activeDomain);
return getHubFromCarrier(activeDomain);
}
function createNewHub(parent) {
const carrier = {};
ensureHubOnCarrier(carrier, parent);
return getHubFromCarrier(carrier);
}
function runWithAsyncContext2(callback, options) {
const activeDomain = getActiveDomain();
if (activeDomain && _optionalChain([options, "optionalAccess", (_4) => _4.reuseExisting])) {
return callback();
}
const local = domain.create();
const parentHub = activeDomain ? getHubFromCarrier(activeDomain) : void 0;
const newHub = createNewHub(parentHub);
setHubOnCarrier(local, newHub);
return local.bind(() => {
return callback();
})();
}
function setDomainAsyncContextStrategy() {
setAsyncContextStrategy({ getCurrentHub: getCurrentHub2, runWithAsyncContext: runWithAsyncContext2 });
}
var domain;
var init_domain2 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/async/domain.js"() {
init_import_meta_url();
init_esm6();
domain = __toESM(require("domain"));
init_esm7();
__name(getActiveDomain, "getActiveDomain");
__name(getCurrentHub2, "getCurrentHub");
__name(createNewHub, "createNewHub");
__name(runWithAsyncContext2, "runWithAsyncContext");
__name(setDomainAsyncContextStrategy, "setDomainAsyncContextStrategy");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/async/hooks.js
function setHooksAsyncContextStrategy() {
if (!asyncStorage) {
asyncStorage = new async_hooks.AsyncLocalStorage();
}
function getCurrentHub3() {
return asyncStorage.getStore();
}
__name(getCurrentHub3, "getCurrentHub");
function createNewHub2(parent) {
const carrier = {};
ensureHubOnCarrier(carrier, parent);
return getHubFromCarrier(carrier);
}
__name(createNewHub2, "createNewHub");
function runWithAsyncContext3(callback, options) {
const existingHub = getCurrentHub3();
if (existingHub && _optionalChain([options, "optionalAccess", (_4) => _4.reuseExisting])) {
return callback();
}
const newHub = createNewHub2(existingHub);
return asyncStorage.run(newHub, () => {
return callback();
});
}
__name(runWithAsyncContext3, "runWithAsyncContext");
setAsyncContextStrategy({ getCurrentHub: getCurrentHub3, runWithAsyncContext: runWithAsyncContext3 });
}
var async_hooks, asyncStorage;
var init_hooks = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/async/hooks.js"() {
init_import_meta_url();
init_esm6();
init_esm7();
async_hooks = __toESM(require("async_hooks"));
__name(setHooksAsyncContextStrategy, "setHooksAsyncContextStrategy");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/async/index.js
function setNodeAsyncContextStrategy() {
if (NODE_VERSION.major && NODE_VERSION.major >= 14) {
setHooksAsyncContextStrategy();
} else {
setDomainAsyncContextStrategy();
}
}
var init_async = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/async/index.js"() {
init_import_meta_url();
init_nodeVersion();
init_domain2();
init_hooks();
__name(setNodeAsyncContextStrategy, "setNodeAsyncContextStrategy");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/console.js
var util2, Console;
var init_console2 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/console.js"() {
init_import_meta_url();
util2 = __toESM(require("util"));
init_esm7();
init_esm6();
Console = class _Console {
static {
__name(this, "Console");
}
constructor() {
_Console.prototype.__init.call(this);
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Console";
}
/**
* @inheritDoc
*/
__init() {
this.name = _Console.id;
}
/**
* @inheritDoc
*/
setupOnce() {
addConsoleInstrumentationHandler(({ args, level }) => {
const hub = getCurrentHub();
if (!hub.getIntegration(_Console)) {
return;
}
hub.addBreadcrumb(
{
category: "console",
level: severityLevelFromString(level),
message: util2.format.apply(void 0, args)
},
{
input: [...args],
level
}
);
});
}
};
Console.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/debug-build.js
var DEBUG_BUILD4;
var init_debug_build4 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/debug-build.js"() {
init_import_meta_url();
DEBUG_BUILD4 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/utils/http.js
function extractRawUrl(requestOptions) {
const { protocol, hostname: hostname2, port } = parseRequestOptions(requestOptions);
const path72 = requestOptions.path ? requestOptions.path : "/";
return `${protocol}//${hostname2}${port}${path72}`;
}
function extractUrl(requestOptions) {
const { protocol, hostname: hostname2, port } = parseRequestOptions(requestOptions);
const path72 = requestOptions.pathname || "/";
const authority = requestOptions.auth ? redactAuthority(requestOptions.auth) : "";
return `${protocol}//${authority}${hostname2}${port}${path72}`;
}
function redactAuthority(auth) {
const [user, password] = auth.split(":");
return `${user ? "[Filtered]" : ""}:${password ? "[Filtered]" : ""}@`;
}
function cleanSpanDescription(description, requestOptions, request4) {
if (!description) {
return description;
}
let [method, requestUrl] = description.split(" ");
if (requestOptions.host && !requestOptions.protocol) {
requestOptions.protocol = _optionalChain([request4, "optionalAccess", (_4) => _4.agent, "optionalAccess", (_22) => _22.protocol]);
requestUrl = extractUrl(requestOptions);
}
if (_optionalChain([requestUrl, "optionalAccess", (_32) => _32.startsWith, "call", (_4) => _4("///")])) {
requestUrl = requestUrl.slice(2);
}
return `${method} ${requestUrl}`;
}
function urlToOptions(url4) {
const options = {
protocol: url4.protocol,
hostname: typeof url4.hostname === "string" && url4.hostname.startsWith("[") ? url4.hostname.slice(1, -1) : url4.hostname,
hash: url4.hash,
search: url4.search,
pathname: url4.pathname,
path: `${url4.pathname || ""}${url4.search || ""}`,
href: url4.href
};
if (url4.port !== "") {
options.port = Number(url4.port);
}
if (url4.username || url4.password) {
options.auth = `${url4.username}:${url4.password}`;
}
return options;
}
function normalizeRequestArgs(httpModule, requestArgs) {
let callback, requestOptions;
if (typeof requestArgs[requestArgs.length - 1] === "function") {
callback = requestArgs.pop();
}
if (typeof requestArgs[0] === "string") {
requestOptions = urlToOptions(new import_url7.URL(requestArgs[0]));
} else if (requestArgs[0] instanceof import_url7.URL) {
requestOptions = urlToOptions(requestArgs[0]);
} else {
requestOptions = requestArgs[0];
try {
const parsed = new import_url7.URL(
requestOptions.path || "",
`${requestOptions.protocol || "http:"}//${requestOptions.hostname}`
);
requestOptions = {
pathname: parsed.pathname,
search: parsed.search,
hash: parsed.hash,
...requestOptions
};
} catch (e7) {
}
}
if (requestArgs.length === 2) {
requestOptions = { ...requestOptions, ...requestArgs[1] };
}
if (requestOptions.protocol === void 0) {
if (NODE_VERSION.major && NODE_VERSION.major > 8) {
requestOptions.protocol = _optionalChain([_optionalChain([httpModule, "optionalAccess", (_5) => _5.globalAgent]), "optionalAccess", (_6) => _6.protocol]) || _optionalChain([requestOptions.agent, "optionalAccess", (_7) => _7.protocol]) || _optionalChain([requestOptions._defaultAgent, "optionalAccess", (_8) => _8.protocol]);
} else {
requestOptions.protocol = _optionalChain([requestOptions.agent, "optionalAccess", (_9) => _9.protocol]) || _optionalChain([requestOptions._defaultAgent, "optionalAccess", (_10) => _10.protocol]) || _optionalChain([_optionalChain([httpModule, "optionalAccess", (_11) => _11.globalAgent]), "optionalAccess", (_12) => _12.protocol]);
}
}
if (callback) {
return [requestOptions, callback];
} else {
return [requestOptions];
}
}
function parseRequestOptions(requestOptions) {
const protocol = requestOptions.protocol || "";
const hostname2 = requestOptions.hostname || requestOptions.host || "";
const port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 || /^(.*):(\d+)$/.test(hostname2) ? "" : `:${requestOptions.port}`;
return { protocol, hostname: hostname2, port };
}
var import_url7;
var init_http3 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/utils/http.js"() {
init_import_meta_url();
init_esm6();
import_url7 = require("url");
init_nodeVersion();
__name(extractRawUrl, "extractRawUrl");
__name(extractUrl, "extractUrl");
__name(redactAuthority, "redactAuthority");
__name(cleanSpanDescription, "cleanSpanDescription");
__name(urlToOptions, "urlToOptions");
__name(normalizeRequestArgs, "normalizeRequestArgs");
__name(parseRequestOptions, "parseRequestOptions");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/http.js
function _createWrappedRequestMethodFactory(httpModule, breadcrumbsEnabled, shouldCreateSpanForRequest, tracePropagationTargets) {
const createSpanUrlMap = new LRUMap(100);
const headersUrlMap = new LRUMap(100);
const shouldCreateSpan = /* @__PURE__ */ __name((url4) => {
if (shouldCreateSpanForRequest === void 0) {
return true;
}
const cachedDecision = createSpanUrlMap.get(url4);
if (cachedDecision !== void 0) {
return cachedDecision;
}
const decision = shouldCreateSpanForRequest(url4);
createSpanUrlMap.set(url4, decision);
return decision;
}, "shouldCreateSpan");
const shouldAttachTraceData = /* @__PURE__ */ __name((url4) => {
if (tracePropagationTargets === void 0) {
return true;
}
const cachedDecision = headersUrlMap.get(url4);
if (cachedDecision !== void 0) {
return cachedDecision;
}
const decision = stringMatchesSomePattern(url4, tracePropagationTargets);
headersUrlMap.set(url4, decision);
return decision;
}, "shouldAttachTraceData");
function addRequestBreadcrumb(event, requestSpanData, req, res) {
if (!getCurrentHub().getIntegration(Http)) {
return;
}
getCurrentHub().addBreadcrumb(
{
category: "http",
data: {
status_code: res && res.statusCode,
...requestSpanData
},
type: "http"
},
{
event,
request: req,
response: res
}
);
}
__name(addRequestBreadcrumb, "addRequestBreadcrumb");
return /* @__PURE__ */ __name(function wrappedRequestMethodFactory(originalRequestMethod) {
return /* @__PURE__ */ __name(function wrappedMethod(...args) {
const requestArgs = normalizeRequestArgs(httpModule, args);
const requestOptions = requestArgs[0];
const rawRequestUrl = extractRawUrl(requestOptions);
const requestUrl = extractUrl(requestOptions);
if (isSentryRequestUrl(requestUrl, getCurrentHub())) {
return originalRequestMethod.apply(httpModule, requestArgs);
}
const hub = getCurrentHub();
const scope = hub.getScope();
const parentSpan = scope.getSpan();
const data = getRequestSpanData(requestUrl, requestOptions);
const requestSpan = shouldCreateSpan(rawRequestUrl) ? _optionalChain([parentSpan, "optionalAccess", (_12) => _12.startChild, "call", (_13) => _13({
op: "http.client",
origin: "auto.http.node.http",
description: `${data["http.method"]} ${data.url}`,
data
})]) : void 0;
if (shouldAttachTraceData(rawRequestUrl)) {
if (requestSpan) {
const sentryTraceHeader = requestSpan.toTraceparent();
const dynamicSamplingContext = _optionalChain([requestSpan, "optionalAccess", (_14) => _14.transaction, "optionalAccess", (_15) => _15.getDynamicSamplingContext, "call", (_16) => _16()]);
addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, dynamicSamplingContext);
} else {
const client = hub.getClient();
const { traceId, sampled, dsc } = scope.getPropagationContext();
const sentryTraceHeader = generateSentryTraceHeader(traceId, void 0, sampled);
const dynamicSamplingContext = dsc || (client ? getDynamicSamplingContextFromClient(traceId, client, scope) : void 0);
addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, dynamicSamplingContext);
}
} else {
DEBUG_BUILD4 && logger3.log(
`[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`
);
}
return originalRequestMethod.apply(httpModule, requestArgs).once("response", function(res) {
const req = this;
if (breadcrumbsEnabled) {
addRequestBreadcrumb("response", data, req, res);
}
if (requestSpan) {
if (res.statusCode) {
requestSpan.setHttpStatus(res.statusCode);
}
requestSpan.description = cleanSpanDescription(requestSpan.description, requestOptions, req);
requestSpan.finish();
}
}).once("error", function() {
const req = this;
if (breadcrumbsEnabled) {
addRequestBreadcrumb("error", data, req);
}
if (requestSpan) {
requestSpan.setHttpStatus(500);
requestSpan.description = cleanSpanDescription(requestSpan.description, requestOptions, req);
requestSpan.finish();
}
});
}, "wrappedMethod");
}, "wrappedRequestMethodFactory");
}
function addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, dynamicSamplingContext) {
const headers = requestOptions.headers || {};
if (headers["sentry-trace"]) {
return;
}
DEBUG_BUILD4 && logger3.log(`[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `);
const sentryBaggage = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
const sentryBaggageHeader = sentryBaggage && sentryBaggage.length > 0 ? normalizeBaggageHeader(requestOptions, sentryBaggage) : void 0;
requestOptions.headers = {
...requestOptions.headers,
"sentry-trace": sentryTraceHeader,
// Setting a header to `undefined` will crash in node so we only set the baggage header when it's defined
...sentryBaggageHeader && { baggage: sentryBaggageHeader }
};
}
function getRequestSpanData(requestUrl, requestOptions) {
const method = requestOptions.method || "GET";
const data = {
url: requestUrl,
"http.method": method
};
if (requestOptions.hash) {
data["http.fragment"] = requestOptions.hash.substring(1);
}
if (requestOptions.search) {
data["http.query"] = requestOptions.search.substring(1);
}
return data;
}
function normalizeBaggageHeader(requestOptions, sentryBaggageHeader) {
if (!requestOptions.headers || !requestOptions.headers.baggage) {
return sentryBaggageHeader;
} else if (!sentryBaggageHeader) {
return requestOptions.headers.baggage;
} else if (Array.isArray(requestOptions.headers.baggage)) {
return [...requestOptions.headers.baggage, sentryBaggageHeader];
}
return [requestOptions.headers.baggage, sentryBaggageHeader];
}
var Http;
var init_http4 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/http.js"() {
init_import_meta_url();
init_esm6();
init_esm7();
init_esm6();
init_debug_build4();
init_nodeVersion();
init_http3();
Http = class _Http {
static {
__name(this, "Http");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Http";
}
/**
* @inheritDoc
*/
__init() {
this.name = _Http.id;
}
/**
* @inheritDoc
*/
constructor(options = {}) {
_Http.prototype.__init.call(this);
this._breadcrumbs = typeof options.breadcrumbs === "undefined" ? true : options.breadcrumbs;
this._tracing = !options.tracing ? void 0 : options.tracing === true ? {} : options.tracing;
}
/**
* @inheritDoc
*/
setupOnce(_addGlobalEventProcessor, setupOnceGetCurrentHub) {
if (!this._breadcrumbs && !this._tracing) {
return;
}
const clientOptions = _optionalChain([setupOnceGetCurrentHub, "call", (_4) => _4(), "access", (_22) => _22.getClient, "call", (_32) => _32(), "optionalAccess", (_4) => _4.getOptions, "call", (_5) => _5()]);
if (clientOptions && clientOptions.instrumenter !== "sentry") {
DEBUG_BUILD4 && logger3.log("HTTP Integration is skipped because of instrumenter configuration.");
return;
}
const shouldCreateSpanForRequest = (
// eslint-disable-next-line deprecation/deprecation
_optionalChain([this, "access", (_6) => _6._tracing, "optionalAccess", (_7) => _7.shouldCreateSpanForRequest]) || _optionalChain([clientOptions, "optionalAccess", (_8) => _8.shouldCreateSpanForRequest])
);
const tracePropagationTargets = _optionalChain([clientOptions, "optionalAccess", (_9) => _9.tracePropagationTargets]) || _optionalChain([this, "access", (_10) => _10._tracing, "optionalAccess", (_11) => _11.tracePropagationTargets]);
const httpModule = require("http");
const wrappedHttpHandlerMaker = _createWrappedRequestMethodFactory(
httpModule,
this._breadcrumbs,
shouldCreateSpanForRequest,
tracePropagationTargets
);
fill(httpModule, "get", wrappedHttpHandlerMaker);
fill(httpModule, "request", wrappedHttpHandlerMaker);
if (NODE_VERSION.major && NODE_VERSION.major > 8) {
const httpsModule = require("https");
const wrappedHttpsHandlerMaker = _createWrappedRequestMethodFactory(
httpsModule,
this._breadcrumbs,
shouldCreateSpanForRequest,
tracePropagationTargets
);
fill(httpsModule, "get", wrappedHttpsHandlerMaker);
fill(httpsModule, "request", wrappedHttpsHandlerMaker);
}
}
};
Http.__initStatic();
__name(_createWrappedRequestMethodFactory, "_createWrappedRequestMethodFactory");
__name(addHeadersToRequestOptions, "addHeadersToRequestOptions");
__name(getRequestSpanData, "getRequestSpanData");
__name(normalizeBaggageHeader, "normalizeBaggageHeader");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/utils/errorhandling.js
function logAndExitProcess(error2) {
consoleSandbox(() => {
console.error(error2);
});
const client = getClient();
if (client === void 0) {
DEBUG_BUILD4 && logger3.warn("No NodeClient was defined, we are exiting the process now.");
global.process.exit(1);
}
const options = client.getOptions();
const timeout2 = options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout || DEFAULT_SHUTDOWN_TIMEOUT;
client.close(timeout2).then(
(result) => {
if (!result) {
DEBUG_BUILD4 && logger3.warn("We reached the timeout for emptying the request buffer, still exiting now!");
}
global.process.exit(1);
},
(error3) => {
DEBUG_BUILD4 && logger3.error(error3);
}
);
}
var DEFAULT_SHUTDOWN_TIMEOUT;
var init_errorhandling = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/utils/errorhandling.js"() {
init_import_meta_url();
init_esm7();
init_esm6();
init_debug_build4();
DEFAULT_SHUTDOWN_TIMEOUT = 2e3;
__name(logAndExitProcess, "logAndExitProcess");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/onuncaughtexception.js
var OnUncaughtException;
var init_onuncaughtexception = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/onuncaughtexception.js"() {
init_import_meta_url();
init_esm7();
init_esm6();
init_debug_build4();
init_errorhandling();
OnUncaughtException = class _OnUncaughtException {
static {
__name(this, "OnUncaughtException");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "OnUncaughtException";
}
/**
* @inheritDoc
*/
__init() {
this.name = _OnUncaughtException.id;
}
/**
* @inheritDoc
*/
__init2() {
this.handler = this._makeErrorHandler();
}
// CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts`
/**
* @inheritDoc
*/
constructor(options = {}) {
_OnUncaughtException.prototype.__init.call(this);
_OnUncaughtException.prototype.__init2.call(this);
this._options = {
exitEvenIfOtherHandlersAreRegistered: true,
...options
};
}
/**
* @inheritDoc
*/
setupOnce() {
global.process.on("uncaughtException", this.handler);
}
/**
* @hidden
*/
_makeErrorHandler() {
const timeout2 = 2e3;
let caughtFirstError = false;
let caughtSecondError = false;
let calledFatalError = false;
let firstError;
return (error2) => {
let onFatalError = logAndExitProcess;
const client = getClient();
if (this._options.onFatalError) {
onFatalError = this._options.onFatalError;
} else if (client && client.getOptions().onFatalError) {
onFatalError = client.getOptions().onFatalError;
}
const userProvidedListenersCount = global.process.listeners("uncaughtException").reduce((acc, listener) => {
if (
// There are 3 listeners we ignore:
listener.name === "domainUncaughtExceptionClear" || // as soon as we're using domains this listener is attached by node itself
listener.tag && listener.tag === "sentry_tracingErrorCallback" || // the handler we register for tracing
listener === this.handler
) {
return acc;
} else {
return acc + 1;
}
}, 0);
const processWouldExit = userProvidedListenersCount === 0;
const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit;
if (!caughtFirstError) {
const hub = getCurrentHub();
firstError = error2;
caughtFirstError = true;
if (hub.getIntegration(_OnUncaughtException)) {
hub.withScope((scope) => {
scope.setLevel("fatal");
hub.captureException(error2, {
originalException: error2,
data: { mechanism: { handled: false, type: "onuncaughtexception" } }
});
if (!calledFatalError && shouldApplyFatalHandlingLogic) {
calledFatalError = true;
onFatalError(error2);
}
});
} else {
if (!calledFatalError && shouldApplyFatalHandlingLogic) {
calledFatalError = true;
onFatalError(error2);
}
}
} else {
if (shouldApplyFatalHandlingLogic) {
if (calledFatalError) {
DEBUG_BUILD4 && logger3.warn(
"uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown"
);
logAndExitProcess(error2);
} else if (!caughtSecondError) {
caughtSecondError = true;
setTimeout(() => {
if (!calledFatalError) {
calledFatalError = true;
onFatalError(firstError, error2);
}
}, timeout2);
}
}
}
};
}
};
OnUncaughtException.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/onunhandledrejection.js
var OnUnhandledRejection;
var init_onunhandledrejection = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/onunhandledrejection.js"() {
init_import_meta_url();
init_esm7();
init_esm6();
init_errorhandling();
OnUnhandledRejection = class _OnUnhandledRejection {
static {
__name(this, "OnUnhandledRejection");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "OnUnhandledRejection";
}
/**
* @inheritDoc
*/
__init() {
this.name = _OnUnhandledRejection.id;
}
/**
* @inheritDoc
*/
constructor(_options = { mode: "warn" }) {
this._options = _options;
_OnUnhandledRejection.prototype.__init.call(this);
}
/**
* @inheritDoc
*/
setupOnce() {
global.process.on("unhandledRejection", this.sendUnhandledPromise.bind(this));
}
/**
* Send an exception with reason
* @param reason string
* @param promise promise
*/
sendUnhandledPromise(reason, promise) {
const hub = getCurrentHub();
if (hub.getIntegration(_OnUnhandledRejection)) {
hub.withScope((scope) => {
scope.setExtra("unhandledPromiseRejection", true);
hub.captureException(reason, {
originalException: promise,
data: { mechanism: { handled: false, type: "onunhandledrejection" } }
});
});
}
this._handleRejection(reason);
}
/**
* Handler for `mode` option
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_handleRejection(reason) {
const rejectionWarning = "This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:";
if (this._options.mode === "warn") {
consoleSandbox(() => {
console.warn(rejectionWarning);
console.error(reason && reason.stack ? reason.stack : reason);
});
} else if (this._options.mode === "strict") {
consoleSandbox(() => {
console.warn(rejectionWarning);
});
logAndExitProcess(reason);
}
}
};
OnUnhandledRejection.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/modules.js
function getPaths() {
try {
return require.cache ? Object.keys(require.cache) : [];
} catch (e7) {
return [];
}
}
function collectModules() {
const mainPaths = require.main && require.main.paths || [];
const paths = getPaths();
const infos = {};
const seen = {};
paths.forEach((path72) => {
let dir = path72;
const updir = /* @__PURE__ */ __name(() => {
const orig = dir;
dir = (0, import_path24.dirname)(orig);
if (!dir || orig === dir || seen[orig]) {
return void 0;
}
if (mainPaths.indexOf(dir) < 0) {
return updir();
}
const pkgfile = (0, import_path24.join)(orig, "package.json");
seen[orig] = true;
if (!(0, import_fs23.existsSync)(pkgfile)) {
return updir();
}
try {
const info = JSON.parse((0, import_fs23.readFileSync)(pkgfile, "utf8"));
infos[info.name] = info.version;
} catch (_oO) {
}
}, "updir");
updir();
});
return infos;
}
var import_fs23, import_path24, moduleCache, Modules;
var init_modules = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/modules.js"() {
init_import_meta_url();
import_fs23 = require("fs");
import_path24 = require("path");
__name(getPaths, "getPaths");
__name(collectModules, "collectModules");
Modules = class _Modules {
static {
__name(this, "Modules");
}
constructor() {
_Modules.prototype.__init.call(this);
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Modules";
}
/**
* @inheritDoc
*/
__init() {
this.name = _Modules.id;
}
/**
* @inheritDoc
*/
setupOnce(addGlobalEventProcessor2, getCurrentHub3) {
addGlobalEventProcessor2((event) => {
if (!getCurrentHub3().getIntegration(_Modules)) {
return event;
}
return {
...event,
modules: {
...event.modules,
...this._getModules()
}
};
});
}
/** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */
_getModules() {
if (!moduleCache) {
moduleCache = collectModules();
}
return moduleCache;
}
};
Modules.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/contextlines.js
function readTextFileAsync(path72) {
return new Promise((resolve25, reject) => {
(0, import_fs24.readFile)(path72, "utf8", (err, data) => {
if (err) reject(err);
else resolve25(data);
});
});
}
async function _readSourceFile(filename) {
const cachedFile = FILE_CONTENT_CACHE.get(filename);
if (cachedFile === null) {
return null;
}
if (cachedFile !== void 0) {
return cachedFile;
}
let content = null;
try {
const rawFileContents = await readTextFileAsync(filename);
content = rawFileContents.split("\n");
} catch (_4) {
}
FILE_CONTENT_CACHE.set(filename, content);
return content;
}
var import_fs24, FILE_CONTENT_CACHE, DEFAULT_LINES_OF_CONTEXT, ContextLines;
var init_contextlines = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/contextlines.js"() {
init_import_meta_url();
init_esm6();
import_fs24 = require("fs");
init_esm6();
FILE_CONTENT_CACHE = new LRUMap(100);
DEFAULT_LINES_OF_CONTEXT = 7;
__name(readTextFileAsync, "readTextFileAsync");
ContextLines = class _ContextLines {
static {
__name(this, "ContextLines");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "ContextLines";
}
/**
* @inheritDoc
*/
__init() {
this.name = _ContextLines.id;
}
constructor(_options = {}) {
this._options = _options;
_ContextLines.prototype.__init.call(this);
}
/** Get's the number of context lines to add */
get _contextLines() {
return this._options.frameContextLines !== void 0 ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
}
/**
* @inheritDoc
*/
setupOnce(addGlobalEventProcessor2, getCurrentHub3) {
addGlobalEventProcessor2((event) => {
const self2 = getCurrentHub3().getIntegration(_ContextLines);
if (!self2) {
return event;
}
return this.addSourceContext(event);
});
}
/** Processes an event and adds context lines */
async addSourceContext(event) {
const enqueuedReadSourceFileTasks = {};
const readSourceFileTasks = [];
if (this._contextLines > 0 && _optionalChain([event, "access", (_22) => _22.exception, "optionalAccess", (_32) => _32.values])) {
for (const exception of event.exception.values) {
if (!_optionalChain([exception, "access", (_4) => _4.stacktrace, "optionalAccess", (_5) => _5.frames])) {
continue;
}
for (let i5 = exception.stacktrace.frames.length - 1; i5 >= 0; i5--) {
const frame = exception.stacktrace.frames[i5];
if (frame.filename && !enqueuedReadSourceFileTasks[frame.filename] && !FILE_CONTENT_CACHE.get(frame.filename)) {
readSourceFileTasks.push(_readSourceFile(frame.filename));
enqueuedReadSourceFileTasks[frame.filename] = 1;
}
}
}
}
if (readSourceFileTasks.length > 0) {
await Promise.all(readSourceFileTasks);
}
if (this._contextLines > 0 && _optionalChain([event, "access", (_6) => _6.exception, "optionalAccess", (_7) => _7.values])) {
for (const exception of event.exception.values) {
if (exception.stacktrace && exception.stacktrace.frames) {
await this.addSourceContextToFrames(exception.stacktrace.frames);
}
}
}
return event;
}
/** Adds context lines to frames */
addSourceContextToFrames(frames) {
for (const frame of frames) {
if (frame.filename && frame.context_line === void 0) {
const sourceFileLines = FILE_CONTENT_CACHE.get(frame.filename);
if (sourceFileLines) {
try {
addContextToFrame(sourceFileLines, frame, this._contextLines);
} catch (e7) {
}
}
}
}
}
};
ContextLines.__initStatic();
__name(_readSourceFile, "_readSourceFile");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/context.js
async function getOsContext() {
const platformId = os9.platform();
switch (platformId) {
case "darwin":
return getDarwinInfo();
case "linux":
return getLinuxInfo();
default:
return {
name: PLATFORM_NAMES[platformId] || platformId,
version: os9.release()
};
}
}
function getCultureContext() {
try {
if (typeof process.versions.icu !== "string") {
return;
}
const january = /* @__PURE__ */ new Date(9e8);
const spanish = new Intl.DateTimeFormat("es", { month: "long" });
if (spanish.format(january) === "enero") {
const options = Intl.DateTimeFormat().resolvedOptions();
return {
locale: options.locale,
timezone: options.timeZone
};
}
} catch (err) {
}
return;
}
function getAppContext() {
const app_memory = process.memoryUsage().rss;
const app_start_time = new Date(Date.now() - process.uptime() * 1e3).toISOString();
return { app_start_time, app_memory };
}
function getDeviceContext(deviceOpt) {
const device = {};
let uptime3;
try {
uptime3 = os9.uptime && os9.uptime();
} catch (e7) {
}
if (typeof uptime3 === "number") {
device.boot_time = new Date(Date.now() - uptime3 * 1e3).toISOString();
}
device.arch = os9.arch();
if (deviceOpt === true || deviceOpt.memory) {
device.memory_size = os9.totalmem();
device.free_memory = os9.freemem();
}
if (deviceOpt === true || deviceOpt.cpu) {
const cpuInfo = os9.cpus();
if (cpuInfo && cpuInfo.length) {
const firstCpu = cpuInfo[0];
device.processor_count = cpuInfo.length;
device.cpu_description = firstCpu.model;
device.processor_frequency = firstCpu.speed;
}
}
return device;
}
function matchFirst(regex2, text) {
const match2 = regex2.exec(text);
return match2 ? match2[1] : void 0;
}
async function getDarwinInfo() {
const darwinInfo = {
kernel_version: os9.release(),
name: "Mac OS X",
version: `10.${Number(os9.release().split(".")[0]) - 4}`
};
try {
const output = await new Promise((resolve25, reject) => {
(0, import_child_process6.execFile)("/usr/bin/sw_vers", (error2, stdout2) => {
if (error2) {
reject(error2);
return;
}
resolve25(stdout2);
});
});
darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output);
darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output);
darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output);
} catch (e7) {
}
return darwinInfo;
}
function getLinuxDistroId(name2) {
return name2.split(" ")[0].toLowerCase();
}
async function getLinuxInfo() {
const linuxInfo = {
kernel_version: os9.release(),
name: "Linux"
};
try {
const etcFiles = await readDirAsync("/etc");
const distroFile = LINUX_DISTROS.find((file) => etcFiles.includes(file.name));
if (!distroFile) {
return linuxInfo;
}
const distroPath = (0, import_path25.join)("/etc", distroFile.name);
const contents = (await readFileAsync(distroPath, { encoding: "utf-8" })).toLowerCase();
const { distros } = distroFile;
linuxInfo.name = distros.find((d6) => contents.indexOf(getLinuxDistroId(d6)) >= 0) || distros[0];
const id = getLinuxDistroId(linuxInfo.name);
linuxInfo.version = LINUX_VERSIONS[id](contents);
} catch (e7) {
}
return linuxInfo;
}
function getCloudResourceContext() {
if (process.env.VERCEL) {
return {
"cloud.provider": "vercel",
"cloud.region": process.env.VERCEL_REGION
};
} else if (process.env.AWS_REGION) {
return {
"cloud.provider": "aws",
"cloud.region": process.env.AWS_REGION,
"cloud.platform": process.env.AWS_EXECUTION_ENV
};
} else if (process.env.GCP_PROJECT) {
return {
"cloud.provider": "gcp"
};
} else if (process.env.ALIYUN_REGION_ID) {
return {
"cloud.provider": "alibaba_cloud",
"cloud.region": process.env.ALIYUN_REGION_ID
};
} else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {
return {
"cloud.provider": "azure",
"cloud.region": process.env.REGION_NAME
};
} else if (process.env.IBM_CLOUD_REGION) {
return {
"cloud.provider": "ibm_cloud",
"cloud.region": process.env.IBM_CLOUD_REGION
};
} else if (process.env.TENCENTCLOUD_REGION) {
return {
"cloud.provider": "tencent_cloud",
"cloud.region": process.env.TENCENTCLOUD_REGION,
"cloud.account.id": process.env.TENCENTCLOUD_APPID,
"cloud.availability_zone": process.env.TENCENTCLOUD_ZONE
};
} else if (process.env.NETLIFY) {
return {
"cloud.provider": "netlify"
};
} else if (process.env.FLY_REGION) {
return {
"cloud.provider": "fly.io",
"cloud.region": process.env.FLY_REGION
};
} else if (process.env.DYNO) {
return {
"cloud.provider": "heroku"
};
} else {
return void 0;
}
}
var import_child_process6, import_fs25, os9, import_path25, import_util16, readFileAsync, readDirAsync, Context, PLATFORM_NAMES, LINUX_DISTROS, LINUX_VERSIONS;
var init_context = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/context.js"() {
init_import_meta_url();
init_esm6();
import_child_process6 = require("child_process");
import_fs25 = require("fs");
os9 = __toESM(require("os"));
import_path25 = require("path");
import_util16 = require("util");
readFileAsync = (0, import_util16.promisify)(import_fs25.readFile);
readDirAsync = (0, import_util16.promisify)(import_fs25.readdir);
Context = class _Context {
static {
__name(this, "Context");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Context";
}
/**
* @inheritDoc
*/
__init() {
this.name = _Context.id;
}
/**
* Caches context so it's only evaluated once
*/
constructor(_options = {
app: true,
os: true,
device: true,
culture: true,
cloudResource: true
}) {
this._options = _options;
_Context.prototype.__init.call(this);
}
/**
* @inheritDoc
*/
setupOnce(addGlobalEventProcessor2) {
addGlobalEventProcessor2((event) => this.addContext(event));
}
/** Processes an event and adds context */
async addContext(event) {
if (this._cachedContext === void 0) {
this._cachedContext = this._getContexts();
}
const updatedContext = this._updateContext(await this._cachedContext);
event.contexts = {
...event.contexts,
app: { ...updatedContext.app, ..._optionalChain([event, "access", (_4) => _4.contexts, "optionalAccess", (_22) => _22.app]) },
os: { ...updatedContext.os, ..._optionalChain([event, "access", (_32) => _32.contexts, "optionalAccess", (_4) => _4.os]) },
device: { ...updatedContext.device, ..._optionalChain([event, "access", (_5) => _5.contexts, "optionalAccess", (_6) => _6.device]) },
culture: { ...updatedContext.culture, ..._optionalChain([event, "access", (_7) => _7.contexts, "optionalAccess", (_8) => _8.culture]) },
cloud_resource: { ...updatedContext.cloud_resource, ..._optionalChain([event, "access", (_9) => _9.contexts, "optionalAccess", (_10) => _10.cloud_resource]) }
};
return event;
}
/**
* Updates the context with dynamic values that can change
*/
_updateContext(contexts) {
if (_optionalChain([contexts, "optionalAccess", (_11) => _11.app, "optionalAccess", (_12) => _12.app_memory])) {
contexts.app.app_memory = process.memoryUsage().rss;
}
if (_optionalChain([contexts, "optionalAccess", (_13) => _13.device, "optionalAccess", (_14) => _14.free_memory])) {
contexts.device.free_memory = os9.freemem();
}
return contexts;
}
/**
* Gets the contexts for the current environment
*/
async _getContexts() {
const contexts = {};
if (this._options.os) {
contexts.os = await getOsContext();
}
if (this._options.app) {
contexts.app = getAppContext();
}
if (this._options.device) {
contexts.device = getDeviceContext(this._options.device);
}
if (this._options.culture) {
const culture = getCultureContext();
if (culture) {
contexts.culture = culture;
}
}
if (this._options.cloudResource) {
contexts.cloud_resource = getCloudResourceContext();
}
return contexts;
}
};
Context.__initStatic();
__name(getOsContext, "getOsContext");
__name(getCultureContext, "getCultureContext");
__name(getAppContext, "getAppContext");
__name(getDeviceContext, "getDeviceContext");
PLATFORM_NAMES = {
aix: "IBM AIX",
freebsd: "FreeBSD",
openbsd: "OpenBSD",
sunos: "SunOS",
win32: "Windows"
};
LINUX_DISTROS = [
{ name: "fedora-release", distros: ["Fedora"] },
{ name: "redhat-release", distros: ["Red Hat Linux", "Centos"] },
{ name: "redhat_version", distros: ["Red Hat Linux"] },
{ name: "SuSE-release", distros: ["SUSE Linux"] },
{ name: "lsb-release", distros: ["Ubuntu Linux", "Arch Linux"] },
{ name: "debian_version", distros: ["Debian"] },
{ name: "debian_release", distros: ["Debian"] },
{ name: "arch-release", distros: ["Arch Linux"] },
{ name: "gentoo-release", distros: ["Gentoo Linux"] },
{ name: "novell-release", distros: ["SUSE Linux"] },
{ name: "alpine-release", distros: ["Alpine Linux"] }
];
LINUX_VERSIONS = {
alpine: /* @__PURE__ */ __name((content) => content, "alpine"),
arch: /* @__PURE__ */ __name((content) => matchFirst(/distrib_release=(.*)/, content), "arch"),
centos: /* @__PURE__ */ __name((content) => matchFirst(/release ([^ ]+)/, content), "centos"),
debian: /* @__PURE__ */ __name((content) => content, "debian"),
fedora: /* @__PURE__ */ __name((content) => matchFirst(/release (..)/, content), "fedora"),
mint: /* @__PURE__ */ __name((content) => matchFirst(/distrib_release=(.*)/, content), "mint"),
red: /* @__PURE__ */ __name((content) => matchFirst(/release ([^ ]+)/, content), "red"),
suse: /* @__PURE__ */ __name((content) => matchFirst(/VERSION = (.*)\n/, content), "suse"),
ubuntu: /* @__PURE__ */ __name((content) => matchFirst(/distrib_release=(.*)/, content), "ubuntu")
};
__name(matchFirst, "matchFirst");
__name(getDarwinInfo, "getDarwinInfo");
__name(getLinuxDistroId, "getLinuxDistroId");
__name(getLinuxInfo, "getLinuxInfo");
__name(getCloudResourceContext, "getCloudResourceContext");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/localvariables.js
function createRateLimiter(maxPerSecond, enable, disable) {
let count = 0;
let retrySeconds = 5;
let disabledTimeout = 0;
setInterval(() => {
if (disabledTimeout === 0) {
if (count > maxPerSecond) {
retrySeconds *= 2;
disable(retrySeconds);
if (retrySeconds > 86400) {
retrySeconds = 86400;
}
disabledTimeout = retrySeconds;
}
} else {
disabledTimeout -= 1;
if (disabledTimeout === 0) {
enable();
}
}
count = 0;
}, 1e3).unref();
return () => {
count += 1;
};
}
function createCallbackList(complete) {
let callbacks = [];
let completedCalled = false;
function checkedComplete(result) {
callbacks = [];
if (completedCalled) {
return;
}
completedCalled = true;
complete(result);
}
__name(checkedComplete, "checkedComplete");
callbacks.push(checkedComplete);
function add(fn2) {
callbacks.push(fn2);
}
__name(add, "add");
function next(result) {
const popped = callbacks.pop() || checkedComplete;
try {
popped(result);
} catch (_4) {
checkedComplete(result);
}
}
__name(next, "next");
return { add, next };
}
function tryNewAsyncSession() {
try {
return new AsyncSession();
} catch (e7) {
return void 0;
}
}
function isAnonymous(name2) {
return name2 !== void 0 && ["", "?", "<anonymous>"].includes(name2);
}
function functionNamesMatch(a5, b6) {
return a5 === b6 || isAnonymous(a5) && isAnonymous(b6);
}
function hashFrames(frames) {
if (frames === void 0) {
return;
}
return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, "");
}
function hashFromStack(stackParser, stack) {
if (stack === void 0) {
return void 0;
}
return hashFrames(stackParser(stack, 1));
}
var AsyncSession, LocalVariables;
var init_localvariables = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/localvariables.js"() {
init_import_meta_url();
init_esm6();
init_esm6();
init_nodeVersion();
__name(createRateLimiter, "createRateLimiter");
__name(createCallbackList, "createCallbackList");
AsyncSession = class {
static {
__name(this, "AsyncSession");
}
/** Throws if inspector API is not available */
constructor() {
const { Session } = require("inspector");
this._session = new Session();
}
/** @inheritdoc */
configureAndConnect(onPause, captureAll) {
this._session.connect();
this._session.on("Debugger.paused", (event) => {
onPause(event, () => {
this._session.post("Debugger.resume");
});
});
this._session.post("Debugger.enable");
this._session.post("Debugger.setPauseOnExceptions", { state: captureAll ? "all" : "uncaught" });
}
setPauseOnExceptions(captureAll) {
this._session.post("Debugger.setPauseOnExceptions", { state: captureAll ? "all" : "uncaught" });
}
/** @inheritdoc */
getLocalVariables(objectId, complete) {
this._getProperties(objectId, (props) => {
const { add, next } = createCallbackList(complete);
for (const prop of props) {
if (_optionalChain([prop, "optionalAccess", (_22) => _22.value, "optionalAccess", (_32) => _32.objectId]) && _optionalChain([prop, "optionalAccess", (_4) => _4.value, "access", (_5) => _5.className]) === "Array") {
const id = prop.value.objectId;
add((vars) => this._unrollArray(id, prop.name, vars, next));
} else if (_optionalChain([prop, "optionalAccess", (_6) => _6.value, "optionalAccess", (_7) => _7.objectId]) && _optionalChain([prop, "optionalAccess", (_8) => _8.value, "optionalAccess", (_9) => _9.className]) === "Object") {
const id = prop.value.objectId;
add((vars) => this._unrollObject(id, prop.name, vars, next));
} else if (_optionalChain([prop, "optionalAccess", (_10) => _10.value, "optionalAccess", (_11) => _11.value]) || _optionalChain([prop, "optionalAccess", (_12) => _12.value, "optionalAccess", (_13) => _13.description])) {
add((vars) => this._unrollOther(prop, vars, next));
}
}
next({});
});
}
/**
* Gets all the PropertyDescriptors of an object
*/
_getProperties(objectId, next) {
this._session.post(
"Runtime.getProperties",
{
objectId,
ownProperties: true
},
(err, params) => {
if (err) {
next([]);
} else {
next(params.result);
}
}
);
}
/**
* Unrolls an array property
*/
_unrollArray(objectId, name2, vars, next) {
this._getProperties(objectId, (props) => {
vars[name2] = props.filter((v7) => v7.name !== "length" && !isNaN(parseInt(v7.name, 10))).sort((a5, b6) => parseInt(a5.name, 10) - parseInt(b6.name, 10)).map((v7) => _optionalChain([v7, "optionalAccess", (_14) => _14.value, "optionalAccess", (_15) => _15.value]));
next(vars);
});
}
/**
* Unrolls an object property
*/
_unrollObject(objectId, name2, vars, next) {
this._getProperties(objectId, (props) => {
vars[name2] = props.map((v7) => [v7.name, _optionalChain([v7, "optionalAccess", (_16) => _16.value, "optionalAccess", (_17) => _17.value])]).reduce((obj, [key, val2]) => {
obj[key] = val2;
return obj;
}, {});
next(vars);
});
}
/**
* Unrolls other properties
*/
_unrollOther(prop, vars, next) {
if (_optionalChain([prop, "optionalAccess", (_18) => _18.value, "optionalAccess", (_19) => _19.value])) {
vars[prop.name] = prop.value.value;
} else if (_optionalChain([prop, "optionalAccess", (_20) => _20.value, "optionalAccess", (_21) => _21.description]) && _optionalChain([prop, "optionalAccess", (_22) => _22.value, "optionalAccess", (_23) => _23.type]) !== "function") {
vars[prop.name] = `<${prop.value.description}>`;
}
next(vars);
}
};
__name(tryNewAsyncSession, "tryNewAsyncSession");
__name(isAnonymous, "isAnonymous");
__name(functionNamesMatch, "functionNamesMatch");
__name(hashFrames, "hashFrames");
__name(hashFromStack, "hashFromStack");
LocalVariables = class _LocalVariables {
static {
__name(this, "LocalVariables");
}
static __initStatic() {
this.id = "LocalVariables";
}
__init() {
this.name = _LocalVariables.id;
}
__init2() {
this._cachedFrames = new LRUMap(20);
}
constructor(_options = {}, _session = tryNewAsyncSession()) {
this._options = _options;
this._session = _session;
_LocalVariables.prototype.__init.call(this);
_LocalVariables.prototype.__init2.call(this);
}
/**
* @inheritDoc
*/
setupOnce(addGlobalEventProcessor2, getCurrentHub3) {
this._setup(addGlobalEventProcessor2, _optionalChain([getCurrentHub3, "call", (_24) => _24(), "access", (_25) => _25.getClient, "call", (_26) => _26(), "optionalAccess", (_27) => _27.getOptions, "call", (_28) => _28()]));
}
/** Setup in a way that's easier to call from tests */
_setup(addGlobalEventProcessor2, clientOptions) {
if (this._session && _optionalChain([clientOptions, "optionalAccess", (_29) => _29.includeLocalVariables])) {
const unsupportedNodeVersion = (NODE_VERSION.major || 0) < 18;
if (unsupportedNodeVersion) {
logger3.log("The `LocalVariables` integration is only supported on Node >= v18.");
return;
}
const captureAll = this._options.captureAllExceptions !== false;
this._session.configureAndConnect(
(ev, complete) => this._handlePaused(clientOptions.stackParser, ev, complete),
captureAll
);
if (captureAll) {
const max = this._options.maxExceptionsPerSecond || 50;
this._rateLimiter = createRateLimiter(
max,
() => {
logger3.log("Local variables rate-limit lifted.");
_optionalChain([this, "access", (_30) => _30._session, "optionalAccess", (_31) => _31.setPauseOnExceptions, "call", (_32) => _32(true)]);
},
(seconds) => {
logger3.log(
`Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`
);
_optionalChain([this, "access", (_33) => _33._session, "optionalAccess", (_34) => _34.setPauseOnExceptions, "call", (_35) => _35(false)]);
}
);
}
addGlobalEventProcessor2(async (event) => this._addLocalVariables(event));
}
}
/**
* Handle the pause event
*/
_handlePaused(stackParser, { params: { reason, data, callFrames } }, complete) {
if (reason !== "exception" && reason !== "promiseRejection") {
complete();
return;
}
_optionalChain([this, "access", (_36) => _36._rateLimiter, "optionalCall", (_37) => _37()]);
const exceptionHash = hashFromStack(stackParser, _optionalChain([data, "optionalAccess", (_38) => _38.description]));
if (exceptionHash == void 0) {
complete();
return;
}
const { add, next } = createCallbackList((frames) => {
this._cachedFrames.set(exceptionHash, frames);
complete();
});
for (let i5 = 0; i5 < Math.min(callFrames.length, 5); i5++) {
const { scopeChain, functionName, this: obj } = callFrames[i5];
const localScope = scopeChain.find((scope) => scope.type === "local");
const fn2 = obj.className === "global" || !obj.className ? functionName : `${obj.className}.${functionName}`;
if (_optionalChain([localScope, "optionalAccess", (_39) => _39.object, "access", (_40) => _40.objectId]) === void 0) {
add((frames) => {
frames[i5] = { function: fn2 };
next(frames);
});
} else {
const id = localScope.object.objectId;
add(
(frames) => _optionalChain([this, "access", (_41) => _41._session, "optionalAccess", (_42) => _42.getLocalVariables, "call", (_43) => _43(id, (vars) => {
frames[i5] = { function: fn2, vars };
next(frames);
})])
);
}
}
next([]);
}
/**
* Adds local variables event stack frames.
*/
_addLocalVariables(event) {
for (const exception of _optionalChain([event, "optionalAccess", (_44) => _44.exception, "optionalAccess", (_45) => _45.values]) || []) {
this._addLocalVariablesToException(exception);
}
return event;
}
/**
* Adds local variables to the exception stack frames.
*/
_addLocalVariablesToException(exception) {
const hash = hashFrames(_optionalChain([exception, "optionalAccess", (_46) => _46.stacktrace, "optionalAccess", (_47) => _47.frames]));
if (hash === void 0) {
return;
}
const cachedFrames = this._cachedFrames.remove(hash);
if (cachedFrames === void 0) {
return;
}
const frameCount = _optionalChain([exception, "access", (_48) => _48.stacktrace, "optionalAccess", (_49) => _49.frames, "optionalAccess", (_50) => _50.length]) || 0;
for (let i5 = 0; i5 < frameCount; i5++) {
const frameIndex = frameCount - i5 - 1;
if (!_optionalChain([exception, "optionalAccess", (_51) => _51.stacktrace, "optionalAccess", (_52) => _52.frames, "optionalAccess", (_53) => _53[frameIndex]]) || !cachedFrames[i5]) {
break;
}
if (
// We need to have vars to add
cachedFrames[i5].vars === void 0 || // We're not interested in frames that are not in_app because the vars are not relevant
exception.stacktrace.frames[frameIndex].in_app === false || // The function names need to match
!functionNamesMatch(exception.stacktrace.frames[frameIndex].function, cachedFrames[i5].function)
) {
continue;
}
exception.stacktrace.frames[frameIndex].vars = cachedFrames[i5].vars;
}
}
};
LocalVariables.__initStatic();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/undici/index.js
function setHeadersOnRequest(request4, sentryTrace, sentryBaggageHeader) {
const headerLines = request4.headers.split("\r\n");
const hasSentryHeaders = headerLines.some((headerLine) => headerLine.startsWith("sentry-trace:"));
if (hasSentryHeaders) {
return;
}
request4.addHeader("sentry-trace", sentryTrace);
if (sentryBaggageHeader) {
request4.addHeader("baggage", sentryBaggageHeader);
}
}
function createRequestSpan(activeSpan, request4, stringUrl) {
const url4 = parseUrl2(stringUrl);
const method = request4.method || "GET";
const data = {
"http.method": method
};
if (url4.search) {
data["http.query"] = url4.search;
}
if (url4.hash) {
data["http.fragment"] = url4.hash;
}
return _optionalChain([activeSpan, "optionalAccess", (_7) => _7.startChild, "call", (_8) => _8({
op: "http.client",
origin: "auto.http.node.undici",
description: `${method} ${getSanitizedUrlString(url4)}`,
data
})]);
}
var ChannelName, Undici;
var init_undici = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/undici/index.js"() {
init_import_meta_url();
init_esm6();
init_esm7();
init_esm6();
init_nodeVersion();
(function(ChannelName2) {
const RequestCreate = "undici:request:create";
ChannelName2["RequestCreate"] = RequestCreate;
const RequestEnd = "undici:request:headers";
ChannelName2["RequestEnd"] = RequestEnd;
const RequestError = "undici:request:error";
ChannelName2["RequestError"] = RequestError;
})(ChannelName || (ChannelName = {}));
Undici = class _Undici {
static {
__name(this, "Undici");
}
/**
* @inheritDoc
*/
static __initStatic() {
this.id = "Undici";
}
/**
* @inheritDoc
*/
__init() {
this.name = _Undici.id;
}
__init2() {
this._createSpanUrlMap = new LRUMap(100);
}
__init3() {
this._headersUrlMap = new LRUMap(100);
}
constructor(_options = {}) {
_Undici.prototype.__init.call(this);
_Undici.prototype.__init2.call(this);
_Undici.prototype.__init3.call(this);
_Undici.prototype.__init4.call(this);
_Undici.prototype.__init5.call(this);
_Undici.prototype.__init6.call(this);
this._options = {
breadcrumbs: _options.breadcrumbs === void 0 ? true : _options.breadcrumbs,
shouldCreateSpanForRequest: _options.shouldCreateSpanForRequest
};
}
/**
* @inheritDoc
*/
setupOnce(_addGlobalEventProcessor) {
if (NODE_VERSION.major && NODE_VERSION.major < 16) {
return;
}
let ds;
try {
ds = dynamicRequire(module, "diagnostics_channel");
} catch (e7) {
}
if (!ds || !ds.subscribe) {
return;
}
ds.subscribe(ChannelName.RequestCreate, this._onRequestCreate);
ds.subscribe(ChannelName.RequestEnd, this._onRequestEnd);
ds.subscribe(ChannelName.RequestError, this._onRequestError);
}
/** Helper that wraps shouldCreateSpanForRequest option */
_shouldCreateSpan(url4) {
if (this._options.shouldCreateSpanForRequest === void 0) {
return true;
}
const cachedDecision = this._createSpanUrlMap.get(url4);
if (cachedDecision !== void 0) {
return cachedDecision;
}
const decision = this._options.shouldCreateSpanForRequest(url4);
this._createSpanUrlMap.set(url4, decision);
return decision;
}
__init4() {
this._onRequestCreate = (message) => {
const hub = getCurrentHub();
if (!hub.getIntegration(_Undici)) {
return;
}
const { request: request4 } = message;
const stringUrl = request4.origin ? request4.origin.toString() + request4.path : request4.path;
if (isSentryRequestUrl(stringUrl, hub) || request4.__sentry_span__ !== void 0) {
return;
}
const client = hub.getClient();
if (!client) {
return;
}
const clientOptions = client.getOptions();
const scope = hub.getScope();
const parentSpan = scope.getSpan();
const span = this._shouldCreateSpan(stringUrl) ? createRequestSpan(parentSpan, request4, stringUrl) : void 0;
if (span) {
request4.__sentry_span__ = span;
}
const shouldAttachTraceData = /* @__PURE__ */ __name((url4) => {
if (clientOptions.tracePropagationTargets === void 0) {
return true;
}
const cachedDecision = this._headersUrlMap.get(url4);
if (cachedDecision !== void 0) {
return cachedDecision;
}
const decision = stringMatchesSomePattern(url4, clientOptions.tracePropagationTargets);
this._headersUrlMap.set(url4, decision);
return decision;
}, "shouldAttachTraceData");
if (shouldAttachTraceData(stringUrl)) {
if (span) {
const dynamicSamplingContext = _optionalChain([span, "optionalAccess", (_4) => _4.transaction, "optionalAccess", (_5) => _5.getDynamicSamplingContext, "call", (_6) => _6()]);
const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
setHeadersOnRequest(request4, span.toTraceparent(), sentryBaggageHeader);
} else {
const { traceId, sampled, dsc } = scope.getPropagationContext();
const sentryTrace = generateSentryTraceHeader(traceId, void 0, sampled);
const dynamicSamplingContext = dsc || getDynamicSamplingContextFromClient(traceId, client, scope);
const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
setHeadersOnRequest(request4, sentryTrace, sentryBaggageHeader);
}
}
};
}
__init5() {
this._onRequestEnd = (message) => {
const hub = getCurrentHub();
if (!hub.getIntegration(_Undici)) {
return;
}
const { request: request4, response } = message;
const stringUrl = request4.origin ? request4.origin.toString() + request4.path : request4.path;
if (isSentryRequestUrl(stringUrl, hub)) {
return;
}
const span = request4.__sentry_span__;
if (span) {
span.setHttpStatus(response.statusCode);
span.finish();
}
if (this._options.breadcrumbs) {
hub.addBreadcrumb(
{
category: "http",
data: {
method: request4.method,
status_code: response.statusCode,
url: stringUrl
},
type: "http"
},
{
event: "response",
request: request4,
response
}
);
}
};
}
__init6() {
this._onRequestError = (message) => {
const hub = getCurrentHub();
if (!hub.getIntegration(_Undici)) {
return;
}
const { request: request4 } = message;
const stringUrl = request4.origin ? request4.origin.toString() + request4.path : request4.path;
if (isSentryRequestUrl(stringUrl, hub)) {
return;
}
const span = request4.__sentry_span__;
if (span) {
span.setStatus("internal_error");
span.finish();
}
if (this._options.breadcrumbs) {
hub.addBreadcrumb(
{
category: "http",
data: {
method: request4.method,
url: stringUrl
},
level: "error",
type: "http"
},
{
event: "error",
request: request4
}
);
}
};
}
};
Undici.__initStatic();
__name(setHeadersOnRequest, "setHeadersOnRequest");
__name(createRequestSpan, "createRequestSpan");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/spotlight.js
function connectToSpotlight(client, options) {
const spotlightUrl = parseSidecarUrl(options.sidecarUrl);
if (!spotlightUrl) {
return;
}
let failedRequests = 0;
if (typeof client.on !== "function") {
logger3.warn("[Spotlight] Cannot connect to spotlight due to missing method on SDK client (`client.on`)");
return;
}
client.on("beforeEnvelope", (envelope) => {
if (failedRequests > 3) {
logger3.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests");
return;
}
const serializedEnvelope = serializeEnvelope(envelope);
const req = http4.request(
{
method: "POST",
path: spotlightUrl.pathname,
hostname: spotlightUrl.hostname,
port: spotlightUrl.port,
headers: {
"Content-Type": "application/x-sentry-envelope"
}
},
(res) => {
res.on("data", () => {
});
res.on("end", () => {
});
res.setEncoding("utf8");
}
);
req.on("error", () => {
failedRequests++;
logger3.warn("[Spotlight] Failed to send envelope to Spotlight Sidecar");
});
req.write(serializedEnvelope);
req.end();
});
}
function parseSidecarUrl(url4) {
try {
return new import_url8.URL(`${url4}`);
} catch (e7) {
logger3.warn(`[Spotlight] Invalid sidecar URL: ${url4}`);
return void 0;
}
}
var http4, import_url8, Spotlight;
var init_spotlight = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/spotlight.js"() {
init_import_meta_url();
init_esm6();
http4 = __toESM(require("http"));
import_url8 = require("url");
init_esm6();
Spotlight = class _Spotlight {
static {
__name(this, "Spotlight");
}
static __initStatic() {
this.id = "Spotlight";
}
__init() {
this.name = _Spotlight.id;
}
constructor(options) {
_Spotlight.prototype.__init.call(this);
this._options = {
sidecarUrl: _optionalChain([options, "optionalAccess", (_4) => _4.sidecarUrl]) || "http://localhost:8969/stream"
};
}
/**
* JSDoc
*/
setupOnce() {
}
/**
* Sets up forwarding envelopes to the Spotlight Sidecar
*/
setup(client) {
if (typeof process === "object" && process.env && true) {
logger3.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?");
}
connectToSpotlight(client, this._options);
}
};
Spotlight.__initStatic();
__name(connectToSpotlight, "connectToSpotlight");
__name(parseSidecarUrl, "parseSidecarUrl");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/sdk.js
function init2(options = {}) {
if (isAnrChildProcess()) {
options.autoSessionTracking = false;
options.tracesSampleRate = 0;
}
const carrier = getMainCarrier();
setNodeAsyncContextStrategy();
const autoloadedIntegrations = _optionalChain([carrier, "access", (_4) => _4.__SENTRY__, "optionalAccess", (_22) => _22.integrations]) || [];
options.defaultIntegrations = options.defaultIntegrations === false ? [] : [
...Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations,
...autoloadedIntegrations
];
if (options.dsn === void 0 && process.env.SENTRY_DSN) {
options.dsn = process.env.SENTRY_DSN;
}
const sentryTracesSampleRate = process.env.SENTRY_TRACES_SAMPLE_RATE;
if (options.tracesSampleRate === void 0 && sentryTracesSampleRate) {
const tracesSampleRate = parseFloat(sentryTracesSampleRate);
if (isFinite(tracesSampleRate)) {
options.tracesSampleRate = tracesSampleRate;
}
}
if (options.release === void 0) {
const detectedRelease = getSentryRelease();
if (detectedRelease !== void 0) {
options.release = detectedRelease;
} else {
options.autoSessionTracking = false;
}
}
if (options.environment === void 0 && process.env.SENTRY_ENVIRONMENT) {
options.environment = process.env.SENTRY_ENVIRONMENT;
}
if (options.autoSessionTracking === void 0 && options.dsn !== void 0) {
options.autoSessionTracking = true;
}
if (options.instrumenter === void 0) {
options.instrumenter = "sentry";
}
const clientOptions = {
...options,
stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
integrations: getIntegrationsToSetup(options),
transport: options.transport || makeNodeTransport
};
initAndBind(options.clientClass || NodeClient, clientOptions);
if (options.autoSessionTracking) {
startSessionTracking();
}
updateScopeFromEnvVariables();
if (options.spotlight) {
const client = getCurrentHub().getClient();
if (client && client.addIntegration) {
client.setupIntegrations(true);
client.addIntegration(
new Spotlight({ sidecarUrl: typeof options.spotlight === "string" ? options.spotlight : void 0 })
);
}
}
}
function getSentryRelease(fallback) {
if (process.env.SENTRY_RELEASE) {
return process.env.SENTRY_RELEASE;
}
if (GLOBAL_OBJ.SENTRY_RELEASE && GLOBAL_OBJ.SENTRY_RELEASE.id) {
return GLOBAL_OBJ.SENTRY_RELEASE.id;
}
return (
// GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
process.env.GITHUB_SHA || // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
process.env.COMMIT_REF || // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
process.env.VERCEL_GIT_COMMIT_SHA || process.env.VERCEL_GITHUB_COMMIT_SHA || process.env.VERCEL_GITLAB_COMMIT_SHA || process.env.VERCEL_BITBUCKET_COMMIT_SHA || // Zeit (now known as Vercel)
process.env.ZEIT_GITHUB_COMMIT_SHA || process.env.ZEIT_GITLAB_COMMIT_SHA || process.env.ZEIT_BITBUCKET_COMMIT_SHA || // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
process.env.CF_PAGES_COMMIT_SHA || fallback
);
}
function startSessionTracking() {
const hub = getCurrentHub();
hub.startSession();
process.on("beforeExit", () => {
const session = hub.getScope().getSession();
const terminalStates = ["exited", "crashed"];
if (session && !terminalStates.includes(session.status)) hub.endSession();
});
}
function updateScopeFromEnvVariables() {
const sentryUseEnvironment = (process.env.SENTRY_USE_ENVIRONMENT || "").toLowerCase();
if (!["false", "n", "no", "off", "0"].includes(sentryUseEnvironment)) {
const sentryTraceEnv = process.env.SENTRY_TRACE;
const baggageEnv = process.env.SENTRY_BAGGAGE;
const { propagationContext } = tracingContextFromHeaders(sentryTraceEnv, baggageEnv);
getCurrentHub().getScope().setPropagationContext(propagationContext);
}
}
var defaultIntegrations, defaultStackParser;
var init_sdk2 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/sdk.js"() {
init_import_meta_url();
init_esm6();
init_esm7();
init_esm6();
init_anr();
init_async();
init_client9();
init_console2();
init_http4();
init_onuncaughtexception();
init_onunhandledrejection();
init_modules();
init_contextlines();
init_context();
init_localvariables();
init_undici();
init_spotlight();
init_module4();
init_http2();
defaultIntegrations = [
// Common
new integrations_exports.InboundFilters(),
new integrations_exports.FunctionToString(),
new integrations_exports.LinkedErrors(),
// Native Wrappers
new Console(),
new Http(),
new Undici(),
// Global Handlers
new OnUncaughtException(),
new OnUnhandledRejection(),
// Event Info
new ContextLines(),
new LocalVariables(),
new Context(),
new Modules(),
new RequestData()
];
__name(init2, "init");
__name(getSentryRelease, "getSentryRelease");
defaultStackParser = createStackParser(nodeStackLineParser(getModuleFromFilename));
__name(startSessionTracking, "startSessionTracking");
__name(updateScopeFromEnvVariables, "updateScopeFromEnvVariables");
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/index.js
var integrations_exports2 = {};
__export(integrations_exports2, {
Console: () => Console,
Context: () => Context,
ContextLines: () => ContextLines,
Http: () => Http,
LocalVariables: () => LocalVariables,
Modules: () => Modules,
OnUncaughtException: () => OnUncaughtException,
OnUnhandledRejection: () => OnUnhandledRejection,
RequestData: () => RequestData,
Spotlight: () => Spotlight,
Undici: () => Undici
});
var init_integrations2 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/integrations/index.js"() {
init_import_meta_url();
init_console2();
init_http4();
init_onuncaughtexception();
init_onunhandledrejection();
init_modules();
init_contextlines();
init_context();
init_esm7();
init_localvariables();
init_undici();
init_spotlight();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/tracing/integrations.js
var integrations_exports3 = {};
__export(integrations_exports3, {
Apollo: () => Apollo,
Express: () => Express,
GraphQL: () => GraphQL,
Mongo: () => Mongo,
Mysql: () => Mysql,
Postgres: () => Postgres,
Prisma: () => Prisma
});
var init_integrations3 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/tracing/integrations.js"() {
init_import_meta_url();
init_esm8();
}
});
// ../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/index.js
var INTEGRATIONS;
var init_esm9 = __esm({
"../../node_modules/.pnpm/@sentry+node@7.87.0_supports-color@9.2.2/node_modules/@sentry/node/esm/index.js"() {
init_import_meta_url();
init_esm7();
init_esm7();
init_sdk2();
init_integrations2();
init_integrations3();
INTEGRATIONS = {
...integrations_exports,
...integrations_exports2,
...integrations_exports3
};
}
});
// src/sentry/index.ts
function setupSentry() {
if (true) {
init2({
release: `wrangler@${version}`,
dsn: "https://9edbb8417b284aa2bbead9b4c318918b@sentry10.cfdata.org/583",
transport: makeSentry10Transport,
integrations(defaultIntegrations2) {
return defaultIntegrations2.filter(
({ name: name2 }) => !disabledDefaultIntegrations.includes(name2)
);
},
beforeSend(event) {
delete event.server_name;
if (event.contexts !== void 0) {
delete event.contexts.culture;
}
const fakeInstallPath = process.platform === "win32" ? "C:\\Project\\" : "/project/";
for (const exception of event.exception?.values ?? []) {
for (const frame of exception.stacktrace?.frames ?? []) {
if (frame.filename === void 0) {
continue;
}
const nodeModulesIndex = frame.filename.indexOf("node_modules");
if (nodeModulesIndex === -1) {
continue;
}
frame.filename = fakeInstallPath + frame.filename.substring(nodeModulesIndex);
}
}
return event;
}
});
}
}
function addBreadcrumb2(message, level = "log") {
if (true) {
addBreadcrumb({
message,
level
});
}
}
async function captureGlobalException(e7) {
if (true) {
sentryReportingAllowed = await confirm(
"Would you like to report this error to Cloudflare? Wrangler's output and the error details will be shared with the Wrangler team to help us diagnose and fix the issue.",
{ fallbackValue: false }
);
if (!sentryReportingAllowed) {
logger.debug(`Sentry: Reporting disabled - would have sent ${e7}.`);
return;
}
logger.debug(`Sentry: Capturing exception ${e7}`);
captureException(e7);
}
}
async function closeSentry() {
if (true) {
await close();
}
}
var import_undici16, sentryReportingAllowed, makeSentry10Transport, disabledDefaultIntegrations;
var init_sentry = __esm({
"src/sentry/index.ts"() {
init_import_meta_url();
init_esm9();
init_esm6();
import_undici16 = __toESM(require_undici());
init_package();
init_dialogs();
init_logger();
sentryReportingAllowed = false;
makeSentry10Transport = /* @__PURE__ */ __name((options) => {
let eventQueue = [];
const transportSentry10 = /* @__PURE__ */ __name(async (request4) => {
const sentryWorkerPayload = {
envelope: request4.body,
url: options.url
};
try {
if (sentryReportingAllowed) {
const eventsToSend = [...eventQueue];
eventQueue = [];
for (const event of eventsToSend) {
await (0, import_undici16.fetch)(event[0], event[1]);
}
const response = await (0, import_undici16.fetch)(
`https://platform.dash.cloudflare.com/sentry/envelope`,
{
method: "POST",
headers: {
Accept: "*/*",
"Content-Type": "application/json"
},
body: JSON.stringify(sentryWorkerPayload)
}
);
return {
statusCode: response.status,
headers: {
"x-sentry-rate-limits": response.headers.get(
"X-Sentry-Rate-Limits"
),
"retry-after": response.headers.get("Retry-After")
}
};
} else {
eventQueue.push([
`https://platform.dash.cloudflare.com/sentry/envelope`,
{
method: "POST",
headers: {
Accept: "*/*",
"Content-Type": "application/json"
},
body: JSON.stringify(sentryWorkerPayload)
}
]);
return {
statusCode: 200
};
}
} catch (err) {
logger.error(err);
return rejectedSyncPromise(err);
}
}, "transportSentry10");
return createTransport(options, transportSentry10);
}, "makeSentry10Transport");
disabledDefaultIntegrations = [
"LocalVariables",
// Local variables may contain tokens and PII
"Http",
// Only captures method/URL/response status, but URL may contain PII
"Undici",
// Same as "Http"
"RequestData"
// Request data to Wrangler's HTTP servers may contain PII
];
__name(setupSentry, "setupSentry");
__name(addBreadcrumb2, "addBreadcrumb");
__name(captureGlobalException, "captureGlobalException");
__name(closeSentry, "closeSentry");
}
});
// src/tail/index.ts
var import_promises28, import_signal_exit6, tailCommand;
var init_tail = __esm({
"src/tail/index.ts"() {
init_import_meta_url();
import_promises28 = require("timers/promises");
import_signal_exit6 = __toESM(require_signal_exit());
init_config2();
init_create_command();
init_errors();
init_logger();
init_metrics();
init_user2();
init_getLegacyScriptName();
init_isLegacyEnv();
init_wrangler_banner();
init_zones();
init_createTail();
tailCommand = createCommand({
metadata: {
description: "\u{1F99A} Start a log tailing session for a Worker",
status: "stable",
owner: "Workers: Workers Observability"
},
positionalArgs: ["worker"],
args: {
worker: {
describe: "Name or route of the worker to tail",
type: "string"
},
format: {
choices: ["json", "pretty"],
describe: "The format of log entries"
},
status: {
choices: ["ok", "error", "canceled"],
describe: "Filter by invocation status",
array: true
},
header: {
type: "string",
requiresArg: true,
describe: "Filter by HTTP header"
},
method: {
type: "string",
requiresArg: true,
describe: "Filter by HTTP method",
array: true
},
"sampling-rate": {
type: "number",
describe: "Adds a percentage of requests to log sampling rate"
},
search: {
type: "string",
requiresArg: true,
describe: "Filter by a text match in console.log messages"
},
ip: {
type: "string",
requiresArg: true,
describe: 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
array: true
},
"version-id": {
type: "string",
requiresArg: true,
describe: "Filter by Worker version"
},
debug: {
type: "boolean",
hidden: true,
default: false,
describe: "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it."
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
behaviour: {
printBanner: false
},
async handler(args, { config }) {
args.format ??= process.stdout.isTTY ? "pretty" : "json";
if (args.format === "pretty") {
await printWranglerBanner();
}
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\nFor Pages, please run `wrangler pages deployment tail` instead."
);
}
sendMetricsEvent("begin log stream", {
sendMetrics: config.send_metrics
});
let scriptName;
const accountId = await requireAuth(config);
if (args.worker?.includes(".")) {
scriptName = await getWorkerForZone(
config,
{
worker: args.worker,
accountId
},
config.configPath
);
if (args.format === "pretty") {
logger.log(
`Connecting to worker ${scriptName} at route ${args.worker}`
);
}
} else {
scriptName = getLegacyScriptName({ name: args.worker, ...args }, config);
}
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`wrangler tail <worker-name>\``
);
}
const cliFilters = {
status: args.status,
header: args.header,
method: args.method,
samplingRate: args.samplingRate,
search: args.search,
clientIp: args.ip,
versionId: args.versionId
};
const filters = translateCLICommandToFilterMessage(cliFilters);
const { tail, expiration, deleteTail } = await createTail(
config,
accountId,
scriptName,
filters,
args.debug,
!isLegacyEnv(config) ? args.env : void 0
);
const scriptDisplayName = `${scriptName}${args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""}`;
if (args.format === "pretty") {
logger.log(
`Successfully created tail, expires at ${expiration.toLocaleString()}`
);
}
const printLog = args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
tail.on("message", printLog);
while (tail.readyState !== tail.OPEN) {
switch (tail.readyState) {
case tail.CONNECTING:
await (0, import_promises28.setTimeout)(100);
break;
case tail.CLOSING:
await (0, import_promises28.setTimeout)(100);
break;
case tail.CLOSED:
sendMetricsEvent("end log stream", {
sendMetrics: config.send_metrics
});
throw new Error(
`Connection to ${scriptDisplayName} closed unexpectedly.`
);
}
}
if (args.format === "pretty") {
logger.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
}
const cancelPing = startWebSocketPing();
tail.on("close", exit4);
(0, import_signal_exit6.default)(exit4);
async function exit4() {
cancelPing();
tail.terminate();
await deleteTail();
sendMetricsEvent("end log stream", {
sendMetrics: config.send_metrics
});
}
__name(exit4, "exit");
function startWebSocketPing() {
const PING_MESSAGE = Buffer.from("wrangler tail ping");
const PING_INTERVAL = 1e4;
let waitingForPong = false;
const pingInterval = setInterval(() => {
if (waitingForPong) {
throw createFatalError(
"Tail disconnected, exiting.",
args.format === "json",
1,
{ telemetryMessage: true }
);
}
waitingForPong = true;
tail.ping(PING_MESSAGE);
}, PING_INTERVAL);
tail.on("pong", (data) => {
if (data.equals(PING_MESSAGE)) {
waitingForPong = false;
}
});
return () => clearInterval(pingInterval);
}
__name(startWebSocketPing, "startWebSocketPing");
}
});
}
});
// src/triggers/index.ts
var triggersNamespace, triggersDeployCommand;
var init_triggers = __esm({
"src/triggers/index.ts"() {
init_import_meta_url();
init_assets();
init_create_command();
init_metrics();
init_user2();
init_getScriptName();
init_isLegacyEnv();
init_deploy3();
triggersNamespace = createNamespace({
metadata: {
description: "\u{1F3AF} Updates the triggers of your current deployment",
status: "experimental",
owner: "Workers: Authoring and Testing"
}
});
triggersDeployCommand = createCommand({
metadata: {
description: "Updates the triggers of your current deployment",
status: "experimental",
owner: "Workers: Authoring and Testing"
},
args: {
name: {
describe: "Name of the worker",
type: "string",
requiresArg: true
},
triggers: {
describe: "cron schedules to attach",
alias: ["schedule", "schedules"],
type: "string",
requiresArg: true,
array: true
},
routes: {
describe: "Routes to upload",
alias: "route",
type: "string",
requiresArg: true,
array: true
},
"dry-run": {
describe: "Don't actually deploy",
type: "boolean"
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
}
},
behaviour: {
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
async handler(args, { config }) {
const assetsOptions = getAssetsOptions({ assets: void 0 }, config);
sendMetricsEvent(
"deploy worker triggers",
{},
{
sendMetrics: config.send_metrics
}
);
const accountId = args.dryRun ? void 0 : await requireAuth(config);
await triggersDeploy({
config,
accountId,
name: getScriptName(args, config),
env: args.env,
triggers: args.triggers,
routes: args.routes,
legacyEnv: isLegacyEnv(config),
dryRun: args.dryRun,
assetsOptions
});
}
});
}
});
// src/dev/dev-vars.ts
function getVarsForDev(configPath, envFiles, vars, env6, silent = false) {
const configDir = path56.resolve(configPath ? path56.dirname(configPath) : ".");
const devVarsPath = path56.resolve(configDir, ".dev.vars");
const loaded = loadDotDevDotVars(devVarsPath, env6);
if (loaded !== void 0) {
const devVarsRelativePath = path56.relative(process.cwd(), loaded.path);
if (!silent) {
logger.log(`Using vars defined in ${devVarsRelativePath}`);
}
return { ...vars, ...loaded.parsed };
} else if (getCloudflareLoadDevVarsFromDotEnv()) {
const resolvedEnvFilePaths = (envFiles ?? getDefaultEnvFiles(env6)).map(
(p6) => path56.resolve(configDir, p6)
);
const dotEnvVars = loadDotEnv(resolvedEnvFilePaths, {
includeProcessEnv: getCloudflareIncludeProcessEnvFromEnv(),
silent
});
return { ...vars, ...dotEnvVars };
} else {
return vars;
}
}
function tryLoadDotDevDotVars(basePath) {
try {
const contents = maybeGetFile(basePath);
if (contents === void 0) {
logger.debug(
`local dev variables file not found at "${path56.relative(".", basePath)}". Continuing... For more details, refer to https://developers.cloudflare.com/workers/wrangler/system-environment-variables/`
);
return;
}
const parsed = import_dotenv3.default.parse(contents);
return { path: basePath, parsed };
} catch (e7) {
throw new Error(
`Failed to load local dev variables file "${path56.relative(".", basePath)}":`,
{ cause: e7 }
);
}
}
function loadDotDevDotVars(envPath, env6) {
return env6 !== void 0 && tryLoadDotDevDotVars(`${envPath}.${env6}`) || tryLoadDotDevDotVars(envPath);
}
var path56, import_dotenv3;
var init_dev_vars = __esm({
"src/dev/dev-vars.ts"() {
init_import_meta_url();
path56 = __toESM(require("path"));
init_workers_shared();
import_dotenv3 = __toESM(require_main());
init_dot_env();
init_misc_variables();
init_logger();
__name(getVarsForDev, "getVarsForDev");
__name(tryLoadDotDevDotVars, "tryLoadDotDevDotVars");
__name(loadDotDevDotVars, "loadDotDevDotVars");
}
});
// src/process-env.ts
function isProcessEnvPopulated(compatibility_date, compatibility_flags = []) {
if (compatibility_flags.includes("nodejs_compat_populate_process_env") && compatibility_flags.includes("nodejs_compat_do_not_populate_process_env")) {
throw new UserError("Can't both enable and disable a flag");
}
if (compatibility_flags.includes("nodejs_compat_populate_process_env") && compatibility_flags.includes("nodejs_compat")) {
return true;
}
if (compatibility_flags.includes("nodejs_compat_do_not_populate_process_env")) {
return false;
}
return compatibility_flags.includes("nodejs_compat") && !!compatibility_date && compatibility_date >= "2025-04-01";
}
var init_process_env = __esm({
"src/process-env.ts"() {
init_import_meta_url();
init_errors();
__name(isProcessEnvPopulated, "isProcessEnvPopulated");
}
});
// src/type-generation/runtime/index.ts
async function generateRuntimeTypes({
config: { compatibility_date, compatibility_flags = [] },
outFile = DEFAULT_OUTFILE_RELATIVE_PATH
}) {
if (!compatibility_date) {
throw new Error("Config must have a compatibility date.");
}
const header = `// Runtime types generated with workerd@${import_workerd.version} ${compatibility_date} ${compatibility_flags.sort().join(",")}`;
try {
const lines = (await (0, import_promises29.readFile)(outFile, "utf8")).split("\n");
const existingHeader = lines.find(
(line) => line.startsWith("// Runtime types generated with workerd@")
);
const existingTypesStart = lines.findIndex(
(line) => line === "// Begin runtime types"
);
if (existingHeader === header && existingTypesStart !== -1) {
logger.debug("Using cached runtime types: ", header);
return {
runtimeHeader: header,
runtimeTypes: lines.slice(existingTypesStart + 1).join("\n")
};
}
} catch (e7) {
if (e7.code !== "ENOENT") {
throw e7;
}
}
const types3 = await generate({
compatibilityDate: compatibility_date,
// Ignore nodejs compat flags as there is currently no mechanism to generate these dynamically.
compatibilityFlags: compatibility_flags.filter(
(flag) => !flag.includes("nodejs_compat")
)
});
return { runtimeHeader: header, runtimeTypes: types3 };
}
async function generate({
compatibilityDate,
compatibilityFlags = []
}) {
const worker = (0, import_fs26.readFileSync)(require.resolve("workerd/worker.mjs")).toString();
const mf = new import_miniflare19.Miniflare({
compatibilityDate: "2024-01-01",
compatibilityFlags: ["nodejs_compat", "rtti_api"],
modules: true,
script: worker
});
const flagsString = compatibilityFlags.length ? `+${compatibilityFlags.join("+")}` : "";
const path72 = `http://dummy.com/${compatibilityDate}${flagsString}`;
try {
const res = await mf.dispatchFetch(path72);
const text = await res.text();
if (!res.ok) {
throw new Error(text);
}
return text;
} finally {
await mf.dispose();
}
}
var import_fs26, import_promises29, import_miniflare19, import_workerd, DEFAULT_OUTFILE_RELATIVE_PATH;
var init_runtime = __esm({
"src/type-generation/runtime/index.ts"() {
init_import_meta_url();
import_fs26 = require("fs");
import_promises29 = require("fs/promises");
import_miniflare19 = require("miniflare");
import_workerd = require("workerd");
init_logger();
DEFAULT_OUTFILE_RELATIVE_PATH = "worker-configuration.d.ts";
__name(generateRuntimeTypes, "generateRuntimeTypes");
__name(generate, "generate");
}
});
// src/type-generation/runtime/log-runtime-types-message.ts
function logRuntimeTypesMessage(tsconfigTypes, isNodeCompat = false) {
const isWorkersTypesInstalled = tsconfigTypes.find(
(type) => type.startsWith("@cloudflare/workers-types")
);
const maybeHasOldRuntimeFile = (0, import_node_fs29.existsSync)("./.wrangler/types/runtime.d.ts");
if (maybeHasOldRuntimeFile) {
logAction("Remove the old runtime.d.ts file");
logger.log(
source_default.dim(
"`wrangler types` now outputs runtime and Env types in one file.\nYou can now delete the ./.wrangler/types/runtime.d.ts and update your tsconfig.json`"
)
);
logger.log("");
}
if (isWorkersTypesInstalled) {
logAction(
"Migrate from @cloudflare/workers-types to generated runtime types"
);
logger.log(
source_default.dim(
"`wrangler types` now generates runtime types and supersedes @cloudflare/workers-types.\nYou should now uninstall @cloudflare/workers-types and remove it from your tsconfig.json."
)
);
logger.log("");
}
let isNodeTypesInstalled = Boolean(
tsconfigTypes.find((type) => type === "node")
);
if (!isNodeTypesInstalled && isNodeCompat) {
const nodeModules = findUpMultipleSync("node_modules", {
type: "directory"
});
for (const folder of nodeModules) {
if (nodeModules && (0, import_node_fs29.existsSync)((0, import_node_path53.join)(folder, "@types/node"))) {
isNodeTypesInstalled = true;
break;
}
}
}
if (isNodeCompat && !isNodeTypesInstalled) {
logAction("Install @types/node");
logger.log(
source_default.dim(
`Since you have the \`nodejs_compat\` flag, you should install Node.js types by running "npm i --save-dev @types/node".`
)
);
logger.log("");
}
logger.log(
`\u{1F4D6} Read about runtime types
${source_default.dim("https://developers.cloudflare.com/workers/languages/typescript/#generate-types")}`
);
}
var import_node_fs29, import_node_path53, logAction;
var init_log_runtime_types_message = __esm({
"src/type-generation/runtime/log-runtime-types-message.ts"() {
init_import_meta_url();
import_node_fs29 = require("fs");
import_node_path53 = require("path");
init_source();
init_find_up();
init_logger();
__name(logRuntimeTypesMessage, "logRuntimeTypesMessage");
logAction = /* @__PURE__ */ __name((msg) => {
logger.log(source_default.hex("#BD5B08").bold("Action required"), msg);
}, "logAction");
}
});
// src/type-generation/index.ts
function isValidIdentifier2(key) {
return /^[a-zA-Z_$][\w$]*$/.test(key);
}
function constructTypeKey(key) {
if (isValidIdentifier2(key)) {
return `${key}`;
}
return `"${key}"`;
}
function constructTSModuleGlob(glob) {
if (!glob.includes("*")) {
return glob;
} else if (glob.includes(".")) {
return `*.${glob.split(".").at(-1)}`;
} else {
return glob.replace("**/*", "*").replace("**/", "*/").replace("/**", "/*");
}
}
function generateImportSpecifier(from, to) {
const relativePath = (0, import_node_path54.relative)((0, import_node_path54.dirname)(from), (0, import_node_path54.dirname)(to)).replace(/\\/g, "/");
const filename = (0, import_node_path54.basename)(to, (0, import_node_path54.extname)(to));
if (!relativePath) {
return `./${filename}`;
} else if (relativePath.startsWith("..")) {
return `${relativePath}/${filename}`;
} else {
return `./${relativePath}/${filename}`;
}
}
async function generateEnvTypes(config, args, envInterface, outputPath, entrypoint, serviceEntries, log2 = true) {
const stringKeys = [];
const secrets = getVarsForDev(
config.userConfigPath,
args.envFile,
// We do not want `getVarsForDev()` to merge in the standard vars into the dev vars
// because we want to be able to work with secrets differently to vars.
// So we pass in a fake vars object here.
{},
args.env,
true
);
const configToDTS = {
kv_namespaces: config.kv_namespaces ?? [],
vars: collectAllVars({ ...args, config: config.configPath }),
wasm_modules: config.wasm_modules,
text_blobs: {
...config.text_blobs
},
data_blobs: config.data_blobs,
durable_objects: config.durable_objects,
r2_buckets: config.r2_buckets,
d1_databases: config.d1_databases,
services: config.services,
analytics_engine_datasets: config.analytics_engine_datasets,
dispatch_namespaces: config.dispatch_namespaces,
logfwdr: config.logfwdr,
unsafe: config.unsafe,
rules: config.rules,
queues: config.queues,
send_email: config.send_email,
vectorize: config.vectorize,
hyperdrive: config.hyperdrive,
mtls_certificates: config.mtls_certificates,
browser: config.browser,
images: config.images,
ai: config.ai,
version_metadata: config.version_metadata,
secrets,
assets: config.assets,
workflows: config.workflows,
pipelines: config.pipelines,
secrets_store_secrets: config.secrets_store_secrets,
unsafe_hello_world: config.unsafe_hello_world
};
const entrypointFormat = entrypoint?.format ?? "modules";
const fullOutputPath = (0, import_node_path54.resolve)(outputPath);
const userProvidedEnvInterface = envInterface !== "Env";
if (userProvidedEnvInterface && entrypointFormat === "service-worker") {
throw new Error(
"An env-interface value has been provided but the worker uses the incompatible Service Worker syntax"
);
}
const envTypeStructure = [];
if (configToDTS.kv_namespaces) {
for (const kvNamespace2 of configToDTS.kv_namespaces) {
envTypeStructure.push([
constructTypeKey(kvNamespace2.binding),
"KVNamespace"
]);
}
}
if (configToDTS.vars) {
const vars = Object.entries(configToDTS.vars).filter(
([key]) => !(key in configToDTS.secrets)
);
for (const [varName, varValues] of vars) {
envTypeStructure.push([
constructTypeKey(varName),
varValues.length === 1 ? varValues[0] : varValues.join(" | ")
]);
stringKeys.push(varName);
}
}
for (const secretName in configToDTS.secrets) {
envTypeStructure.push([constructTypeKey(secretName), "string"]);
stringKeys.push(secretName);
}
if (configToDTS.durable_objects?.bindings) {
for (const durableObject of configToDTS.durable_objects.bindings) {
const doEntrypoint = durableObject.script_name ? serviceEntries?.get(durableObject.script_name) : entrypoint;
const importPath = doEntrypoint ? generateImportSpecifier(fullOutputPath, doEntrypoint.file) : void 0;
const exportExists = doEntrypoint?.exports?.some(
(e7) => e7 === durableObject.class_name
);
let typeName;
if (importPath && exportExists) {
typeName = `DurableObjectNamespace<import("${importPath}").${durableObject.class_name}>`;
} else if (durableObject.script_name) {
typeName = `DurableObjectNamespace /* ${durableObject.class_name} from ${durableObject.script_name} */`;
} else {
typeName = `DurableObjectNamespace /* ${durableObject.class_name} */`;
}
envTypeStructure.push([constructTypeKey(durableObject.name), typeName]);
}
}
if (configToDTS.r2_buckets) {
for (const R2Bucket of configToDTS.r2_buckets) {
envTypeStructure.push([constructTypeKey(R2Bucket.binding), "R2Bucket"]);
}
}
if (configToDTS.d1_databases) {
for (const d1 of configToDTS.d1_databases) {
envTypeStructure.push([constructTypeKey(d1.binding), "D1Database"]);
}
}
if (configToDTS.secrets_store_secrets) {
for (const secretsStoreSecret of configToDTS.secrets_store_secrets) {
envTypeStructure.push([
constructTypeKey(secretsStoreSecret.binding),
"SecretsStoreSecret"
]);
}
}
if (configToDTS.unsafe_hello_world) {
for (const helloWorld of configToDTS.unsafe_hello_world) {
envTypeStructure.push([
constructTypeKey(helloWorld.binding),
"HelloWorldBinding"
]);
}
}
if (configToDTS.services) {
for (const service of configToDTS.services) {
const serviceEntry = service.service !== entrypoint?.name ? serviceEntries?.get(service.service) : entrypoint;
const importPath = serviceEntry ? generateImportSpecifier(fullOutputPath, serviceEntry.file) : void 0;
const exportExists = serviceEntry?.exports?.some(
(e7) => e7 === (service.entrypoint ?? "default")
);
let typeName;
if (importPath && exportExists) {
typeName = `Service<typeof import("${importPath}").${service.entrypoint ?? "default"}>`;
} else if (service.entrypoint) {
typeName = `Service /* entrypoint ${service.entrypoint} from ${service.service} */`;
} else {
typeName = `Fetcher /* ${service.service} */`;
}
envTypeStructure.push([constructTypeKey(service.binding), typeName]);
}
}
if (configToDTS.analytics_engine_datasets) {
for (const analyticsEngine of configToDTS.analytics_engine_datasets) {
envTypeStructure.push([
constructTypeKey(analyticsEngine.binding),
"AnalyticsEngineDataset"
]);
}
}
if (configToDTS.dispatch_namespaces) {
for (const namespace of configToDTS.dispatch_namespaces) {
envTypeStructure.push([
constructTypeKey(namespace.binding),
"DispatchNamespace"
]);
}
}
if (configToDTS.logfwdr?.bindings?.length) {
envTypeStructure.push([constructTypeKey("LOGFWDR_SCHEMA"), "any"]);
}
if (configToDTS.data_blobs) {
for (const dataBlobs in configToDTS.data_blobs) {
envTypeStructure.push([constructTypeKey(dataBlobs), "ArrayBuffer"]);
}
}
if (configToDTS.text_blobs) {
for (const textBlobs in configToDTS.text_blobs) {
envTypeStructure.push([constructTypeKey(textBlobs), "string"]);
}
}
if (configToDTS.unsafe?.bindings) {
for (const unsafe of configToDTS.unsafe.bindings) {
if (unsafe.type === "ratelimit") {
envTypeStructure.push([constructTypeKey(unsafe.name), "RateLimit"]);
} else {
envTypeStructure.push([constructTypeKey(unsafe.name), "any"]);
}
}
}
if (configToDTS.queues) {
if (configToDTS.queues.producers) {
for (const queue of configToDTS.queues.producers) {
envTypeStructure.push([constructTypeKey(queue.binding), "Queue"]);
}
}
}
if (configToDTS.send_email) {
for (const sendEmail of configToDTS.send_email) {
envTypeStructure.push([constructTypeKey(sendEmail.name), "SendEmail"]);
}
}
if (configToDTS.vectorize) {
for (const vectorize of configToDTS.vectorize) {
envTypeStructure.push([
constructTypeKey(vectorize.binding),
"VectorizeIndex"
]);
}
}
if (configToDTS.hyperdrive) {
for (const hyperdrive of configToDTS.hyperdrive) {
envTypeStructure.push([
constructTypeKey(hyperdrive.binding),
"Hyperdrive"
]);
}
}
if (configToDTS.mtls_certificates) {
for (const mtlsCertificate of configToDTS.mtls_certificates) {
envTypeStructure.push([
constructTypeKey(mtlsCertificate.binding),
"Fetcher"
]);
}
}
if (configToDTS.browser) {
envTypeStructure.push([
constructTypeKey(configToDTS.browser.binding),
"Fetcher"
]);
}
if (configToDTS.ai) {
envTypeStructure.push([constructTypeKey(configToDTS.ai.binding), "Ai"]);
}
if (configToDTS.images) {
envTypeStructure.push([
constructTypeKey(configToDTS.images.binding),
"ImagesBinding"
]);
}
if (configToDTS.version_metadata) {
envTypeStructure.push([
configToDTS.version_metadata.binding,
"WorkerVersionMetadata"
]);
}
if (configToDTS.assets?.binding) {
envTypeStructure.push([
constructTypeKey(configToDTS.assets.binding),
"Fetcher"
]);
}
if (configToDTS.workflows) {
for (const workflow of configToDTS.workflows) {
envTypeStructure.push([constructTypeKey(workflow.binding), "Workflow"]);
}
}
if (configToDTS.pipelines) {
for (const pipeline of configToDTS.pipelines) {
envTypeStructure.push([
constructTypeKey(pipeline.binding),
`import("cloudflare:pipelines").Pipeline<import("cloudflare:pipelines").PipelineRecord>`
]);
}
}
const modulesTypeStructure = [];
if (configToDTS.rules) {
const moduleTypeMap = {
Text: "string",
Data: "ArrayBuffer",
CompiledWasm: "WebAssembly.Module"
};
for (const ruleObject of configToDTS.rules) {
const typeScriptType = moduleTypeMap[ruleObject.type];
if (typeScriptType !== void 0) {
ruleObject.globs.forEach((glob) => {
modulesTypeStructure.push(`declare module "${constructTSModuleGlob(glob)}" {
const value: ${typeScriptType};
export default value;
}`);
});
}
}
}
const wranglerCommandUsed = ["wrangler", ...process.argv.slice(2)].join(" ");
const typesHaveBeenFound = envTypeStructure.length || modulesTypeStructure.length;
if (entrypointFormat === "modules" || typesHaveBeenFound) {
const { fileContent, consoleOutput } = generateTypeStrings(
entrypointFormat,
envInterface,
envTypeStructure.map(([key, value]) => `${key}: ${value};`),
modulesTypeStructure,
stringKeys,
config.compatibility_date,
config.compatibility_flags
);
const hash = (0, import_node_crypto11.createHash)("sha256").update(consoleOutput).digest("hex").slice(0, 32);
const envHeader = `// Generated by Wrangler by running \`${wranglerCommandUsed}\` (hash: ${hash})`;
if (log2) {
logger.log(source_default.dim(consoleOutput));
}
return { envHeader, envTypes: fileContent };
} else {
if (log2) {
logger.log(source_default.dim("No project types to add.\n"));
}
return {
envHeader: void 0,
envTypes: void 0
};
}
}
function generateTypeStrings(formatType, envInterface, envTypeStructure, modulesTypeStructure, stringKeys, compatibilityDate, compatibilityFlags) {
let baseContent = "";
let processEnv = "";
if (formatType === "modules") {
if (isProcessEnvPopulated(compatibilityDate, compatibilityFlags) && stringKeys.length > 0) {
processEnv = `
type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, ${stringKeys.map((k6) => `"${k6}"`).join(" | ")}>> {}
}`;
}
baseContent = `declare namespace Cloudflare {
interface Env {${envTypeStructure.map((value) => `
${value}`).join("")}
}
}
interface ${envInterface} extends Cloudflare.Env {}${processEnv}`;
} else {
baseContent = `export {};
declare global {
${envTypeStructure.map((value) => ` const ${value}`).join("\n")}
}`;
}
const modulesContent = modulesTypeStructure.join("\n");
return {
fileContent: `${baseContent}
${modulesContent}`,
consoleOutput: `${baseContent}
${modulesContent}`
};
}
function readTsconfigTypes(tsconfigPath) {
if (!fs21.existsSync(tsconfigPath)) {
return [];
}
try {
const tsconfig = parseJSONC(
fs21.readFileSync(tsconfigPath, "utf-8")
);
return tsconfig.compilerOptions?.types || [];
} catch {
return [];
}
}
function collectAllVars(args) {
const varsInfo = {};
function collectEnvironmentVars(vars) {
Object.entries(vars ?? {}).forEach(([key, value]) => {
varsInfo[key] ??= /* @__PURE__ */ new Set();
if (!args.strictVars) {
varsInfo[key].add(
Array.isArray(value) ? typeofArray(value) : typeof value
);
return;
}
if (typeof value === "number" || typeof value === "boolean") {
varsInfo[key].add(`${value}`);
return;
}
if (typeof value === "string" || typeof value === "object") {
varsInfo[key].add(JSON.stringify(value));
return;
}
varsInfo[key].add("unknown");
});
}
__name(collectEnvironmentVars, "collectEnvironmentVars");
const { rawConfig } = experimental_readRawConfig(args);
collectEnvironmentVars(rawConfig.vars);
Object.entries(rawConfig.env ?? {}).forEach(([_envName, env6]) => {
collectEnvironmentVars(env6.vars);
});
return Object.fromEntries(
Object.entries(varsInfo).map(([key, value]) => [key, [...value]])
);
}
function typeofArray(array) {
const typesInArray = [...new Set(array.map((item) => typeof item))].sort();
if (typesInArray.length === 1) {
return `${typesInArray[0]}[]`;
}
return `(${typesInArray.join("|")})[]`;
}
var import_node_crypto11, fs21, import_node_path54, import_miniflare20, typesCommand, checkPath, logHorizontalRule;
var init_type_generation = __esm({
"src/type-generation/index.ts"() {
init_import_meta_url();
import_node_crypto11 = require("crypto");
fs21 = __toESM(require("fs"));
import_node_path54 = require("path");
init_source();
init_find_up();
import_miniflare20 = require("miniflare");
init_config2();
init_create_command();
init_entry();
init_dev_vars();
init_errors();
init_logger();
init_parse();
init_process_env();
init_runtime();
init_log_runtime_types_message();
typesCommand = createCommand({
metadata: {
description: "\u{1F4DD} Generate types from your Worker configuration\n",
status: "stable",
owner: "Workers: Authoring and Testing",
epilogue: "\u{1F4D6} Learn more at https://developers.cloudflare.com/workers/languages/typescript/#generate-types"
},
behaviour: {
provideConfig: false
},
positionalArgs: ["path"],
args: {
path: {
describe: "The path to the declaration file for the generated types",
type: "string",
default: "worker-configuration.d.ts",
demandOption: false
},
"env-interface": {
type: "string",
default: "Env",
describe: "The name of the generated environment interface",
requiresArg: true
},
"include-runtime": {
type: "boolean",
default: true,
describe: "Include runtime types in the generated types"
},
"include-env": {
type: "boolean",
default: true,
describe: "Include Env types in the generated types"
},
"strict-vars": {
type: "boolean",
default: true,
describe: "Generate literal and union types for variables"
},
"experimental-include-runtime": {
alias: "x-include-runtime",
type: "string",
describe: "The path of the generated runtime types file",
demandOption: false,
hidden: true,
deprecated: true
}
},
validateArgs(args) {
if (typeof args.experimentalIncludeRuntime === "string") {
throw new CommandLineArgsError(
"You no longer need to use --experimental-include-runtime.\n`wrangler types` will now generate runtime types in the same file as the Env types.\nYou should delete the old runtime types file, and remove it from your tsconfig.json.\nThen rerun `wrangler types`.",
{ telemetryMessage: true }
);
}
const validInterfaceRegex = /^[a-zA-Z][a-zA-Z0-9_]*$/;
if (!validInterfaceRegex.test(args.envInterface)) {
throw new CommandLineArgsError(
`The provided env-interface value ("${args.envInterface}") does not satisfy the validation regex: ${validInterfaceRegex}`,
{
telemetryMessage: "The provided env-interface value does not satisfy the validation regex"
}
);
}
if (!args.path.endsWith(".d.ts")) {
throw new CommandLineArgsError(
`The provided output path '${args.path}' does not point to a declaration file - please use the '.d.ts' extension`,
{
telemetryMessage: "The provided path does not point to a declaration file"
}
);
}
checkPath(args.path);
if (!args.includeEnv && !args.includeRuntime) {
throw new CommandLineArgsError(
`You cannot run this command without including either Env or Runtime types`,
{
telemetryMessage: true
}
);
}
},
async handler(args) {
let config;
const secondaryConfigs = [];
if (Array.isArray(args.config)) {
config = readConfig({ ...args, config: args.config[0] });
for (const configPath of args.config.slice(1)) {
secondaryConfigs.push(readConfig({ config: configPath }));
}
} else {
config = readConfig(args);
}
const { envInterface, path: outputPath } = args;
if (!config.configPath || !fs21.existsSync(config.configPath) || fs21.statSync(config.configPath).isDirectory()) {
throw new UserError(
`No config file detected${args.config ? ` (at ${args.config})` : ""}. This command requires a Wrangler configuration file.`,
{ telemetryMessage: "No config file detected" }
);
}
const secondaryEntries = /* @__PURE__ */ new Map();
if (secondaryConfigs.length > 0) {
for (const secondaryConfig of secondaryConfigs) {
const serviceEntry = await getEntry({}, secondaryConfig, "types");
if (serviceEntry.name) {
const key = serviceEntry.name;
if (secondaryEntries.has(key)) {
logger.warn(
`Configuration file for Worker '${key}' has been passed in more than once using \`--config\`. To remove this warning, only pass each unique Worker config file once.`
);
}
secondaryEntries.set(key, serviceEntry);
logger.log(
source_default.dim(
`- Found Worker '${key}' at '${(0, import_node_path54.relative)(process.cwd(), serviceEntry.file)}' (${secondaryConfig.configPath})`
)
);
} else {
throw new UserError(
`Could not resolve entry point for service config '${secondaryConfig}'.`
);
}
}
}
const configContainsEntrypoint = config.main !== void 0 || !!config.site?.["entry-point"];
let entrypoint;
if (configContainsEntrypoint) {
try {
entrypoint = await getEntry({}, config, "types");
} catch {
entrypoint = void 0;
}
}
const entrypointFormat = entrypoint?.format ?? "modules";
const header = ["/* eslint-disable */"];
const content = [];
if (args.includeEnv) {
logger.log(`Generating project types...
`);
const { envHeader, envTypes } = await generateEnvTypes(
config,
args,
envInterface,
outputPath,
entrypoint,
secondaryEntries
);
if (envHeader && envTypes) {
header.push(envHeader);
content.push(envTypes);
}
}
if (args.includeRuntime) {
logger.log("Generating runtime types...\n");
const { runtimeHeader, runtimeTypes } = await generateRuntimeTypes({
config,
outFile: outputPath || void 0
});
header.push(runtimeHeader);
content.push(`// Begin runtime types
${runtimeTypes}`);
logger.log(source_default.dim("Runtime types generated.\n"));
}
logHorizontalRule();
if (header.length && content.length || entrypointFormat === "modules") {
fs21.writeFileSync(
outputPath,
`${header.join("\n")}
${content.join("\n")}`,
"utf-8"
);
logger.log(`\u2728 Types written to ${outputPath}
`);
}
const tsconfigPath = config.tsconfig ?? (0, import_node_path54.join)((0, import_node_path54.dirname)(config.configPath), "tsconfig.json");
const tsconfigTypes = readTsconfigTypes(tsconfigPath);
const { mode } = (0, import_miniflare20.getNodeCompat)(
config.compatibility_date,
config.compatibility_flags
);
if (args.includeRuntime) {
logRuntimeTypesMessage(tsconfigTypes, mode !== null);
}
logger.log(
`\u{1F4E3} Remember to rerun 'wrangler types' after you change your ${configFileName(config.configPath)} file.
`
);
}
});
__name(isValidIdentifier2, "isValidIdentifier");
__name(constructTypeKey, "constructTypeKey");
__name(constructTSModuleGlob, "constructTSModuleGlob");
__name(generateImportSpecifier, "generateImportSpecifier");
__name(generateEnvTypes, "generateEnvTypes");
checkPath = /* @__PURE__ */ __name((path72) => {
const wranglerOverrideDTSPath = findUpSync(path72);
if (wranglerOverrideDTSPath === void 0) {
return;
}
try {
const fileContent = fs21.readFileSync(wranglerOverrideDTSPath, "utf8");
if (!fileContent.includes("Generated by Wrangler") && !fileContent.includes("Runtime types generated with workerd")) {
throw new UserError(
`A non-Wrangler ${(0, import_node_path54.basename)(path72)} already exists, please rename and try again.`,
{ telemetryMessage: "A non-Wrangler .d.ts file already exists" }
);
}
} catch (error2) {
if (error2 instanceof Error && !error2.message.includes("not found")) {
throw error2;
}
}
}, "checkPath");
__name(generateTypeStrings, "generateTypeStrings");
__name(readTsconfigTypes, "readTsconfigTypes");
__name(collectAllVars, "collectAllVars");
__name(typeofArray, "typeofArray");
logHorizontalRule = /* @__PURE__ */ __name(() => {
const screenWidth = process.stdout.columns;
logger.log(source_default.dim("\u2500".repeat(Math.min(screenWidth, 60))));
}, "logHorizontalRule");
}
});
// src/user/membership.ts
async function fetchMembershipRoles(complianceConfig, accountTag) {
const allMemberships = await fetchPagedListResult(
complianceConfig,
"/memberships"
);
const membership = allMemberships.find((m6) => m6.account.id === accountTag);
return membership?.roles;
}
var init_membership = __esm({
"src/user/membership.ts"() {
init_import_meta_url();
init_cfetch();
__name(fetchMembershipRoles, "fetchMembershipRoles");
}
});
// src/user/whoami.ts
async function whoami(complianceConfig, accountFilter) {
logger.log("Getting User settings...");
const user = await getUserInfo(complianceConfig);
if (!user) {
logger.log("You are not authenticated. Please run `wrangler login`.");
return;
}
printUserEmail(user);
if (user.authType === "User API Token" || user.authType === "Account API Token") {
logger.log(
"\u2139\uFE0F The API Token is read from the CLOUDFLARE_API_TOKEN environment variable."
);
}
printComplianceRegion(complianceConfig);
printAccountList(user);
printTokenPermissions(user);
await printMembershipInfo(complianceConfig, user, accountFilter);
}
function printComplianceRegion(complianceConfig) {
const complianceRegion = getCloudflareComplianceRegion(complianceConfig);
if (complianceRegion !== "public") {
const complianceRegionSource = complianceConfig?.compliance_region ? "Wrangler configuration" : "`CLOUDFLARE_COMPLIANCE_REGION` environment variable";
logger.log(
`\u{1F30D} The compliance region is set to "${source_default.blue(complianceRegion)}" via the ${complianceRegionSource}.`
);
}
}
function printUserEmail(user) {
if (user.authType === "Account API Token") {
const accountName = user.accounts[0].name;
return void logger.log(
`\u{1F44B} You are logged in with an ${user.authType}, associated with the account ${source_default.blue(accountName)}.`
);
}
if (!user.email) {
return void logger.log(
`\u{1F44B} You are logged in with an ${user.authType}. Unable to retrieve email for this user. Are you missing the \`User->User Details->Read\` permission?`
);
}
logger.log(
`\u{1F44B} You are logged in with an ${user.authType}, associated with the email ${source_default.blue(user.email)}.`
);
}
function printAccountList(user) {
logger.table(
user.accounts.map((account) => ({
"Account Name": account.name,
"Account ID": account.id
}))
);
}
function printTokenPermissions(user) {
const permissions = user.tokenPermissions?.map((scope) => scope.split(":")) ?? [];
if (user.authType !== "OAuth Token") {
return void logger.log(
`\u{1F513} To see token permissions visit https://dash.cloudflare.com/${user.authType === "User API Token" ? "profile" : user.accounts[0].id}/api-tokens.`
);
}
logger.log(`\u{1F513} Token Permissions:`);
logger.log(`Scope (Access)`);
const expectedScopes = new Set(DefaultScopeKeys);
for (const [scope, access4] of permissions) {
expectedScopes.delete(`${scope}:${access4}`);
logger.log(`- ${scope} ${access4 ? `(${access4})` : ``}`);
}
if (expectedScopes.size > 0) {
logger.log("");
logger.log(
formatMessage({
text: "Wrangler is missing some expected Oauth scopes. To fix this, run `wrangler login` to refresh your token. The missing scopes are:",
kind: "warning",
notes: [...expectedScopes.values()].map((s5) => ({ text: `- ${s5}` }))
})
);
}
}
async function printMembershipInfo(complianceConfig, user, accountFilter) {
try {
if (!accountFilter) {
return;
}
const eq = /* @__PURE__ */ __name((a5, b6) => a5.localeCompare(b6, void 0, { sensitivity: "base" }) == 0, "eq");
const selectedAccount = user.accounts.find(
(a5) => eq(a5.id, accountFilter) || eq(a5.name, accountFilter)
);
if (!selectedAccount) {
return;
}
const membershipRoles = await fetchMembershipRoles(
complianceConfig,
selectedAccount.id
);
if (!membershipRoles) {
return;
}
logger.log(
`\u{1F3A2} Membership roles in "${selectedAccount.name}": Contact account super admin to change your permissions.`
);
for (const role of membershipRoles) {
logger.log(`- ${role}`);
}
} catch (e7) {
if (isAuthenticationError(e7)) {
logger.log(
`\u{1F3A2} Unable to get membership roles. Make sure you have permissions to read the account. Are you missing the \`User->Memberships->Read\` permission?`
);
return;
} else {
throw e7;
}
}
}
async function getUserInfo(complianceConfig) {
const apiToken = getAPIToken();
if (!apiToken) {
return;
}
const authType = await getAuthType(complianceConfig, apiToken);
const tokenPermissions = await getTokenPermissions();
return {
apiToken: "authKey" in apiToken ? apiToken.authKey : apiToken.apiToken,
authType,
email: "authEmail" in apiToken ? apiToken.authEmail : await getEmail(complianceConfig),
accounts: await getAccounts(complianceConfig),
tokenPermissions
};
}
async function getAuthType(complianceConfig, credentials) {
if ("authKey" in credentials) {
return "Global API Key";
}
const usingEnvAuth = !!getAuthFromEnv();
if (!usingEnvAuth) {
return "OAuth Token";
}
const tokenType = await getTokenType(complianceConfig);
if (tokenType === "account") {
return "Account API Token";
} else {
return "User API Token";
}
}
async function getTokenType(complianceConfig) {
try {
await fetchResult(complianceConfig, "/user/tokens/verify");
return "user";
} catch (e7) {
if (e7.code === 1e3) {
return "account";
}
throw e7;
}
}
async function getEmail(complianceConfig) {
try {
const { email } = await fetchResult(
complianceConfig,
"/user"
);
return email;
} catch (e7) {
const unauthorizedAccess = 9109;
if (e7.code === unauthorizedAccess) {
return void 0;
} else {
throw e7;
}
}
}
async function getAccounts(complianceConfig) {
return await fetchPagedListResult(complianceConfig, "/accounts");
}
async function getTokenPermissions() {
return getScopes();
}
var init_whoami = __esm({
"src/user/whoami.ts"() {
init_import_meta_url();
init_source();
init_cfetch();
init_deploy8();
init_misc_variables();
init_logger();
init_parse();
init_membership();
init_user2();
__name(whoami, "whoami");
__name(printComplianceRegion, "printComplianceRegion");
__name(printUserEmail, "printUserEmail");
__name(printAccountList, "printAccountList");
__name(printTokenPermissions, "printTokenPermissions");
__name(printMembershipInfo, "printMembershipInfo");
__name(getUserInfo, "getUserInfo");
__name(getAuthType, "getAuthType");
__name(getTokenType, "getTokenType");
__name(getEmail, "getEmail");
__name(getAccounts, "getAccounts");
__name(getTokenPermissions, "getTokenPermissions");
}
});
// src/user/commands.ts
var loginCommand, logoutCommand, whoamiCommand;
var init_commands8 = __esm({
"src/user/commands.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_metrics();
init_user();
init_whoami();
loginCommand = createCommand({
metadata: {
description: "\u{1F513} Login to Cloudflare",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false
},
args: {
"scopes-list": {
describe: "List all the available OAuth scopes with descriptions"
},
browser: {
default: true,
type: "boolean",
describe: "Automatically open the OAuth link in a browser"
},
scopes: {
describe: "Pick the set of applicable OAuth scopes when logging in",
array: true,
type: "string",
requiresArg: true
},
"callback-host": {
describe: "Use the ip or host address for the temporary login callback server.",
type: "string",
requiresArg: false,
default: "localhost"
},
"callback-port": {
describe: "Use the port for the temporary login callback server.",
type: "number",
requiresArg: false,
default: 8976
}
},
async handler(args, { config }) {
if (args.scopesList) {
listScopes();
return;
}
if (args.scopes) {
if (args.scopes.length === 0) {
listScopes();
return;
}
if (!validateScopeKeys(args.scopes)) {
throw new CommandLineArgsError(
`One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --scopes-list" to see the valid scopes.`
);
}
await login(config, {
scopes: args.scopes,
browser: args.browser,
callbackHost: args.callbackHost,
callbackPort: args.callbackPort
});
return;
}
await login(config, {
browser: args.browser,
callbackHost: args.callbackHost,
callbackPort: args.callbackPort
});
sendMetricsEvent("login user", {
sendMetrics: config.send_metrics
});
}
});
logoutCommand = createCommand({
metadata: {
description: "\u{1F6AA} Logout from Cloudflare",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false
},
async handler(_4, { config }) {
await logout();
sendMetricsEvent("logout user", {
sendMetrics: config.send_metrics
});
}
});
whoamiCommand = createCommand({
metadata: {
description: "\u{1F575}\uFE0F Retrieve your user information",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false
},
args: {
account: {
type: "string",
describe: "Show membership information for the given account (id or name)."
}
},
async handler(args, { config }) {
await whoami(config, args.account);
sendMetricsEvent("view accounts", {
sendMetrics: config.send_metrics
});
}
});
}
});
// src/utils/logPossibleBugMessage.ts
async function logPossibleBugMessage() {
if (process.versions.bun) {
logger.warn(
`Wrangler does not support the Bun runtime. Please try this command again using Node.js via \`npm\` or \`pnpm\`. Alternatively, make sure you're not passing the \`--bun\` flag when running \`bun run wrangler ...\``
);
return;
}
logger.log(
`${fgGreenColor}%s${resetColor}`,
"If you think this is a bug then please create an issue at https://github.com/cloudflare/workers-sdk/issues/new/choose"
);
const latestVersion = await updateCheck();
if (latestVersion) {
logger.log(
`Note that there is a newer version of Wrangler available (${latestVersion}). Consider checking whether upgrading resolves this error.`
);
}
}
var init_logPossibleBugMessage = __esm({
"src/utils/logPossibleBugMessage.ts"() {
init_import_meta_url();
init_logger();
init_update_check();
init_constants5();
__name(logPossibleBugMessage, "logPossibleBugMessage");
}
});
// src/vectorize/client.ts
async function createIndex(config, body, deprecatedV1) {
const accountId = await requireAuth(config);
const versionParam = deprecatedV1 ? `` : `/v2`;
return await fetchResult(
config,
`/accounts/${accountId}/vectorize${versionParam}/indexes`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify(body)
}
);
}
async function deleteIndex(config, indexName, deprecatedV1) {
const accountId = await requireAuth(config);
const versionParam = deprecatedV1 ? `` : `/v2`;
return await fetchResult(
config,
`/accounts/${accountId}/vectorize${versionParam}/indexes/${indexName}`,
{
method: "DELETE"
}
);
}
async function getIndex(config, indexName, deprecatedV1) {
const accountId = await requireAuth(config);
const versionParam = deprecatedV1 ? `` : `/v2`;
return await fetchResult(
config,
`/accounts/${accountId}/vectorize${versionParam}/indexes/${indexName}`,
{
method: "GET"
}
);
}
async function listIndexes(config, deprecatedV1) {
const accountId = await requireAuth(config);
const versionParam = deprecatedV1 ? `` : `/v2`;
return await fetchListResult(
config,
`/accounts/${accountId}/vectorize${versionParam}/indexes`,
{
method: "GET"
}
);
}
async function insertIntoIndexV1(config, indexName, body) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/indexes/${indexName}/insert`,
{
method: "POST",
body
}
);
}
async function insertIntoIndex(config, indexName, body) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/insert`,
{
method: "POST",
body
}
);
}
async function upsertIntoIndex(config, indexName, body) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/upsert`,
{
method: "POST",
body
}
);
}
async function queryIndexByVector(config, indexName, vector, options) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/query`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify({
...options,
vector: Array.isArray(vector) ? vector : Array.from(vector)
})
}
);
}
async function queryIndexByVectorId(config, indexName, vectorId, options) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/query`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify({
...options,
vectorId
})
}
);
}
async function getByIds(config, indexName, ids) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/get_by_ids`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify(ids)
}
);
}
async function deleteByIds(config, indexName, ids) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/delete_by_ids`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify(ids)
}
);
}
async function indexInfo(config, indexName) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/info`,
{
method: "GET"
}
);
}
async function createMetadataIndex(config, indexName, payload) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/metadata_index/create`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify(payload)
}
);
}
async function listMetadataIndex(config, indexName) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/metadata_index/list`,
{
method: "GET"
}
);
}
async function deleteMetadataIndex(config, indexName, payload) {
const accountId = await requireAuth(config);
return await fetchResult(
config,
`/accounts/${accountId}/vectorize/v2/indexes/${indexName}/metadata_index/delete`,
{
method: "POST",
headers: {
"content-type": jsonContentType
},
body: JSON.stringify(payload)
}
);
}
async function listVectors(config, indexName, options) {
const accountId = await requireAuth(config);
const searchParams = new URLSearchParams();
if (options?.count !== void 0) {
searchParams.set("count", options.count.toString());
}
if (options?.cursor !== void 0) {
searchParams.set("cursor", options.cursor);
}
const queryString = searchParams.toString();
const url4 = `/accounts/${accountId}/vectorize/v2/indexes/${indexName}/list${queryString ? `?${queryString}` : ""}`;
return await fetchResult(config, url4, {
method: "GET"
});
}
var jsonContentType;
var init_client10 = __esm({
"src/vectorize/client.ts"() {
init_import_meta_url();
init_cfetch();
init_user2();
jsonContentType = "application/json; charset=utf-8;";
__name(createIndex, "createIndex");
__name(deleteIndex, "deleteIndex");
__name(getIndex, "getIndex");
__name(listIndexes, "listIndexes");
__name(insertIntoIndexV1, "insertIntoIndexV1");
__name(insertIntoIndex, "insertIntoIndex");
__name(upsertIntoIndex, "upsertIntoIndex");
__name(queryIndexByVector, "queryIndexByVector");
__name(queryIndexByVectorId, "queryIndexByVectorId");
__name(getByIds, "getByIds");
__name(deleteByIds, "deleteByIds");
__name(indexInfo, "indexInfo");
__name(createMetadataIndex, "createMetadataIndex");
__name(listMetadataIndex, "listMetadataIndex");
__name(deleteMetadataIndex, "deleteMetadataIndex");
__name(listVectors, "listVectors");
}
});
// src/vectorize/common.ts
async function isValidFile(path72) {
try {
await (0, import_promises30.access)(path72, import_promises30.constants.R_OK);
const fileStat = await (0, import_promises30.stat)(path72);
return fileStat.isFile() && fileStat.size > 0;
} catch {
return false;
}
}
async function* getBatchFromFile(rl, batchSize = VECTORIZE_MAX_BATCH_SIZE) {
const batch = [];
try {
for await (const line of rl) {
batch.push(line);
if (batch.length >= batchSize) {
yield batch.splice(0, batchSize);
}
}
if (batch.length > 0) {
yield batch;
}
} catch {
logger.error(
`\u{1F6A8} Encountered an error while reading batches from the file.`
);
return;
}
}
var import_promises30, deprecatedV1DefaultFlag, VECTORIZE_V1_MAX_BATCH_SIZE, VECTORIZE_MAX_BATCH_SIZE, VECTORIZE_UPSERT_BATCH_SIZE, VECTORIZE_MAX_UPSERT_VECTOR_RECORDS;
var init_common3 = __esm({
"src/vectorize/common.ts"() {
init_import_meta_url();
import_promises30 = require("fs/promises");
init_logger();
deprecatedV1DefaultFlag = false;
VECTORIZE_V1_MAX_BATCH_SIZE = 1e3;
VECTORIZE_MAX_BATCH_SIZE = 5e3;
VECTORIZE_UPSERT_BATCH_SIZE = VECTORIZE_V1_MAX_BATCH_SIZE;
VECTORIZE_MAX_UPSERT_VECTOR_RECORDS = 1e5;
__name(isValidFile, "isValidFile");
__name(getBatchFromFile, "getBatchFromFile");
}
});
// src/vectorize/create.ts
var vectorizeCreateCommand;
var init_create8 = __esm({
"src/vectorize/create.ts"() {
init_import_meta_url();
init_config2();
init_create_command();
init_errors();
init_logger();
init_getValidBindingName();
init_client10();
init_common3();
vectorizeCreateCommand = createCommand({
metadata: {
description: "Create a Vectorize index",
status: "stable",
owner: "Product: Vectorize"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index to create (must be unique)."
},
dimensions: {
type: "number",
description: "The dimension size to configure this index for, based on the output dimensions of your ML model."
},
metric: {
type: "string",
choices: ["euclidean", "cosine", "dot-product"],
description: "The distance metric to use for searching within the index."
},
preset: {
type: "string",
choices: [
"@cf/baai/bge-small-en-v1.5",
"@cf/baai/bge-base-en-v1.5",
"@cf/baai/bge-large-en-v1.5",
"openai/text-embedding-ada-002",
"cohere/embed-multilingual-v2.0"
],
description: "The name of an preset representing an embeddings model: Vectorize will configure the dimensions and distance metric for you when provided."
},
description: {
type: "string",
description: "An optional description for this index."
},
json: {
type: "boolean",
default: false,
description: "Return output as clean JSON"
},
"deprecated-v1": {
type: "boolean",
deprecated: true,
default: deprecatedV1DefaultFlag,
description: "Create a deprecated Vectorize V1 index. This is not recommended and indexes created with this option need all other Vectorize operations to have this option enabled."
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
let indexConfig;
if (args.preset) {
indexConfig = { preset: args.preset };
logger.log(
`Configuring index based for the embedding model ${args.preset}.`
);
} else if (args.dimensions && args.metric) {
indexConfig = {
metric: args.metric,
dimensions: args.dimensions
};
} else {
throw new UserError(
"\u{1F6A8} You must provide both dimensions and a metric, or a known model preset when creating an index."
);
}
if (args.deprecatedV1) {
logger.warn(
"Creation of legacy Vectorize indexes will be blocked by December 2024"
);
}
const index = {
name: args.name,
description: args.description,
config: indexConfig
};
logger.log(`\u{1F6A7} Creating index: '${args.name}'`);
const indexResult = await createIndex(config, index, args.deprecatedV1);
let bindingName;
if (args.deprecatedV1) {
bindingName = "VECTORIZE_INDEX";
} else {
bindingName = "VECTORIZE";
}
if (args.json) {
logger.log(JSON.stringify(index, null, 2));
return;
}
logger.log(
`\u2705 Successfully created a new Vectorize index: '${indexResult.name}'`
);
await updateConfigFile(
(name2) => ({
vectorize: [
{
binding: getValidBindingName(name2 ?? bindingName, bindingName),
index_name: indexResult.name
}
]
}),
config.configPath,
args.env
);
}
});
}
});
// src/vectorize/createMetadataIndex.ts
var vectorizeCreateMetadataIndexCommand;
var init_createMetadataIndex = __esm({
"src/vectorize/createMetadataIndex.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
vectorizeCreateMetadataIndexCommand = createCommand({
metadata: {
description: "Enable metadata filtering on the specified property",
owner: "Product: Vectorize",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
propertyName: {
type: "string",
demandOption: true,
description: "The name of the metadata property to index."
},
type: {
type: "string",
demandOption: true,
choices: ["string", "number", "boolean"],
description: "The type of metadata property to index. Valid types are 'string', 'number' and 'boolean'."
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const reqOptions = {
propertyName: args.propertyName,
indexType: args.type
};
logger.log(`\u{1F4CB} Creating metadata index...`);
const mutation = await createMetadataIndex(config, args.name, reqOptions);
logger.log(
`\u2705 Successfully enqueued metadata index creation request. Mutation changeset identifier: ${mutation.mutationId}.`
);
}
});
}
});
// src/vectorize/delete.ts
var vectorizeDeleteCommand;
var init_delete8 = __esm({
"src/vectorize/delete.ts"() {
init_import_meta_url();
init_create_command();
init_dialogs();
init_logger();
init_client10();
init_common3();
vectorizeDeleteCommand = createCommand({
metadata: {
description: "Delete a Vectorize index",
status: "stable",
owner: "Product: Vectorize"
},
behaviour: {
printBanner: true,
provideConfig: true
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index"
},
force: {
type: "boolean",
alias: "y",
default: false,
description: "Skip confirmation"
},
"deprecated-v1": {
type: "boolean",
default: deprecatedV1DefaultFlag,
description: "Delete a deprecated Vectorize V1 index."
}
},
positionalArgs: ["name"],
async handler({ name: name2, force, deprecatedV1 }, { config }) {
logger.log(`Deleting Vectorize index ${name2}`);
if (!force) {
const confirmedDeletion = await confirm(
`OK to delete the index '${name2}'?`
);
if (!confirmedDeletion) {
logger.log("Deletion cancelled.");
return;
}
}
await deleteIndex(config, name2, deprecatedV1);
logger.log(`\u2705 Deleted index ${name2}`);
}
});
}
});
// src/vectorize/deleteByIds.ts
var vectorizeDeleteVectorsCommand;
var init_deleteByIds = __esm({
"src/vectorize/deleteByIds.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client10();
vectorizeDeleteVectorsCommand = createCommand({
metadata: {
description: "Delete vectors in a Vectorize index",
owner: "Product: Vectorize",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
ids: {
type: "string",
array: true,
demandOption: true,
describe: "Vector identifiers to be deleted from the Vectorize Index. Example: `--ids a 'b' 1 '2'`"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
if (args.ids.length === 0) {
throw new UserError(
"\u{1F6A8} Please provide valid vector identifiers for deletion."
);
}
logger.log(`\u{1F4CB} Deleting vectors...`);
const ids = {
ids: args.ids
};
const mutation = await deleteByIds(config, args.name, ids);
logger.log(
`\u2705 Successfully enqueued ${args.ids.length} vectors into index '${args.name}' for deletion. Mutation changeset identifier: ${mutation.mutationId}.`
);
}
});
}
});
// src/vectorize/deleteMetadataIndex.ts
var vectorizeDeleteMetadataIndexCommand;
var init_deleteMetadataIndex = __esm({
"src/vectorize/deleteMetadataIndex.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
vectorizeDeleteMetadataIndexCommand = createCommand({
metadata: {
description: "Delete metadata indexes",
owner: "Product: Vectorize",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
propertyName: {
type: "string",
demandOption: true,
description: "The name of the metadata property to index."
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const reqOptions = {
propertyName: args.propertyName
};
logger.log(`\u{1F4CB} Deleting metadata index...`);
const mutation = await deleteMetadataIndex(config, args.name, reqOptions);
logger.log(
`\u2705 Successfully enqueued metadata index deletion request. Mutation changeset identifier: ${mutation.mutationId}.`
);
}
});
}
});
// src/vectorize/get.ts
var vectorizeGetCommand;
var init_get4 = __esm({
"src/vectorize/get.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
init_common3();
vectorizeGetCommand = createCommand({
metadata: {
description: "Get a Vectorize index by name",
status: "stable",
owner: "Product: Vectorize"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
json: {
type: "boolean",
default: false,
description: "Return output as clean JSON"
},
"deprecated-v1": {
type: "boolean",
default: deprecatedV1DefaultFlag,
description: "Fetch a deprecated V1 Vectorize index. This must be enabled if the index was created with V1 option."
}
},
positionalArgs: ["name"],
async handler({ name: name2, json, deprecatedV1 }, { config }) {
const index = await getIndex(config, name2, deprecatedV1);
if (json) {
logger.log(JSON.stringify(index, null, 2));
return;
}
logger.table([
{
name: index.name,
dimensions: index.config?.dimensions.toString(),
metric: index.config?.metric,
description: index.description || "",
created: index.created_on,
modified: index.modified_on
}
]);
}
});
}
});
// src/vectorize/getByIds.ts
var vectorizeGetVectorsCommand;
var init_getByIds = __esm({
"src/vectorize/getByIds.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client10();
vectorizeGetVectorsCommand = createCommand({
metadata: {
description: "Get vectors from a Vectorize index",
owner: "Product: Vectorize",
status: "stable"
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
ids: {
type: "string",
array: true,
demandOption: true,
describe: "Vector identifiers to be fetched from the Vectorize Index. Example: `--ids a 'b' 1 '2'`"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
if (args.ids.length === 0) {
throw new UserError("\u{1F6A8} Please provide valid vector identifiers.");
}
logger.log(`\u{1F4CB} Fetching vectors...`);
const ids = {
ids: args.ids
};
const vectors = await getByIds(config, args.name, ids);
if (vectors.length === 0) {
logger.warn(
`The index does not contain vectors corresponding to the provided identifiers`
);
return;
}
logger.log(JSON.stringify(vectors, null, 2));
}
});
}
});
// src/vectorize/index.ts
var vectorizeNamespace;
var init_vectorize = __esm({
"src/vectorize/index.ts"() {
init_import_meta_url();
init_create_command();
vectorizeNamespace = createNamespace({
metadata: {
description: "\u{1F9EE} Manage Vectorize indexes",
status: "stable",
owner: "Product: Vectorize"
}
});
}
});
// src/vectorize/info.ts
var vectorizeInfoCommand;
var init_info4 = __esm({
"src/vectorize/info.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
vectorizeInfoCommand = createCommand({
metadata: {
description: "Get additional details about the index",
owner: "Product: Vectorize",
status: "stable"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
json: {
describe: "return output as clean JSON",
type: "boolean",
default: false
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
logger.log(`\u{1F4CB} Fetching index info...`);
const info = await indexInfo(config, args.name);
if (args.json) {
logger.log(JSON.stringify(info, null, 2));
return;
}
logger.table([
{
dimensions: info.dimensions.toString(),
vectorCount: info.vectorCount.toString(),
processedUpToMutation: info.processedUpToMutation,
processedUpToDatetime: info.processedUpToDatetime
}
]);
}
});
}
});
// src/vectorize/insert.ts
var import_node_fs30, import_node_readline3, import_undici17, vectorizeInsertCommand;
var init_insert = __esm({
"src/vectorize/insert.ts"() {
init_import_meta_url();
import_node_fs30 = require("fs");
import_node_readline3 = require("readline");
import_undici17 = __toESM(require_undici());
init_create_command();
init_errors();
init_logger();
init_client10();
init_common3();
vectorizeInsertCommand = createCommand({
metadata: {
description: "Insert vectors into a Vectorize index",
owner: "Product: Vectorize",
status: "stable"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
file: {
describe: "A file containing line separated json (ndjson) vector objects.",
demandOption: true,
type: "string"
},
"batch-size": {
describe: "Number of vector records to include when sending to the Cloudflare API.",
type: "number",
default: VECTORIZE_UPSERT_BATCH_SIZE
},
json: {
describe: "return output as clean JSON",
type: "boolean",
default: false
},
"deprecated-v1": {
type: "boolean",
default: deprecatedV1DefaultFlag,
describe: "Insert into a deprecated V1 Vectorize index. This must be enabled if the index was created with the V1 option."
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
if (!await isValidFile(args.file)) {
throw new UserError(
`\u{1F6A8} Cannot read invalid or empty file: ${args.file}.`
);
}
const rl = (0, import_node_readline3.createInterface)({ input: (0, import_node_fs30.createReadStream)(args.file) });
if (args.deprecatedV1 && Number(args.batchSize) > VECTORIZE_V1_MAX_BATCH_SIZE) {
throw new UserError(
`\u{1F6A8} Vectorize currently limits upload batches to ${VECTORIZE_V1_MAX_BATCH_SIZE} records at a time.`
);
} else if (!args.deprecatedV1 && Number(args.batchSize) > VECTORIZE_MAX_BATCH_SIZE) {
throw new UserError(
`\u{1F6A8} The global rate limit for the Cloudflare API is 1200 requests per five minutes. Vectorize V2 indexes currently limit upload batches to ${VECTORIZE_MAX_BATCH_SIZE} records at a time to stay within the service limits.`
);
}
let vectorInsertCount = 0;
for await (const batch of getBatchFromFile(rl, args.batchSize)) {
const formData = new import_undici17.FormData();
formData.append(
"vectors",
new File([batch.join(`
`)], "vectors.ndjson", {
type: "application/x-ndjson"
})
);
if (args.deprecatedV1) {
logger.log(`\u2728 Uploading vector batch (${batch.length} vectors)`);
const idxPart = await insertIntoIndexV1(config, args.name, formData);
vectorInsertCount += idxPart.count;
} else {
const mutation = await insertIntoIndex(config, args.name, formData);
vectorInsertCount += batch.length;
logger.log(
`\u2728 Enqueued ${batch.length} vectors into index '${args.name}' for insertion. Mutation changeset identifier: ${mutation.mutationId}`
);
}
if (vectorInsertCount > VECTORIZE_MAX_UPSERT_VECTOR_RECORDS) {
logger.warn(
`\u{1F6A7} While Vectorize is in beta, we've limited uploads to 100k vectors per run. You may run this again with another batch to upload further`
);
break;
}
}
if (args.json) {
logger.log(
JSON.stringify({ index: args.name, count: vectorInsertCount }, null, 2)
);
return;
}
if (args.deprecatedV1) {
logger.log(
`\u2705 Successfully inserted ${vectorInsertCount} vectors into index '${args.name}'`
);
} else {
logger.log(
`\u2705 Successfully enqueued ${vectorInsertCount} vectors into index '${args.name}' for insertion.`
);
}
}
});
}
});
// src/vectorize/list.ts
var vectorizeListCommand;
var init_list8 = __esm({
"src/vectorize/list.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
init_common3();
vectorizeListCommand = createCommand({
metadata: {
description: "List your Vectorize indexes",
status: "stable",
owner: "Product: Vectorize"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
json: {
type: "boolean",
default: false,
description: "Return output as clean JSON"
},
"deprecated-v1": {
type: "boolean",
default: deprecatedV1DefaultFlag,
description: "List deprecated Vectorize V1 indexes for your account."
}
},
async handler(args, { config }) {
logger.log(`\u{1F4CB} Listing Vectorize indexes...`);
const indexes = await listIndexes(config, args.deprecatedV1);
if (indexes.length === 0) {
logger.warn(`
You haven't created any indexes on this account.
Use 'wrangler vectorize create <name>' to create one, or visit
https://developers.cloudflare.com/vectorize/ to get started.
`);
return;
}
if (args.json) {
logger.log(JSON.stringify(indexes, null, 2));
return;
}
logger.table(
indexes.map((index) => ({
name: index.name,
dimensions: index.config?.dimensions.toString(),
metric: index.config?.metric,
description: index.description ?? "",
created: index.created_on,
modified: index.modified_on
}))
);
}
});
}
});
// src/vectorize/listMetadataIndex.ts
var vectorizeListMetadataIndexCommand;
var init_listMetadataIndex = __esm({
"src/vectorize/listMetadataIndex.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
vectorizeListMetadataIndexCommand = createCommand({
metadata: {
description: "List metadata properties on which metadata filtering is enabled",
owner: "Product: Vectorize",
status: "stable"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
json: {
describe: "return output as clean JSON",
type: "boolean",
default: false
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
logger.log(`\u{1F4CB} Fetching metadata indexes...`);
const res = await listMetadataIndex(config, args.name);
if (res.metadataIndexes.length === 0) {
logger.warn(`
You haven't created any metadata indexes on this account.
Use 'wrangler vectorize create-metadata-index <name>' to create one, or visit
https://developers.cloudflare.com/vectorize/ to get started.
`);
return;
}
if (args.json) {
logger.log(JSON.stringify(res.metadataIndexes, null, 2));
return;
}
logger.table(
res.metadataIndexes.map((index) => ({
propertyName: index.propertyName,
type: index.indexType
}))
);
}
});
}
});
// src/vectorize/listVectors.ts
var vectorizeListVectorsCommand;
var init_listVectors = __esm({
"src/vectorize/listVectors.ts"() {
init_import_meta_url();
init_create_command();
init_logger();
init_client10();
vectorizeListVectorsCommand = createCommand({
metadata: {
description: "List vector identifiers in a Vectorize index",
status: "stable",
owner: "Product: Vectorize",
examples: [
{
command: "wrangler vectorize list-vectors my-index",
description: "List vector identifiers in the index 'my-index'"
},
{
command: "wrangler vectorize list-vectors my-index --count 50",
description: "List up to 50 vector identifiers"
},
{
command: "wrangler vectorize list-vectors my-index --cursor abc123",
description: "Continue listing from a specific cursor position"
}
]
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index"
},
count: {
type: "number",
description: "Maximum number of vectors to return (1-1000)"
},
cursor: {
type: "string",
description: "Cursor for pagination to get the next page of results"
},
json: {
type: "boolean",
default: false,
description: "Return output as clean JSON"
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
logger.log(`\u{1F4CB} Listing vectors in index '${args.name}'...`);
const options = {};
if (args.count !== void 0) {
options.count = args.count;
}
if (args.cursor) {
options.cursor = args.cursor;
}
const result = await listVectors(config, args.name, options);
if (result.vectors.length === 0) {
logger.warn("No vectors found in this index.");
return;
}
if (args.json) {
logger.log(JSON.stringify(result, null, 2));
return;
}
logger.table(
result.vectors.map((vector, index) => ({
"#": (index + 1).toString(),
"Vector ID": vector.id
}))
);
logger.log(
`
Showing ${result.count} of ${result.totalCount} total vectors`
);
if (result.isTruncated && result.nextCursor) {
logger.log(`
\u{1F4A1} To get the next page, run:`);
logger.log(
` wrangler vectorize list-vectors ${args.name} --cursor ${result.nextCursor}`
);
}
}
});
}
});
// src/vectorize/query.ts
function validateQueryFilterInnerValue(innerValue) {
return ["string", "number", "boolean"].includes(typeof innerValue);
}
function validateQueryFilter(input) {
try {
const parsedObj = input;
if (typeof parsedObj !== "object" || parsedObj === null || Array.isArray(parsedObj)) {
return null;
}
const result = {};
for (const field in parsedObj) {
if (Object.prototype.hasOwnProperty.call(parsedObj, field)) {
const value = parsedObj[field];
if (Array.isArray(value)) {
continue;
}
if (typeof value === "object" && value !== null) {
const innerObj = {};
let validInnerObj = true;
for (const op in value) {
if (Object.prototype.hasOwnProperty.call(value, op)) {
const innerValue = value[op];
if (["$eq", "$ne", "$lt", "$lte", "$gt", "gte"].includes(op)) {
if (!validateQueryFilterInnerValue(innerValue)) {
validInnerObj = false;
}
} else if (["$in", "$nin"].includes(op)) {
if (!Array.isArray(innerValue)) {
validInnerObj = false;
} else {
if (!innerValue.every(validateQueryFilterInnerValue)) {
validInnerObj = false;
}
}
} else {
validInnerObj = false;
}
innerObj[op] = innerValue;
}
}
if (validInnerObj && Object.keys(innerObj).length > 0) {
result[field] = innerObj;
} else if (validInnerObj) {
}
} else {
result[field] = value;
}
}
}
if (Object.keys(result).length > 0) {
return result;
} else {
return null;
}
} catch {
return null;
}
}
var vectorizeQueryCommand;
var init_query = __esm({
"src/vectorize/query.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
init_logger();
init_client10();
vectorizeQueryCommand = createCommand({
metadata: {
description: "Query a Vectorize index",
status: "stable",
owner: "Product: Vectorize",
examples: [
{
command: `wrangler vectorize query --vector 1 2 3 0.5 1.25 6`,
description: "Query the Vectorize Index by vector"
},
{
command: `wrangler vectorize query --vector $(jq -r '.[]' data.json | xargs)`,
description: "Query the Vectorize Index by vector from a json file that contains data in the format [1, 2, 3]."
},
{
command: "wrangler vectorize query --filter '{ 'p1': 'abc', 'p2': { '$ne': true }, 'p3': 10, 'p4': false, 'nested.p5': 'abcd' }'",
description: "Filter the query results."
}
]
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index"
},
vector: {
type: "number",
array: true,
description: "Vector to query the Vectorize Index",
coerce: /* @__PURE__ */ __name((arg) => arg.filter(
(value) => typeof value === "number" && !isNaN(value)
), "coerce")
},
"vector-id": {
type: "string",
description: "Identifier for a vector in the index against which the index should be queried"
},
"top-k": {
type: "number",
default: 5,
description: "The number of results (nearest neighbors) to return"
},
"return-values": {
type: "boolean",
default: false,
description: "Specify if the vector values should be included in the results"
},
"return-metadata": {
type: "string",
choices: ["all", "indexed", "none"],
default: "none",
description: "Specify if the vector metadata should be included in the results"
},
namespace: {
type: "string",
description: "Filter the query results based on this namespace"
},
filter: {
type: "string",
description: "Filter the query results based on this metadata filter.",
coerce: /* @__PURE__ */ __name((jsonStr) => {
try {
return JSON.parse(jsonStr);
} catch {
logger.warn(
"\u{1F6A8} Invalid query filter. Please use the recommended format."
);
}
}, "coerce")
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const queryOptions = {
topK: args.topK,
returnValues: args.returnValues,
returnMetadata: args.returnMetadata
};
if (args.namespace) {
queryOptions.namespace = args.namespace;
}
if (args.filter) {
const parsedFilter = validateQueryFilter(args.filter);
if (!parsedFilter) {
logger.warn(
"\u{1F6A8} Could not parse the provided query filter. Please use the recommended format."
);
} else {
queryOptions.filter = parsedFilter;
}
}
if (args.vector === void 0 && args.vectorId === void 0 || args.vector !== void 0 && args.vectorId !== void 0) {
throw new UserError(
"\u{1F6A8} Either vector or vector-id parameter must be provided, but not both."
);
}
logger.log(`\u{1F4CB} Searching for relevant vectors...`);
let res;
if (args.vector !== void 0) {
res = await queryIndexByVector(
config,
args.name,
args.vector,
queryOptions
);
} else if (args.vectorId !== void 0) {
res = await queryIndexByVectorId(
config,
args.name,
args.vectorId,
queryOptions
);
}
if (res === void 0 || res.count === 0) {
logger.warn(`Could not find any relevant vectors`);
return;
}
logger.log(JSON.stringify(res, null, 2));
}
});
__name(validateQueryFilterInnerValue, "validateQueryFilterInnerValue");
__name(validateQueryFilter, "validateQueryFilter");
}
});
// src/vectorize/upsert.ts
var import_node_fs31, import_node_readline4, import_undici18, vectorizeUpsertCommand;
var init_upsert = __esm({
"src/vectorize/upsert.ts"() {
init_import_meta_url();
import_node_fs31 = require("fs");
import_node_readline4 = require("readline");
import_undici18 = __toESM(require_undici());
init_create_command();
init_errors();
init_logger();
init_client10();
init_common3();
vectorizeUpsertCommand = createCommand({
metadata: {
description: "Upsert vectors into a Vectorize index",
status: "stable",
owner: "Product: Vectorize"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
type: "string",
demandOption: true,
description: "The name of the Vectorize index."
},
file: {
describe: "A file containing line separated json (ndjson) vector objects.",
demandOption: true,
type: "string"
},
"batch-size": {
describe: "Number of vector records to include in a single upsert batch when sending to the Cloudflare API.",
type: "number",
default: VECTORIZE_MAX_BATCH_SIZE
},
json: {
describe: "return output as clean JSON",
type: "boolean",
default: false
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
if (!await isValidFile(args.file)) {
throw new UserError(
`\u{1F6A8} Cannot read invalid or empty file: ${args.file}.`
);
}
const rl = (0, import_node_readline4.createInterface)({ input: (0, import_node_fs31.createReadStream)(args.file) });
if (Number(args.batchSize) > VECTORIZE_MAX_BATCH_SIZE) {
throw new UserError(
`\u{1F6A8} The global rate limit for the Cloudflare API is 1200 requests per five minutes. Vectorize indexes currently limit upload batches to ${VECTORIZE_MAX_BATCH_SIZE} records at a time to stay within the service limits.`
);
}
let vectorUpsertCount = 0;
for await (const batch of getBatchFromFile(rl, args.batchSize)) {
const formData = new import_undici18.FormData();
formData.append(
"vectors",
new File([batch.join(`
`)], "vectors.ndjson", {
type: "application/x-ndjson"
})
);
{
const mutation = await upsertIntoIndex(config, args.name, formData);
vectorUpsertCount += batch.length;
logger.log(
`\u2728 Enqueued ${batch.length} vectors into index '${args.name}' for upsertion. Mutation changeset identifier: ${mutation.mutationId}`
);
}
if (vectorUpsertCount > VECTORIZE_MAX_UPSERT_VECTOR_RECORDS) {
logger.warn(
`\u{1F6A7} While Vectorize is in beta, we've limited uploads to 100k vectors per run. You may run this again with another batch to upload further`
);
break;
}
}
if (args.json) {
logger.log(
JSON.stringify({ index: args.name, count: vectorUpsertCount }, null, 2)
);
return;
}
{
logger.log(
`\u2705 Successfully enqueued ${vectorUpsertCount} vectors into index '${args.name}' for upsertion.`
);
}
}
});
}
});
// src/versions/index.ts
var versionsNamespace;
var init_versions = __esm({
"src/versions/index.ts"() {
init_import_meta_url();
init_create_command();
versionsNamespace = createNamespace({
metadata: {
description: "\u{1FAE7} List, view, upload and deploy Versions of your Worker to Cloudflare",
status: "stable",
owner: "Workers: Authoring and Testing"
}
});
}
});
// src/versions/deploy.ts
async function confirmLatestDeploymentOverwrite(config, accountId, scriptName) {
try {
const latest = await fetchLatestDeployment(config, accountId, scriptName);
if (latest && latest.versions.length >= 2) {
const versionCache = /* @__PURE__ */ new Map();
warn(
`Your last deployment has multiple versions. To progress that deployment use "wrangler versions deploy" instead.`,
{ shape: shapes.corners.tl, newlineBefore: false }
);
newline();
await printDeployment(
config,
accountId,
scriptName,
latest,
"last",
versionCache
);
return inputPrompt({
type: "confirm",
question: `"wrangler deploy" will upload a new version and deploy it globally immediately.
Are you sure you want to continue?`,
label: "",
defaultValue: isNonInteractiveOrCI(),
// defaults to true in CI for back-compat
acceptDefault: isNonInteractiveOrCI()
});
}
} catch (e7) {
const isNotFound = e7 instanceof APIError && e7.code == 10007;
if (!isNotFound) {
throw e7;
}
}
return true;
}
async function printLatestDeployment(config, accountId, workerName, versionCache) {
const latestDeployment = await spinnerWhile({
startMessage: "Fetching latest deployment",
async promise() {
return fetchLatestDeployment(config, accountId, workerName);
}
});
await printDeployment(
config,
accountId,
workerName,
latestDeployment,
"current",
versionCache
);
}
async function printDeployment(config, accountId, workerName, deployment, adjective, versionCache) {
const [versions2, traffic] = await fetchDeploymentVersions(
config,
accountId,
workerName,
deployment,
versionCache
);
logRaw(
`${leftT} Your ${adjective} deployment has ${versions2.length} version(s):`
);
printVersions(versions2, traffic);
}
function printVersions(versions2, traffic) {
newline();
log(formatVersions(versions2, traffic));
newline();
}
function formatVersions(versions2, traffic) {
return versions2.map((version5) => {
const trafficString = brandColor(`(${traffic.get(version5.id)}%)`);
const versionIdString = white(version5.id);
return gray(`${trafficString} ${versionIdString}
Created: ${version5.metadata.created_on}
Tag: ${version5.annotations?.["workers/tag"] ?? BLANK_INPUT}
Message: ${version5.annotations?.["workers/message"] ?? BLANK_INPUT}`);
}).join("\n\n");
}
async function promptVersionsToDeploy(complianceConfig, accountId, workerName, defaultSelectedVersionIds, versionCache, yesFlag) {
await spinnerWhile({
startMessage: "Fetching deployable versions",
async promise() {
await fetchDeployableVersions(
complianceConfig,
accountId,
workerName,
versionCache
);
await fetchVersions(
complianceConfig,
accountId,
workerName,
versionCache,
...defaultSelectedVersionIds
);
}
});
const selectableVersions = Array.from(versionCache.values()).sort(
(a5, b6) => b6.metadata.created_on.localeCompare(a5.metadata.created_on)
// String#localeCompare should work because they are ISO strings
);
const question = "Which version(s) do you want to deploy?";
const result = await inputPrompt({
type: "multiselect",
question,
options: selectableVersions.map((version5) => ({
value: version5.id,
label: version5.id,
sublabel: gray(`
${ZERO_WIDTH_SPACE} Created: ${version5.metadata.created_on}
${ZERO_WIDTH_SPACE} Tag: ${version5.annotations?.["workers/tag"] ?? BLANK_INPUT}
${ZERO_WIDTH_SPACE} Message: ${version5.annotations?.["workers/message"] ?? BLANK_INPUT}
`)
})),
label: "",
helpText: "Use SPACE to select/unselect version(s) and ENTER to submit.",
defaultValue: defaultSelectedVersionIds,
acceptDefault: yesFlag,
validate(versionIds) {
if (versionIds === void 0) {
return `You must select at least 1 version to deploy.`;
}
},
renderers: {
submit({ value: versionIds }) {
(0, import_assert5.default)(Array.isArray(versionIds));
const label = brandColor(
`${versionIds.length} Worker Version(s) selected`
);
const versions2 = versionIds?.map((versionId, i5) => {
const version5 = versionCache.get(versionId);
(0, import_assert5.default)(version5);
return `${grayBar}
${leftT} ${white(` Worker Version ${i5 + 1}: `, version5.id)}
${grayBar} ${gray(" Created: ", version5.metadata.created_on)}
${grayBar} ${gray(
" Tag: ",
version5.annotations?.["workers/tag"] ?? BLANK_INPUT
)}
${grayBar} ${gray(
" Message: ",
version5.annotations?.["workers/message"] ?? BLANK_INPUT
)}`;
});
return [
`${leftT} ${question}`,
`${leftT} ${label}`,
...versions2,
grayBar
];
}
}
});
return result;
}
async function promptPercentages(versionIds, optionalVersionTraffic, yesFlag, confirmedVersionTraffic = /* @__PURE__ */ new Map()) {
let n6 = 0;
for (const versionId of versionIds) {
n6++;
const defaultVersionTraffic = assignAndDistributePercentages(
versionIds,
new Map([...optionalVersionTraffic, ...confirmedVersionTraffic])
);
const defaultValue = defaultVersionTraffic.get(versionId)?.toFixed(3).replace(/\.?0+$/, "");
const question = `What percentage of traffic should Worker Version ${n6} receive?`;
const answer = await inputPrompt({
type: "text",
question,
helpText: "(0-100)",
label: `Traffic`,
defaultValue,
initialValue: confirmedVersionTraffic.get(versionId)?.toString(),
// if the user already entered a value, override the default
acceptDefault: yesFlag,
format: /* @__PURE__ */ __name((val2) => `${val2}%`, "format"),
validate: /* @__PURE__ */ __name((val2) => {
const input = val2 !== "" ? val2 : defaultValue;
const percentage2 = parseFloat(input?.toString() ?? "");
if (isNaN(percentage2) || percentage2 < 0 || percentage2 > 100) {
return "Please enter a number between 0 and 100.";
}
}, "validate"),
renderers: {
submit({ value }) {
const percentage2 = parseFloat(value?.toString() ?? "");
return [
leftT + space() + white(question),
leftT + space() + brandColor(`${percentage2}%`) + gray(" of traffic"),
leftT
];
}
}
});
const percentage = parseFloat(answer);
confirmedVersionTraffic.set(versionId, percentage);
}
try {
const { subtotal } = summariseVersionTraffic(
confirmedVersionTraffic,
versionIds
);
validateTrafficSubtotal(subtotal);
} catch (err) {
if (err instanceof UserError) {
if (yesFlag) {
throw err;
}
error(err.message, void 0, leftT);
return promptPercentages(
versionIds,
optionalVersionTraffic,
yesFlag,
confirmedVersionTraffic
);
}
throw err;
}
return confirmedVersionTraffic;
}
async function maybePatchSettings(config, accountId, workerName) {
const maybeUndefinedSettings = {
logpush: config.logpush,
tail_consumers: config.tail_consumers,
observability: config.observability
// TODO reconcile with how regular deploy handles empty state
};
const definedSettings = Object.fromEntries(
Object.entries(maybeUndefinedSettings).filter(
([, value]) => value !== void 0
)
);
const hasZeroSettingsToSync = Object.keys(definedSettings).length === 0;
if (hasZeroSettingsToSync) {
log("No non-versioned settings to sync. Skipping...");
return;
}
const patchedSettings = await spinnerWhile({
startMessage: `Syncing non-versioned settings`,
async promise() {
return await patchNonVersionedScriptSettings(
config,
accountId,
workerName,
definedSettings
);
}
});
const observability = {};
if (patchedSettings.observability) {
observability["enabled"] = String(patchedSettings.observability.enabled);
if (patchedSettings.observability.head_sampling_rate) {
observability["head_sampling_rate"] = String(
patchedSettings.observability.head_sampling_rate
);
}
}
const formattedSettings = formatLabelledValues(
{
logpush: String(patchedSettings.logpush ?? "<skipped>"),
observability: Object.keys(observability).length > 0 ? formatLabelledValues(observability) : "<skipped>",
tail_consumers: patchedSettings.tail_consumers?.map(
(tc) => tc.environment ? `${tc.service} (${tc.environment})` : tc.service
).join("\n") ?? "<skipped>"
},
{
labelJustification: "right",
indentationCount: 4
}
);
log("Synced non-versioned settings:\n" + formattedSettings);
}
function parseVersionSpecs(args) {
const versionIds = [];
const percentages = [];
for (const spec of args.versionSpecs ?? []) {
const [versionId, percentageString] = spec.split("@");
const percentage = percentageString === void 0 || percentageString === "" ? null : parseFloat(percentageString);
if (percentage !== null) {
if (isNaN(percentage)) {
throw new UserError(
`Could not parse percentage value from version-spec positional arg "${spec}"`
);
}
if (percentage < 0 || percentage > 100) {
throw new UserError(
`Percentage value (${percentage}%) parsed from version-spec positional arg "${spec}" must be between 0 and 100.`
);
}
}
versionIds.push(versionId);
percentages.push(percentage);
}
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
for (const versionId of args.versionId ?? []) {
if (!UUID_REGEX.test(versionId)) {
throw new UserError(`Version ID must be a valid UUID (${versionId}).`);
}
versionIds.push(versionId);
}
for (const percentage of args.percentage ?? []) {
if (percentage < 0 || percentage > 100) {
throw new UserError(
`Percentage value (${percentage}%) must be between 0 and 100.`
);
}
percentages.push(percentage);
}
const optionalVersionTraffic = new Map(
versionIds.map((_4, i5) => [versionIds[i5], percentages[i5] ?? null])
);
return optionalVersionTraffic;
}
function assignAndDistributePercentages(versionIds, optionalVersionTraffic) {
const { subtotal, unspecifiedCount } = summariseVersionTraffic(
optionalVersionTraffic,
versionIds
);
const unspecifiedPercentageReplacement = unspecifiedCount === 0 || subtotal > 100 ? 0 : (100 - subtotal) / unspecifiedCount;
const versionTraffic = new Map(
versionIds.map((versionId) => [
versionId,
optionalVersionTraffic.get(versionId) ?? unspecifiedPercentageReplacement
])
);
return versionTraffic;
}
function summariseVersionTraffic(optionalVersionTraffic, versionIds = Array.from(optionalVersionTraffic.keys())) {
const versionsWithoutPercentage = versionIds.filter(
(versionId) => optionalVersionTraffic.get(versionId) == null
);
const percentages = versionIds.map(
(versionId) => optionalVersionTraffic.get(versionId) ?? null
);
const percentagesSubtotal = percentages.reduce(
(sum, x6) => sum + (x6 ?? 0),
0
);
return {
subtotal: percentagesSubtotal,
unspecifiedCount: versionsWithoutPercentage.length
};
}
function validateTrafficSubtotal(subtotal, { max = 100, min = 100, epsilon = EPSILON } = {}) {
const isAbove = subtotal > max + epsilon;
const isBelow = subtotal < min - epsilon;
if (max === min && (isAbove || isBelow)) {
throw new UserError(
`Sum of specified percentages (${subtotal}%) must be ${max}%`
);
}
if (isAbove) {
throw new UserError(
`Sum of specified percentages (${subtotal}%) must be at most ${max}%`
);
}
if (isBelow) {
throw new UserError(
`Sum of specified percentages (${subtotal}%) must be at least ${min}%`
);
}
}
var import_assert5, EPSILON, BLANK_INPUT, ZERO_WIDTH_SPACE, versionsDeployCommand;
var init_deploy7 = __esm({
"src/versions/deploy.ts"() {
init_import_meta_url();
import_assert5 = __toESM(require("assert"));
init_cli();
init_colors();
init_interactive();
init_cfetch();
init_create_command();
init_errors();
init_is_interactive();
init_metrics();
init_output();
init_parse();
init_user2();
init_render_labelled_values();
init_api();
EPSILON = 1e-3;
BLANK_INPUT = "-";
ZERO_WIDTH_SPACE = "\u200B";
versionsDeployCommand = createCommand({
metadata: {
description: "Safely roll out new Versions of your Worker by splitting traffic between multiple Versions",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
useConfigRedirectIfAvailable: true,
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
name: {
describe: "Name of the worker",
type: "string",
requiresArg: true
},
"version-id": {
describe: "Worker Version ID(s) to deploy",
type: "string",
array: true,
requiresArg: true
},
percentage: {
describe: "Percentage of traffic to split between Worker Version(s) (0-100)",
array: true,
type: "number",
requiresArg: true
},
"version-specs": {
describe: "Shorthand notation to deploy Worker Version(s) [<version-id>@<percentage>..]",
type: "string",
array: true
},
message: {
describe: "Description of this deployment (optional)",
type: "string",
requiresArg: true
},
yes: {
alias: "y",
describe: "Automatically accept defaults to prompts",
type: "boolean",
default: false
},
"dry-run": {
describe: "Don't actually deploy",
type: "boolean",
default: false
},
"max-versions": {
hidden: true,
// experimental, not supported long-term
describe: "Maximum allowed versions to select",
type: "number",
default: 2
// (when server-side limitation is lifted, we can update this default or just remove the option entirely)
}
},
positionalArgs: ["version-specs"],
handler: /* @__PURE__ */ __name(async function versionsDeployHandler(args, { config }) {
sendMetricsEvent(
"deploy worker versions",
{},
{
sendMetrics: config.send_metrics
}
);
const accountId = await requireAuth(config);
const workerName = args.name ?? config.name;
if (workerName === void 0) {
throw new UserError(
'You need to provide a name of your worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const versionCache = /* @__PURE__ */ new Map();
const optionalVersionTraffic = parseVersionSpecs(args);
startSection(
"Deploy Worker Versions",
"by splitting traffic between multiple versions",
true
);
await printLatestDeployment(config, accountId, workerName, versionCache);
const confirmedVersionsToDeploy = await promptVersionsToDeploy(
config,
accountId,
workerName,
[...optionalVersionTraffic.keys()],
versionCache,
args.yes
);
if (confirmedVersionsToDeploy.length === 0) {
throw new UserError("You must select at least 1 version to deploy.", {
telemetryMessage: true
});
}
if (confirmedVersionsToDeploy.length > args.maxVersions) {
throw new UserError(
`You must select at most ${args.maxVersions} versions to deploy.`,
{ telemetryMessage: "You must select at most 2 versions to deploy.`" }
);
}
const confirmedVersionTraffic = await promptPercentages(
confirmedVersionsToDeploy,
optionalVersionTraffic,
args.yes
);
const message = await inputPrompt({
type: "text",
label: "Deployment message",
defaultValue: args.message,
acceptDefault: args.yes,
question: "Add a deployment message",
helpText: "(optional)"
});
if (args.dryRun) {
cancel("--dry-run: exiting");
return;
}
const start = Date.now();
const { id: deploymentId } = await spinnerWhile({
startMessage: `Deploying ${confirmedVersionsToDeploy.length} version(s)`,
promise() {
return createDeployment(
config,
accountId,
workerName,
confirmedVersionTraffic,
message
);
}
});
await maybePatchSettings(config, accountId, workerName);
const elapsedMilliseconds = Date.now() - start;
const elapsedSeconds = elapsedMilliseconds / 1e3;
const elapsedString = `${elapsedSeconds.toFixed(2)} sec`;
const trafficSummaryList = Array.from(confirmedVersionTraffic).map(
([versionId, percentage]) => `version ${versionId} at ${percentage}%`
);
const trafficSummaryString = new Intl.ListFormat("en-US").format(
trafficSummaryList
);
success(
`Deployed ${workerName} ${trafficSummaryString} (${elapsedString})`
);
let workerTag = null;
try {
const serviceMetaData = await fetchResult(config, `/accounts/${accountId}/workers/services/${workerName}`);
workerTag = serviceMetaData.default_environment.script.tag;
} catch {
}
writeOutput({
type: "version-deploy",
version: 1,
worker_name: workerName,
worker_tag: workerTag,
// NOTE this deploymentId is related to the gradual rollout of the versions given in the version_traffic.
deployment_id: deploymentId,
version_traffic: confirmedVersionTraffic
});
}, "versionsDeployHandler")
});
__name(confirmLatestDeploymentOverwrite, "confirmLatestDeploymentOverwrite");
__name(printLatestDeployment, "printLatestDeployment");
__name(printDeployment, "printDeployment");
__name(printVersions, "printVersions");
__name(formatVersions, "formatVersions");
__name(promptVersionsToDeploy, "promptVersionsToDeploy");
__name(promptPercentages, "promptPercentages");
__name(maybePatchSettings, "maybePatchSettings");
__name(parseVersionSpecs, "parseVersionSpecs");
__name(assignAndDistributePercentages, "assignAndDistributePercentages");
__name(summariseVersionTraffic, "summariseVersionTraffic");
__name(validateTrafficSubtotal, "validateTrafficSubtotal");
}
});
// src/versions/deployments/index.ts
var deploymentsNamespace;
var init_deployments3 = __esm({
"src/versions/deployments/index.ts"() {
init_import_meta_url();
init_create_command();
deploymentsNamespace = createNamespace({
metadata: {
description: "\u{1F6A2} List and view the current and past deployments for your Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
}
});
}
});
// src/versions/list.ts
function getVersionSource(version5) {
return version5.annotations?.["workers/triggered_by"] === void 0 ? formatSource(version5.metadata.source) : formatTrigger(version5.annotations["workers/triggered_by"]);
}
function formatSource(source) {
switch (source) {
case "api":
return "API \u{1F4E1}";
case "dash":
return "Dashboard \u{1F5A5}\uFE0F";
case "wrangler":
return "Wrangler \u{1F920}";
case "terraform":
return "Terraform \u{1F3D7}\uFE0F";
default:
return `Other (${source})`;
}
}
function formatTrigger(trigger) {
switch (trigger) {
case "upload":
return "Upload";
case "secret":
return "Secret Change";
case "rollback":
return "Rollback";
case "promotion":
return "Promotion";
default:
return `Unknown (${trigger})`;
}
}
var BLANK_INPUT2, versionsListCommand;
var init_list9 = __esm({
"src/versions/list.ts"() {
init_import_meta_url();
init_cli();
init_create_command();
init_errors();
init_metrics();
init_user2();
init_render_labelled_values();
init_api();
BLANK_INPUT2 = "-";
versionsListCommand = createCommand({
metadata: {
description: "List the 10 most recent Versions of your Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
json: {
describe: "Display output as clean JSON",
type: "boolean",
default: false
}
},
handler: /* @__PURE__ */ __name(async function versionsListHandler(args, { config }) {
sendMetricsEvent(
"list worker versions",
{ json: args.json },
{
sendMetrics: config.send_metrics
}
);
const accountId = await requireAuth(config);
const workerName = args.name ?? config.name;
if (workerName === void 0) {
throw new UserError(
'You need to provide a name of your worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const versionCache = /* @__PURE__ */ new Map();
const versions2 = (await fetchDeployableVersions(config, accountId, workerName, versionCache)).sort(
(a5, b6) => a5.metadata.created_on.localeCompare(b6.metadata.created_on)
);
if (args.json) {
logRaw(JSON.stringify(versions2, null, 2));
return;
}
for (const version5 of versions2) {
const formattedVersion = formatLabelledValues({
"Version ID": version5.id,
Created: new Date(version5.metadata["created_on"]).toISOString(),
Author: version5.metadata.author_email,
Source: getVersionSource(version5),
Tag: version5.annotations?.["workers/tag"] || BLANK_INPUT2,
Message: version5.annotations?.["workers/message"] || BLANK_INPUT2
});
logRaw(formattedVersion);
logRaw(``);
}
}, "versionsListHandler")
});
__name(getVersionSource, "getVersionSource");
__name(formatSource, "formatSource");
__name(formatTrigger, "formatTrigger");
}
});
// src/versions/deployments/list.ts
function getDeploymentSource(deployment) {
return getVersionSource({
metadata: { source: deployment.source },
annotations: deployment.annotations
});
}
var import_assert6, BLANK_INPUT3, deploymentsListCommand;
var init_list10 = __esm({
"src/versions/deployments/list.ts"() {
init_import_meta_url();
import_assert6 = __toESM(require("assert"));
init_cli();
init_colors();
init_create_command();
init_errors();
init_metrics();
init_user2();
init_render_labelled_values();
init_api();
init_list9();
BLANK_INPUT3 = "-";
deploymentsListCommand = createCommand({
metadata: {
description: "Displays the 10 most recent deployments of your Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
args: {
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
json: {
describe: "Display output as clean JSON",
type: "boolean",
default: false
}
},
behaviour: {
printBanner: false
},
handler: /* @__PURE__ */ __name(async function versionsDeploymentsListHandler(args, { config }) {
sendMetricsEvent(
"list versioned deployments",
{ json: args.json },
{
sendMetrics: config.send_metrics
}
);
const accountId = await requireAuth(config);
const workerName = args.name ?? config.name;
if (workerName === void 0) {
throw new UserError(
'You need to provide a name for your Worker. Either pass it as a cli arg with `--name <name>` or in your configuration file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const deployments = (await fetchLatestDeployments(config, accountId, workerName)).sort((a5, b6) => a5.created_on.localeCompare(b6.created_on));
if (args.json) {
logRaw(JSON.stringify(deployments, null, 2));
return;
}
const versionCache = /* @__PURE__ */ new Map();
const versionIds = deployments.flatMap(
(d6) => d6.versions.map((v7) => v7.version_id)
);
await fetchVersions(
config,
accountId,
workerName,
versionCache,
...versionIds
);
const formattedDeployments = deployments.map((deployment) => {
const formattedVersions = deployment.versions.map((traffic) => {
const version5 = versionCache.get(traffic.version_id);
(0, import_assert6.default)(version5);
const percentage = brandColor(`(${traffic.percentage}%)`);
const details = formatLabelledValues(
{
Created: new Date(version5.metadata["created_on"]).toISOString(),
Tag: version5.annotations?.["workers/tag"] || BLANK_INPUT3,
Message: version5.annotations?.["workers/message"] || BLANK_INPUT3
},
{
indentationCount: 4,
labelJustification: "right",
formatLabel: /* @__PURE__ */ __name((label) => gray(label + ":"), "formatLabel"),
formatValue: /* @__PURE__ */ __name((value) => gray(value), "formatValue")
}
);
return `${percentage} ${version5.id}
${details}`;
});
return formatLabelledValues({
// explicitly not outputting Deployment ID
Created: new Date(deployment.created_on).toISOString(),
Author: deployment.author_email,
Source: getDeploymentSource(deployment),
Message: deployment.annotations?.["workers/message"] || BLANK_INPUT3,
"Version(s)": formattedVersions.join("\n\n")
});
});
logRaw(formattedDeployments.join("\n\n"));
}, "versionsDeploymentsListHandler")
});
__name(getDeploymentSource, "getDeploymentSource");
}
});
// src/versions/deployments/status.ts
var import_assert7, BLANK_INPUT4, deploymentsStatusCommand;
var init_status = __esm({
"src/versions/deployments/status.ts"() {
init_import_meta_url();
import_assert7 = __toESM(require("assert"));
init_cli();
init_colors();
init_create_command();
init_errors();
init_metrics();
init_user2();
init_render_labelled_values();
init_wrangler_banner();
init_api();
init_list10();
BLANK_INPUT4 = "-";
deploymentsStatusCommand = createCommand({
metadata: {
description: "View the current state of your production",
owner: "Workers: Authoring and Testing",
status: "stable"
},
args: {
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
json: {
describe: "Display output as clean JSON",
type: "boolean",
default: false
}
},
behaviour: {
printBanner: false
},
handler: /* @__PURE__ */ __name(async function versionsDeploymentsStatusHandler(args, { config }) {
if (!args.json) {
await printWranglerBanner();
}
sendMetricsEvent(
"view latest versioned deployment",
{},
{
sendMetrics: config.send_metrics
}
);
const accountId = await requireAuth(config);
const workerName = args.name ?? config.name;
if (workerName === void 0) {
throw new UserError(
'You need to provide a name for your Worker. Either pass it as a cli arg with `--name <name>` or in your configuration file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const latestDeployment = await fetchLatestDeployment(
config,
accountId,
workerName
);
if (!latestDeployment) {
throw new UserError(`The Worker ${workerName} has no deployments.`, {
telemetryMessage: "The Worker has no deployments"
});
}
if (args.json) {
logRaw(JSON.stringify(latestDeployment, null, 2));
return;
}
const versionCache = /* @__PURE__ */ new Map();
const versionIds = latestDeployment.versions.map((v7) => v7.version_id);
await fetchVersions(
config,
accountId,
workerName,
versionCache,
...versionIds
);
const formattedVersions = latestDeployment.versions.map((traffic) => {
const version5 = versionCache.get(traffic.version_id);
(0, import_assert7.default)(version5);
const percentage = brandColor(`(${traffic.percentage}%)`);
const details = formatLabelledValues(
{
Created: new Date(version5.metadata["created_on"]).toISOString(),
Tag: version5.annotations?.["workers/tag"] || BLANK_INPUT4,
Message: version5.annotations?.["workers/message"] || BLANK_INPUT4
},
{
indentationCount: 4,
labelJustification: "right",
formatLabel: /* @__PURE__ */ __name((label) => gray(label + ":"), "formatLabel"),
formatValue: /* @__PURE__ */ __name((value) => gray(value), "formatValue")
}
);
return `${percentage} ${version5.id}
${details}`;
});
const formattedDeployment = formatLabelledValues({
// explicitly not outputting Deployment ID
Created: new Date(latestDeployment.created_on).toISOString(),
Author: latestDeployment.author_email,
Source: getDeploymentSource(latestDeployment),
Message: latestDeployment.annotations?.["workers/message"] || BLANK_INPUT4,
"Version(s)": formattedVersions.join("\n\n")
});
logRaw(formattedDeployment);
}, "versionsDeploymentsStatusHandler")
});
}
});
// src/versions/deployments/view.ts
var deploymentsViewCommand;
var init_view = __esm({
"src/versions/deployments/view.ts"() {
init_import_meta_url();
init_create_command();
init_errors();
deploymentsViewCommand = createCommand({
metadata: {
description: "View a deployment of a Worker",
owner: "Workers: Authoring and Testing",
status: "stable",
hidden: true
},
args: {
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
["deployment-id"]: {
describe: "Deprecated. Deployment ID is now referred to as Version ID. Please use `wrangler versions view [version-id]` instead.",
type: "string",
requiresArg: true
}
},
positionalArgs: ["deployment-id"],
handler: /* @__PURE__ */ __name(async function versionsDeploymentsViewHandler(args) {
if (args.deploymentId === void 0) {
throw new UserError(
"`wrangler deployments view` has been renamed `wrangler deployments status`. Please use that command instead."
);
} else {
throw new UserError(
"`wrangler deployments view <deployment-id>` has been renamed `wrangler versions view [version-id]`. Please use that command instead."
);
}
}, "versionsDeploymentsViewHandler")
});
}
});
// src/versions/rollback/index.ts
async function fetchDefaultRollbackVersionId(config, accountId, workerName) {
const deployments = await fetchLatestDeployments(
config,
accountId,
workerName
);
deployments.sort((a5, b6) => b6.created_on.localeCompare(a5.created_on));
deployments.shift();
for (const deployment of deployments) {
const stableVersion = deployment.versions.find(
({ percentage }) => percentage === 100
);
if (stableVersion) {
return stableVersion.version_id;
}
}
throw new Error(
"Could not find stable Worker Version to rollback to. Please try again with an explicit Version ID."
);
}
var CANNOT_ROLLBACK_WITH_MODIFIED_SECERT_CODE, versionsRollbackCommand;
var init_rollback = __esm({
"src/versions/rollback/index.ts"() {
init_import_meta_url();
init_cli();
init_interactive();
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_parse();
init_user2();
init_api();
init_deploy7();
CANNOT_ROLLBACK_WITH_MODIFIED_SECERT_CODE = 10220;
versionsRollbackCommand = createCommand({
args: {
"version-id": {
describe: "The ID of the Worker Version to rollback to",
type: "string",
demandOption: false
},
name: {
describe: "The name of your Worker",
type: "string"
},
message: {
alias: "m",
describe: "The reason for this rollback",
type: "string",
default: void 0
},
yes: {
alias: "y",
describe: "Automatically accept defaults to prompts",
type: "boolean",
default: false
}
},
positionalArgs: ["version-id"],
metadata: {
description: "\u{1F519} Rollback a deployment for a Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
handler: /* @__PURE__ */ __name(async function handleRollback(args, { config }) {
const accountId = await requireAuth(config);
const workerName = args.name ?? config.name;
if (workerName === void 0) {
throw new UserError(
'You need to provide a name for your Worker. Either pass it as a cli arg with `--name <name>` or in your configuration file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
await printLatestDeployment(config, accountId, workerName, /* @__PURE__ */ new Map());
const versionId = args.versionId ?? await spinnerWhile({
promise: fetchDefaultRollbackVersionId(config, accountId, workerName),
startMessage: "Finding latest stable Worker Version to rollback to",
endMessage: ""
});
const message = await prompt(
"Please provide an optional message for this rollback (120 characters max)",
{
defaultValue: args.message ?? "Rollback"
}
);
const version5 = await fetchVersion(
config,
accountId,
workerName,
versionId
);
warn(
`You are about to rollback to Worker Version ${versionId}.
This will immediately replace the current deployment and become the active deployment across all your deployed triggers.
However, your local development environment will not be affected by this rollback.
Rolling back to a previous deployment will not rollback any of the bound resources (Durable Object, D1, R2, KV, etc).`,
{ multiline: true, shape: shapes.leftT }
);
const rollbackTraffic = /* @__PURE__ */ new Map([[versionId, 100]]);
printVersions([version5], rollbackTraffic);
const confirmed = await confirm(
"Are you sure you want to deploy this Worker Version to 100% of traffic?",
{ defaultValue: true }
);
if (!confirmed) {
cancel("Aborting rollback...");
return;
}
logger.log("Performing rollback...");
try {
await createDeployment(
config,
accountId,
workerName,
rollbackTraffic,
message
);
} catch (e7) {
if (e7 instanceof APIError && e7.code === CANNOT_ROLLBACK_WITH_MODIFIED_SECERT_CODE) {
const errorMsg = e7.notes[0].text.replace(
` [code: ${CANNOT_ROLLBACK_WITH_MODIFIED_SECERT_CODE}]`,
""
);
const targetString = "The following secrets have changed:";
const changedSecrets = errorMsg.substring(errorMsg.indexOf(targetString) + targetString.length + 1).split(", ");
const secretConfirmation = await confirm(
`The following secrets have changed since version ${versionId} was deployed. Please confirm you wish to continue with the rollback
` + changedSecrets.map((secret) => ` * ${secret}`).join("\n")
);
if (secretConfirmation) {
await createDeployment(
config,
accountId,
workerName,
rollbackTraffic,
message,
true
);
} else {
cancel("Aborting rollback...");
}
} else {
throw e7;
}
}
success(
`Worker Version ${versionId} has been deployed to 100% of traffic.`
);
logger.log("\nCurrent Version ID: " + versionId);
}, "handleRollback")
});
__name(fetchDefaultRollbackVersionId, "fetchDefaultRollbackVersionId");
}
});
// src/versions/secrets/index.ts
async function copyWorkerVersionWithNewSecrets({
config,
accountId,
scriptName,
versionId,
secrets,
versionMessage,
versionTag,
sendMetrics,
unsafeMetadata,
overrideAllSecrets
}) {
const versionInfo = await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions/${versionId}`
);
const { mainModule, modules, sourceMaps } = await parseModules(
config,
accountId,
scriptName,
versionId
);
const scriptSettings = await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/script-settings`
);
const bindings = versionInfo.resources.bindings.filter((binding) => binding.type !== "secret_text").map((binding) => {
return {
name: binding.name,
type: "inherit"
};
});
for (const secret of secrets) {
if (secret.inherit) {
bindings.push({
type: "inherit",
name: secret.name
});
} else {
bindings.push({
type: "secret_text",
name: secret.name,
text: secret.value
});
}
}
const keepBindings = ["secret_key"];
if (!overrideAllSecrets) {
keepBindings.push("secret_text");
}
const worker = {
name: scriptName,
main: mainModule,
bindings: {
unsafe: { metadata: unsafeMetadata }
// pass along unsafe metadata
},
// handled in rawBindings
rawBindings: bindings,
modules,
sourceMaps,
migrations: void 0,
compatibility_date: versionInfo.resources.script_runtime.compatibility_date,
compatibility_flags: versionInfo.resources.script_runtime.compatibility_flags,
keepVars: false,
// we're re-uploading everything
keepSecrets: false,
// handled in keepBindings
keepBindings,
logpush: scriptSettings.logpush,
placement: versionInfo.resources.script.placement_mode === "smart" ? { mode: "smart" } : void 0,
tail_consumers: scriptSettings.tail_consumers ?? void 0,
limits: versionInfo.resources.script_runtime.limits,
annotations: {
"workers/message": versionMessage,
"workers/tag": versionTag
},
keep_assets: true,
assets: void 0,
observability: scriptSettings.observability
};
const body = createWorkerUploadForm(worker);
const result = await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions`,
{
method: "POST",
body,
headers: await getMetricsUsageHeaders(sendMetrics)
},
new URLSearchParams({
include_subdomain_availability: "true",
// pass excludeScript so the whole body of the
// script doesn't get included in the response
excludeScript: "true"
})
);
return result;
}
async function parseModules(config, accountId, scriptName, versionId) {
const contentRes = await performApiFetch(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/content/v2?version=${versionId}`
);
if (contentRes.headers.get("content-type")?.startsWith("multipart/form-data")) {
const formData = await contentRes.formData();
if (formData.get("__STATIC_CONTENT_MANIFEST") !== null) {
throw new UserError(
"Workers Sites does not support updating secrets through `wrangler versions secret put`. You must use `wrangler secret put` instead."
);
}
const entrypoint = contentRes.headers.get("cf-entrypoint");
if (entrypoint === null) {
throw new FatalError("Got modules without cf-entrypoint header");
}
const entrypointPart = formData.get(entrypoint);
if (entrypointPart === null) {
throw new FatalError("Could not find entrypoint in form-data");
}
const mainModule = {
name: entrypointPart.name,
filePath: "",
content: Buffer.from(await entrypointPart.arrayBuffer()),
type: fromMimeType(entrypointPart.type)
};
const modules = await Promise.all(
Array.from(formData.entries()).filter(
([name2, file]) => name2 !== entrypoint && file.type !== "application/source-map"
).map(
async ([name2, file]) => ({
name: name2,
filePath: "",
content: Buffer.from(await file.arrayBuffer()),
type: fromMimeType(file.type)
})
)
);
const sourceMaps = await Promise.all(
Array.from(formData.entries()).filter(([_4, file]) => file.type === "application/source-map").map(
async ([name2, file]) => ({
name: name2,
content: await file.text()
})
)
);
return { mainModule, modules, sourceMaps };
} else {
const contentType = contentRes.headers.get("content-type");
if (contentType === null) {
throw new FatalError(
"No content-type header was provided for non-module Worker content"
);
}
const content = await contentRes.text();
const mainModule = {
name: "index.js",
filePath: "",
content,
type: fromMimeType(contentType)
};
return { mainModule, modules: [], sourceMaps: [] };
}
}
var versionsSecretNamespace;
var init_secrets = __esm({
"src/versions/secrets/index.ts"() {
init_import_meta_url();
init_cfetch();
init_internal();
init_create_command();
init_create_worker_upload_form();
init_errors();
init_metrics();
versionsSecretNamespace = createNamespace({
metadata: {
description: "Generate a secret that can be referenced in a Worker",
status: "stable",
owner: "Workers: Authoring and Testing"
}
});
__name(copyWorkerVersionWithNewSecrets, "copyWorkerVersionWithNewSecrets");
__name(parseModules, "parseModules");
}
});
// src/versions/secrets/bulk.ts
var versionsSecretBulkCommand;
var init_bulk = __esm({
"src/versions/secrets/bulk.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_create_command();
init_errors();
init_logger();
init_secret();
init_user2();
init_getLegacyScriptName();
init_secrets();
versionsSecretBulkCommand = createCommand({
metadata: {
description: "Create or update a secret variable for a Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false,
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
file: {
describe: `The file of key-value pairs to upload, as JSON in form {"key": value, ...} or .dev.vars file in the form KEY=VALUE`,
type: "string"
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
message: {
describe: "Description of this deployment",
type: "string",
requiresArg: true
},
tag: {
describe: "A tag for this version",
type: "string",
requiresArg: true
}
},
positionalArgs: ["file"],
handler: /* @__PURE__ */ __name(async function versionsSecretPutBulkHandler(args, { config }) {
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
const accountId = await requireAuth(config);
logger.log(
`\u{1F300} Creating the secrets for the Worker "${scriptName}" ${args.env ? `(${args.env})` : ""}`
);
const content = await parseBulkInputToObject(args.file);
if (!content) {
return logger.error(`No content found in file or piped input.`);
}
const secrets = Object.entries(content).map(([key, value]) => ({
name: key,
value
}));
const versions2 = (await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions`
)).items;
if (versions2.length === 0) {
throw new UserError(
"There are currently no uploaded versions of this Worker - please upload a version before uploading a secret."
);
}
const latestVersion = versions2[0];
const newVersion = await copyWorkerVersionWithNewSecrets({
config,
accountId,
scriptName,
versionId: latestVersion.id,
secrets,
versionMessage: args.message ?? `Bulk updated ${secrets.length} secrets`,
versionTag: args.tag,
sendMetrics: config.send_metrics,
unsafeMetadata: config.unsafe.metadata
});
for (const secret of secrets) {
logger.log(`\u2728 Successfully created secret for key: ${secret.name}`);
}
logger.log(
`\u2728 Success! Created version ${newVersion.id} with ${secrets.length} secrets.
\u27A1\uFE0F To deploy this version to production traffic use the command "wrangler versions deploy".`
);
}, "versionsSecretPutBulkHandler")
});
}
});
// src/versions/secrets/delete.ts
var versionsSecretDeleteCommand;
var init_delete9 = __esm({
"src/versions/secrets/delete.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_user2();
init_getLegacyScriptName();
init_isLegacyEnv();
init_secrets();
versionsSecretDeleteCommand = createCommand({
metadata: {
description: "Delete a secret variable from a Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false,
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
key: {
describe: "The variable name to be accessible in the Worker",
type: "string",
requiresArg: true
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
message: {
describe: "Description of this deployment",
type: "string",
requiresArg: true
},
tag: {
describe: "A tag for this version",
type: "string",
requiresArg: true
}
},
positionalArgs: ["key"],
handler: /* @__PURE__ */ __name(async function versionsSecretDeleteHandler(args, { config }) {
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
if (args.key === void 0) {
throw new UserError(
"Secret name is required. Please specify the name of your secret."
);
}
const accountId = await requireAuth(config);
if (await confirm(
`Are you sure you want to permanently delete the secret ${args.key} on the Worker ${scriptName}${args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""}?`
)) {
logger.log(
`\u{1F300} Deleting the secret ${args.key} on the Worker ${scriptName}${args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""}`
);
const versions2 = (await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions`
)).items;
if (versions2.length === 0) {
throw new UserError(
"There are currently no uploaded versions of this Worker - please upload a version before uploading a secret."
);
}
const latestVersion = versions2[0];
const versionInfo = await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions/${latestVersion.id}`
);
const newSecrets = versionInfo.resources.bindings.filter(
(binding) => binding.type === "secret_text" && binding.name !== args.key
).map((binding) => ({
name: binding.name,
value: "",
inherit: true
}));
const newVersion = await copyWorkerVersionWithNewSecrets({
config,
accountId,
scriptName,
versionId: latestVersion.id,
secrets: newSecrets,
versionMessage: args.message ?? `Deleted secret "${args.key}"`,
versionTag: args.tag,
sendMetrics: config.send_metrics,
overrideAllSecrets: true
});
logger.log(
`\u2728 Success! Created version ${newVersion.id} with deleted secret ${args.key}.
\u27A1\uFE0F To deploy this version without the secret ${args.key} to production traffic use the command "wrangler versions deploy".`
);
}
}, "versionsSecretDeleteHandler")
});
}
});
// src/versions/secrets/list.ts
var versionsSecretsListCommand;
var init_list11 = __esm({
"src/versions/secrets/list.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_create_command();
init_errors();
init_logger();
init_user2();
init_getLegacyScriptName();
init_api();
versionsSecretsListCommand = createCommand({
metadata: {
description: "List the secrets currently deployed",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false
},
args: {
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
"latest-version": {
describe: "Only show the latest version",
type: "boolean",
default: false
}
},
handler: /* @__PURE__ */ __name(async function versionsSecretListHandler(args, { config }) {
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
const accountId = await requireAuth(config);
const versionCache = /* @__PURE__ */ new Map();
let versions2 = [];
let rollout = /* @__PURE__ */ new Map();
if (args.latestVersion) {
const mostRecentVersions = (await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions`
)).items;
if (mostRecentVersions.length === 0) {
throw new UserError(
"There are currently no uploaded versions of this Worker - please upload a version."
);
}
const latestVersion = mostRecentVersions[0];
versions2 = [latestVersion];
const latestDeployment = await fetchLatestDeployment(
config,
accountId,
scriptName
);
const deploymentVersion = latestDeployment?.versions.find(
(ver) => ver.version_id === latestVersion.id
);
rollout.set(latestVersion.id, deploymentVersion?.percentage ?? 0);
} else {
const latestDeployment = await fetchLatestDeployment(
config,
accountId,
scriptName
);
[versions2, rollout] = await fetchDeploymentVersions(
config,
accountId,
scriptName,
latestDeployment,
versionCache
);
}
for (const version5 of versions2) {
logger.log(
`-- Version ${version5.id} (${rollout.get(version5.id)}%) secrets --`
);
const secrets = version5.resources.bindings.filter(
(binding) => binding.type === "secret_text"
);
for (const secret of secrets) {
logger.log(`Secret Name: ${secret.name}`);
}
logger.log();
}
}, "versionsSecretListHandler")
});
}
});
// src/versions/secrets/put.ts
var versionsSecretPutCommand;
var init_put = __esm({
"src/versions/secrets/put.ts"() {
init_import_meta_url();
init_cfetch();
init_config2();
init_create_command();
init_dialogs();
init_errors();
init_logger();
init_user2();
init_getLegacyScriptName();
init_std();
init_secrets();
versionsSecretPutCommand = createCommand({
metadata: {
description: "Create or update a secret variable for a Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printConfigWarnings: false,
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
args: {
key: {
describe: "The variable name to be accessible in the Worker",
type: "string",
requiresArg: true
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
message: {
describe: "Description of this deployment",
type: "string",
requiresArg: true
},
tag: {
describe: "A tag for this version",
type: "string",
requiresArg: true
}
},
positionalArgs: ["key"],
handler: /* @__PURE__ */ __name(async function versionsSecretPutHandler(args, { config }) {
const scriptName = getLegacyScriptName(args, config);
if (!scriptName) {
throw new UserError(
`Required Worker name missing. Please specify the Worker name in your ${configFileName(config.configPath)} file, or pass it as an argument with \`--name <worker-name>\``
);
}
if (args.key === void 0) {
throw new UserError(
"Secret name is required. Please specify the name of your secret."
);
}
const accountId = await requireAuth(config);
const isInteractive3 = process.stdin.isTTY;
const secretValue = trimTrailingWhitespace(
isInteractive3 ? await prompt("Enter a secret value:", { isSecret: true }) : await readFromStdin()
);
logger.log(
`\u{1F300} Creating the secret for the Worker "${scriptName}" ${args.env ? `(${args.env})` : ""}`
);
const versions2 = (await fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions`
)).items;
if (versions2.length === 0) {
throw new UserError(
"There are currently no uploaded versions of this Worker. Please upload a version before uploading a secret."
);
}
const latestVersion = versions2[0];
const newVersion = await copyWorkerVersionWithNewSecrets({
config,
accountId,
scriptName,
versionId: latestVersion.id,
secrets: [{ name: args.key, value: secretValue }],
versionMessage: args.message ?? `Updated secret "${args.key}"`,
versionTag: args.tag,
sendMetrics: config.send_metrics,
unsafeMetadata: config.unsafe.metadata
});
logger.log(
`\u2728 Success! Created version ${newVersion.id} with secret ${args.key}.
\u27A1\uFE0F To deploy this version with secret ${args.key} to production traffic use the command "wrangler versions deploy".`
);
}, "versionsSecretPutHandler")
});
}
});
// src/versions/upload.ts
async function versionsUpload(props) {
const { config, accountId, name: name2 } = props;
let versionId = null;
let workerTag = null;
if (accountId && name2) {
try {
const {
default_environment: { script }
} = await fetchResult(
config,
`/accounts/${accountId}/workers/services/${name2}`
// TODO(consider): should this be a /versions endpoint?
);
workerTag = script.tag;
if (script.last_deployed_from === "dash") {
logger.warn(
`You are about to upload a Worker Version that was last published via the Cloudflare Dashboard.
Edits that have been made via the dashboard will be overridden by your local code and config.`
);
if (!await confirm("Would you like to continue?")) {
return {
versionId,
workerTag
};
}
} else if (script.last_deployed_from === "api") {
logger.warn(
`You are about to upload a Workers Version that was last updated via the API.
Edits that have been made via the API will be overridden by your local code and config.`
);
if (!await confirm("Would you like to continue?")) {
return {
versionId,
workerTag
};
}
}
} catch (e7) {
if (e7.code !== 10090) {
throw e7;
}
}
}
const compatibilityDate = props.compatibilityDate || config.compatibility_date;
const compatibilityFlags = props.compatibilityFlags ?? config.compatibility_flags;
if (!compatibilityDate) {
const compatibilityDateStr = formatCompatibilityDate(/* @__PURE__ */ new Date());
throw new UserError(`A compatibility_date is required when uploading a Worker Version. Add the following to your ${configFileName(config.configPath)} file:
\`\`\`
${formatConfigSnippet({ compatibility_date: compatibilityDateStr }, config.configPath), false}
\`\`\`
Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
}
const jsxFactory = props.jsxFactory || config.jsx_factory;
const jsxFragment = props.jsxFragment || config.jsx_fragment;
const minify = props.minify ?? config.minify;
const nodejsCompatMode = validateNodeCompatMode(
compatibilityDate,
compatibilityFlags,
{
noBundle: props.noBundle ?? config.no_bundle
}
);
if (props.noBundle && minify) {
logger.warn(
"`--minify` and `--no-bundle` can't be used together. If you want to minify your Worker and disable Wrangler's bundling, please minify as part of your own bundling process."
);
}
const scriptName = props.name;
if (config.site && !config.site.bucket) {
throw new UserError(
"A [site] definition requires a `bucket` field with a path to the site's assets directory."
);
}
if (props.outDir) {
(0, import_node_fs32.mkdirSync)(props.outDir, { recursive: true });
const readmePath = import_node_path55.default.join(props.outDir, "README.md");
(0, import_node_fs32.writeFileSync)(
readmePath,
`This folder contains the built output assets for the worker "${scriptName}" generated at ${(/* @__PURE__ */ new Date()).toISOString()}.`
);
}
const destination = props.outDir ?? getWranglerTmpDir(props.projectRoot, "deploy");
const start = Date.now();
const workerName = scriptName;
const workerUrl = `/accounts/${accountId}/workers/scripts/${scriptName}`;
const { format: format9 } = props.entry;
if (config.wasm_modules && format9 === "modules") {
throw new UserError(
"You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
);
}
if (config.text_blobs && format9 === "modules") {
throw new UserError(
`You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure \`[rules]\` in your ${configFileName(config.configPath)} file`
);
}
if (config.data_blobs && format9 === "modules") {
throw new UserError(
`You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure \`[rules]\` in your ${configFileName(config.configPath)} file`
);
}
let hasPreview = false;
try {
if (props.noBundle) {
const destinationDir = typeof destination === "string" ? destination : destination.path;
(0, import_node_fs32.mkdirSync)(destinationDir, { recursive: true });
(0, import_node_fs32.writeFileSync)(
import_node_path55.default.join(destinationDir, import_node_path55.default.basename(props.entry.file)),
(0, import_node_fs32.readFileSync)(props.entry.file, "utf-8")
);
}
const entryDirectory = import_node_path55.default.dirname(props.entry.file);
const moduleCollector = createModuleCollector({
wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences(
entryDirectory,
props.entry.file
),
entry: props.entry,
// `moduleCollector` doesn't get used when `props.noBundle` is set, so
// `findAdditionalModules` always defaults to `false`
findAdditionalModules: config.find_additional_modules ?? false,
rules: props.rules
});
const uploadSourceMaps = props.uploadSourceMaps ?? config.upload_source_maps;
const {
modules,
dependencies,
resolvedEntryPointPath,
bundleType,
...bundle
} = props.noBundle ? await noBundleWorker(props.entry, props.rules, props.outDir) : await bundleWorker(
props.entry,
typeof destination === "string" ? destination : destination.path,
{
bundle: true,
additionalModules: [],
moduleCollector,
doBindings: config.durable_objects.bindings,
workflowBindings: config.workflows,
jsxFactory,
jsxFragment,
tsconfig: props.tsconfig ?? config.tsconfig,
minify,
keepNames: config.keep_names ?? true,
sourcemap: uploadSourceMaps,
nodejsCompatMode,
compatibilityDate,
compatibilityFlags,
define: { ...config.define, ...props.defines },
alias: { ...config.alias, ...props.alias },
checkFetch: false,
// We want to know if the build is for development or publishing
// This could potentially cause issues as we no longer have identical behaviour between dev and deploy?
targetConsumer: "deploy",
local: false,
projectRoot: props.projectRoot,
defineNavigatorUserAgent: isNavigatorDefined(
compatibilityDate,
compatibilityFlags
),
plugins: [logBuildOutput(nodejsCompatMode)],
// Pages specific options used by wrangler pages commands
entryName: void 0,
inject: void 0,
isOutfile: void 0,
external: void 0,
// These options are dev-only
testScheduled: void 0,
watch: void 0,
metafile: void 0
}
);
for (const module3 of modules) {
const modulePath = module3.filePath === void 0 ? module3.name : import_node_path55.default.relative("", module3.filePath);
const bytesInOutput = typeof module3.content === "string" ? Buffer.byteLength(module3.content) : module3.content.byteLength;
dependencies[modulePath] = { bytesInOutput };
}
const content = (0, import_node_fs32.readFileSync)(resolvedEntryPointPath, {
encoding: "utf-8"
});
const migrations = !props.dryRun ? await getMigrationsToUpload(scriptName, {
accountId,
config,
legacyEnv: props.legacyEnv,
env: props.env,
dispatchNamespace: void 0
}) : void 0;
const assetsJwt = props.assetsOptions && !props.dryRun ? await syncAssets(
config,
accountId,
props.assetsOptions.directory,
scriptName
) : void 0;
const bindings = getBindings({
...config,
vars: { ...config.vars, ...props.vars }
});
const placement = config.placement?.mode === "smart" ? { mode: "smart", hint: config.placement.hint } : void 0;
const entryPointName = import_node_path55.default.basename(resolvedEntryPointPath);
const main2 = {
name: entryPointName,
filePath: resolvedEntryPointPath,
content,
type: bundleType
};
const worker = {
name: scriptName,
main: main2,
bindings,
migrations,
modules,
sourceMaps: uploadSourceMaps ? loadSourceMaps(main2, modules, bundle) : void 0,
compatibility_date: compatibilityDate,
compatibility_flags: compatibilityFlags,
keepVars: false,
// the wrangler.toml should be the source-of-truth for vars
keepSecrets: true,
// until wrangler.toml specifies secret bindings, we need to inherit from the previous Worker Version
placement,
tail_consumers: config.tail_consumers,
limits: config.limits,
annotations: {
"workers/message": props.message,
"workers/tag": props.tag,
"workers/alias": props.previewAlias
},
assets: props.assetsOptions && assetsJwt ? {
jwt: assetsJwt,
routerConfig: props.assetsOptions.routerConfig,
assetConfig: props.assetsOptions.assetConfig,
_redirects: props.assetsOptions._redirects,
_headers: props.assetsOptions._headers,
run_worker_first: props.assetsOptions.run_worker_first
} : void 0,
logpush: void 0,
// both logpush and observability are not supported in versions upload
observability: void 0
};
await printBundleSize(
{ name: import_node_path55.default.basename(resolvedEntryPointPath), content },
modules
);
const maskedVars = { ...bindings.vars };
for (const key of Object.keys(maskedVars)) {
if (maskedVars[key] !== config.vars[key]) {
maskedVars[key] = "(hidden)";
}
}
let workerBundle;
if (props.dryRun) {
workerBundle = createWorkerUploadForm(worker);
printBindings({ ...bindings, vars: maskedVars }, config.tail_consumers);
} else {
(0, import_node_assert22.default)(accountId, "Missing accountId");
if (getFlag("RESOURCES_PROVISION")) {
await provisionBindings(
bindings,
accountId,
scriptName,
props.experimentalAutoCreate,
props.config
);
}
workerBundle = createWorkerUploadForm(worker);
await ensureQueuesExistByConfig(config);
let bindingsPrinted = false;
try {
const result = await retryOnAPIFailure(
async () => fetchResult(config, `${workerUrl}/versions`, {
method: "POST",
body: workerBundle,
headers: await getMetricsUsageHeaders(config.send_metrics)
})
);
logger.log("Worker Startup Time:", result.startup_time_ms, "ms");
bindingsPrinted = true;
printBindings({ ...bindings, vars: maskedVars }, config.tail_consumers);
versionId = result.id;
hasPreview = result.metadata.has_preview;
} catch (err) {
if (!bindingsPrinted) {
printBindings(
{ ...bindings, vars: maskedVars },
config.tail_consumers
);
}
const message = await helpIfErrorIsSizeOrScriptStartup(
err,
dependencies,
workerBundle,
props.projectRoot
);
if (message) {
logger.error(message);
}
if (err instanceof ParseError && "code" in err && err.code === 10021 && err.notes.length > 0) {
const maybeNameToFilePath = /* @__PURE__ */ __name((moduleName) => {
if (bundleType === "commonjs") {
return resolvedEntryPointPath;
}
if (moduleName === entryPointName) {
return resolvedEntryPointPath;
}
for (const module3 of modules) {
if (moduleName === module3.name) {
return module3.filePath;
}
}
}, "maybeNameToFilePath");
const retrieveSourceMap = /* @__PURE__ */ __name((moduleName) => maybeRetrieveFileSourceMap(maybeNameToFilePath(moduleName)), "retrieveSourceMap");
err.notes[0].text = getSourceMappedString(
err.notes[0].text,
retrieveSourceMap
);
}
throw err;
}
}
if (props.outFile) {
(0, import_node_fs32.mkdirSync)(import_node_path55.default.dirname(props.outFile), { recursive: true });
const serializedFormData = await new import_undici19.Response(workerBundle).arrayBuffer();
(0, import_node_fs32.writeFileSync)(props.outFile, Buffer.from(serializedFormData));
}
} finally {
if (typeof destination !== "string") {
destination.remove();
}
}
if (props.dryRun) {
logger.log(`--dry-run: exiting now.`);
return { versionId, workerTag };
}
if (!accountId) {
throw new UserError("Missing accountId");
}
const uploadMs = Date.now() - start;
logger.log("Uploaded", workerName, formatTime3(uploadMs));
logger.log("Worker Version ID:", versionId);
let versionPreviewUrl = void 0;
let versionPreviewAliasUrl = void 0;
if (versionId && hasPreview) {
const { previews_enabled: previews_available_on_subdomain } = await fetchResult(config, `${workerUrl}/subdomain`);
if (previews_available_on_subdomain) {
const userSubdomain = await getWorkersDevSubdomain(
config,
accountId,
config.configPath
);
const shortVersion = versionId.slice(0, 8);
versionPreviewUrl = `https://${shortVersion}-${workerName}.${userSubdomain}`;
logger.log(`Version Preview URL: ${versionPreviewUrl}`);
if (props.previewAlias) {
versionPreviewAliasUrl = `https://${props.previewAlias}-${workerName}.${userSubdomain}`;
logger.log(`Version Preview Alias URL: ${versionPreviewAliasUrl}`);
}
}
}
const cmdVersionsDeploy = blue("wrangler versions deploy");
const cmdTriggersDeploy = blue("wrangler triggers deploy");
logger.info(
gray(`
To deploy this version to production traffic use the command ${cmdVersionsDeploy}
Changes to non-versioned settings (config properties 'logpush' or 'tail_consumers') take effect after your next deployment using the command ${cmdVersionsDeploy}
Changes to triggers (routes, custom domains, cron schedules, etc) must be applied with the command ${cmdTriggersDeploy}
`)
);
return { versionId, workerTag, versionPreviewUrl, versionPreviewAliasUrl };
}
function formatTime3(duration) {
return `(${(duration / 1e3).toFixed(2)} sec)`;
}
function sanitizeBranchName(branchName) {
return branchName.replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
}
function getBranchName() {
const ciBranchName = getWorkersCIBranchName();
if (ciBranchName) {
return ciBranchName;
}
try {
(0, import_node_child_process7.execSync)(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
return (0, import_node_child_process7.execSync)(`git rev-parse --abbrev-ref HEAD`).toString().trim();
} catch {
return void 0;
}
}
function createTruncatedAlias(branchName, sanitizedAlias, availableSpace) {
const spaceForHash = HASH_LENGTH + 1;
const maxPrefixLength = availableSpace - spaceForHash;
if (maxPrefixLength < 1) {
return void 0;
}
const hash = (0, import_node_crypto12.createHash)("sha256").update(branchName).digest("hex").slice(0, HASH_LENGTH);
const truncatedPrefix = sanitizedAlias.slice(0, maxPrefixLength);
return `${truncatedPrefix}-${hash}`;
}
function generatePreviewAlias(scriptName) {
const warnAndExit = /* @__PURE__ */ __name(() => {
logger.warn(
`Preview alias generation requested, but could not be autogenerated.`
);
return void 0;
}, "warnAndExit");
const branchName = getBranchName();
if (!branchName) {
return warnAndExit();
}
const sanitizedAlias = sanitizeBranchName(branchName);
if (!ALIAS_VALIDATION_REGEX.test(sanitizedAlias)) {
return warnAndExit();
}
const availableSpace = MAX_DNS_LABEL_LENGTH - scriptName.length - 1;
if (sanitizedAlias.length <= availableSpace) {
return sanitizedAlias;
}
const truncatedAlias = createTruncatedAlias(
branchName,
sanitizedAlias,
availableSpace
);
return truncatedAlias || warnAndExit();
}
var import_node_assert22, import_node_child_process7, import_node_crypto12, import_node_fs32, import_node_path55, import_undici19, versionsUploadCommand, MAX_DNS_LABEL_LENGTH, HASH_LENGTH, ALIAS_VALIDATION_REGEX;
var init_upload2 = __esm({
"src/versions/upload.ts"() {
init_import_meta_url();
import_node_assert22 = __toESM(require("assert"));
import_node_child_process7 = require("child_process");
import_node_crypto12 = require("crypto");
import_node_fs32 = require("fs");
import_node_path55 = __toESM(require("path"));
init_colors();
import_undici19 = __toESM(require_undici());
init_assets();
init_cfetch();
init_config2();
init_create_command();
init_bindings();
init_bundle();
init_bundle_reporter();
init_create_worker_upload_form();
init_entry();
init_log_build_output();
init_module_collection();
init_no_bundle_worker();
init_node_compat();
init_source_maps();
init_dialogs();
init_durable();
init_misc_variables();
init_errors();
init_experimental_flags();
init_logger();
init_match_tag();
init_metrics();
init_metrics();
init_navigator_user_agent();
init_output();
init_parse();
init_paths();
init_client2();
init_routes();
init_sourcemap();
init_user2();
init_collectKeyValues();
init_compatibility_date();
init_friendly_validator_errors();
init_getRules();
init_getScriptName();
init_isLegacyEnv();
init_print_bindings();
init_retry();
versionsUploadCommand = createCommand({
metadata: {
description: "Uploads your Worker code and config as a new Version",
owner: "Workers: Authoring and Testing",
status: "stable"
},
args: {
script: {
describe: "The path to an entry point for your Worker",
type: "string",
requiresArg: true
},
name: {
describe: "Name of the worker",
type: "string",
requiresArg: true
},
bundle: {
describe: "Run wrangler's compilation step before publishing",
type: "boolean",
hidden: true
},
"no-bundle": {
describe: "Skip internal build steps and directly deploy Worker",
type: "boolean",
default: false
},
outdir: {
describe: "Output directory for the bundled Worker",
type: "string",
requiresArg: true
},
outfile: {
describe: "Output file for the bundled worker",
type: "string",
requiresArg: true
},
"compatibility-date": {
describe: "Date to use for compatibility checks",
type: "string",
requiresArg: true
},
"compatibility-flags": {
describe: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
requiresArg: true,
array: true
},
latest: {
describe: "Use the latest version of the Worker runtime",
type: "boolean",
default: false
},
assets: {
describe: "Static assets to be served. Replaces Workers Sites.",
type: "string",
requiresArg: true
},
site: {
describe: "Root folder of static assets for Workers Sites",
type: "string",
requiresArg: true,
hidden: true,
deprecated: true
},
"site-include": {
describe: "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
type: "string",
requiresArg: true,
array: true,
hidden: true,
deprecated: true
},
"site-exclude": {
describe: "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
type: "string",
requiresArg: true,
array: true,
hidden: true,
deprecated: true
},
var: {
describe: "A key-value pair to be injected into the script as a variable",
type: "string",
requiresArg: true,
array: true
},
define: {
describe: "A key-value pair to be substituted in the script",
type: "string",
requiresArg: true,
array: true
},
alias: {
describe: "A module pair to be substituted in the script",
type: "string",
requiresArg: true,
array: true
},
"jsx-factory": {
describe: "The function that is called for each JSX element",
type: "string",
requiresArg: true
},
"jsx-fragment": {
describe: "The function that is called for each JSX fragment",
type: "string",
requiresArg: true
},
tsconfig: {
describe: "Path to a custom tsconfig.json file",
type: "string",
requiresArg: true
},
minify: {
describe: "Minify the Worker",
type: "boolean"
},
"upload-source-maps": {
describe: "Include source maps when uploading this Worker Gradual Rollouts Version.",
type: "boolean"
},
"node-compat": {
describe: "Enable Node.js compatibility",
type: "boolean",
hidden: true,
deprecated: true
},
"dry-run": {
describe: "Don't actually deploy",
type: "boolean"
},
tag: {
describe: "A tag for this Worker Gradual Rollouts Version",
type: "string",
requiresArg: true
},
message: {
describe: "A descriptive message for this Worker Gradual Rollouts Version",
type: "string",
requiresArg: true
},
"preview-alias": {
describe: "Name of an alias for this Worker version",
type: "string",
requiresArg: true
},
"experimental-auto-create": {
describe: "Automatically provision draft bindings with new resources",
type: "boolean",
default: true,
hidden: true,
alias: "x-auto-create"
}
},
behaviour: {
useConfigRedirectIfAvailable: true,
overrideExperimentalFlags: /* @__PURE__ */ __name((args) => ({
MULTIWORKER: false,
RESOURCES_PROVISION: args.experimentalProvision ?? false,
REMOTE_BINDINGS: args.experimentalRemoteBindings ?? false,
DEPLOY_REMOTE_DIFF_CHECK: false
}), "overrideExperimentalFlags"),
warnIfMultipleEnvsConfiguredButNoneSpecified: true
},
handler: /* @__PURE__ */ __name(async function versionsUploadHandler(args, { config }) {
const entry = await getEntry(args, config, "versions upload");
sendMetricsEvent(
"upload worker version",
{
usesTypeScript: /\.tsx?$/.test(entry.file)
},
{
sendMetrics: config.send_metrics
}
);
if (args.nodeCompat) {
throw new UserError(
`The --node-compat flag is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`
);
}
if (args.site || config.site) {
throw new UserError(
"Workers Sites does not support uploading versions through `wrangler versions upload`. You must use `wrangler deploy` instead.",
{ telemetryMessage: true }
);
}
validateAssetsArgsAndConfig(
{
site: void 0,
assets: args.assets,
script: args.script
},
config
);
const assetsOptions = getAssetsOptions(args, config);
if (args.latest) {
logger.warn(
`Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your ${configFileName(config.configPath)} file.
`
);
}
const cliVars = collectKeyValues(args.var);
const cliDefines = collectKeyValues(args.define);
const cliAlias = collectKeyValues(args.alias);
const accountId = args.dryRun ? void 0 : await requireAuth(config);
let name2 = getScriptName(args, config);
const ciOverrideName = getCIOverrideName();
let workerNameOverridden = false;
if (ciOverrideName !== void 0 && ciOverrideName !== name2) {
logger.warn(
`Failed to match Worker name. Your config file is using the Worker name "${name2}", but the CI system expected "${ciOverrideName}". Overriding using the CI provided Worker name. Workers Builds connected builds will attempt to open a pull request to resolve this config name mismatch.`
);
name2 = ciOverrideName;
workerNameOverridden = true;
}
if (!name2) {
throw new UserError(
'You need to provide a name of your worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const previewAlias = args.previewAlias ?? (getCIGeneratePreviewAlias() === "true" ? generatePreviewAlias(name2) : void 0);
if (!args.dryRun) {
(0, import_node_assert22.default)(accountId, "Missing account ID");
await verifyWorkerMatchesCITag(
config,
accountId,
name2,
config.configPath
);
}
const { versionId, workerTag, versionPreviewUrl, versionPreviewAliasUrl } = await versionsUpload({
config,
accountId,
name: name2,
rules: getRules(config),
entry,
legacyEnv: isLegacyEnv(config),
env: args.env,
compatibilityDate: args.latest ? formatCompatibilityDate(/* @__PURE__ */ new Date()) : args.compatibilityDate,
compatibilityFlags: args.compatibilityFlags,
vars: cliVars,
defines: cliDefines,
alias: cliAlias,
jsxFactory: args.jsxFactory,
jsxFragment: args.jsxFragment,
tsconfig: args.tsconfig,
assetsOptions,
minify: args.minify,
uploadSourceMaps: args.uploadSourceMaps,
isWorkersSite: Boolean(args.site || config.site),
outDir: args.outdir,
dryRun: args.dryRun,
noBundle: !(args.bundle ?? !config.no_bundle),
keepVars: false,
projectRoot: entry.projectRoot,
tag: args.tag,
message: args.message,
previewAlias,
experimentalAutoCreate: args.experimentalAutoCreate,
outFile: args.outfile
});
writeOutput({
type: "version-upload",
version: 1,
worker_name: name2 ?? null,
worker_tag: workerTag,
version_id: versionId,
preview_url: versionPreviewUrl,
preview_alias_url: versionPreviewAliasUrl,
wrangler_environment: args.env,
worker_name_overridden: workerNameOverridden
});
}, "versionsUploadHandler")
});
__name(versionsUpload, "versionsUpload");
__name(formatTime3, "formatTime");
MAX_DNS_LABEL_LENGTH = 63;
HASH_LENGTH = 4;
ALIAS_VALIDATION_REGEX = /^[a-z](?:[a-z0-9-]*[a-z0-9])?$/i;
__name(sanitizeBranchName, "sanitizeBranchName");
__name(getBranchName, "getBranchName");
__name(createTruncatedAlias, "createTruncatedAlias");
__name(generatePreviewAlias, "generatePreviewAlias");
}
});
// src/versions/view.ts
function printBindingAsToml(binding) {
switch (binding.type) {
case "ai":
return `[ai]
binding = ${binding.name}`;
case "analytics_engine":
return `[[analytics_engine_datasets]]
binding = ${binding.name}` + (binding.dataset ? `
dataset = ${binding.dataset}` : "");
case "browser":
return `[browser]
binding = "${binding.name}"`;
case "d1":
return `[[d1_databases]]
binding = "${binding.name}"
database_id = "${binding.id}"`;
case "dispatch_namespace":
return `[[dispatch_namespaces]]
binding = "${binding.name}"
namespce = "${binding.namespace}"` + (binding.outbound ? `
outbound = { service = "${binding.outbound.worker.service}"` + (binding.outbound.params ? `, parameters = [${binding.outbound.params.map((param) => param.name).join(", ")}]` : "") + " }" : "");
case "durable_object_namespace":
return `[[durable_objects.bindings]]
name = "${binding.name}"
class_name = "${binding.class_name}"` + (binding.script_name ? `
script_name = "${binding.script_name}"` : "");
case "hyperdrive":
return `[[hyperdrive]]
binding = "${binding.name}"
id = "${binding.id}"`;
case "kv_namespace":
return `[[kv_namespaces]]
binding = "${binding.name}"
id = "${binding.namespace_id}"`;
case "mtls_certificate":
return `[[mtls_certificates]]
binding = "${binding.name}"
certificate_id = "${binding.certificate_id}"`;
case "queue":
return `[[queues.producers]]
binding = "${binding.name}"
queue = "${binding.queue_name}"` + (binding.delivery_delay ? `
delivery_delay = ${binding.delivery_delay}` : "");
case "r2_bucket":
return `[[r2_buckets]]
binding = "${binding.name}"
bucket_name = "${binding.bucket_name}"` + (binding.jurisdiction ? `
jurisdiction = "${binding.jurisdiction}"` : "");
case "send_email":
return `[[send_email]]
name = "${binding.name}"` + (binding.destination_address ? `
destination_address = "${binding.destination_address}"` : "") + (binding.allowed_destination_addresses ? `
allowed_destination_addresses = [${binding.allowed_destination_addresses.map((addr) => `"${addr}"`).join(", ")}]` : "");
case "service":
return `[[services]]
binding = "${binding.name}"
service = "${binding.name}"` + (binding.entrypoint ? `
entrypoint = "${binding.entrypoint}"` : "");
case "vectorize":
return `[[vectorize]]
binding = "${binding.name}"
index_name = "${binding.index_name}"`;
case "version_metadata":
return `[version_metadata]
binding = "${binding.name}"`;
default:
return null;
}
}
var BLANK_INPUT5, versionsViewCommand;
var init_view2 = __esm({
"src/versions/view.ts"() {
init_import_meta_url();
init_cli();
init_create_command();
init_errors();
init_metrics();
init_user2();
init_render_labelled_values();
init_api();
init_list9();
BLANK_INPUT5 = "-";
versionsViewCommand = createCommand({
metadata: {
description: "View the details of a specific version of your Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
behaviour: {
printBanner: /* @__PURE__ */ __name((args) => !args.json, "printBanner")
},
args: {
"version-id": {
describe: "The Worker Version ID to view",
type: "string",
requiresArg: true,
demandOption: true
},
name: {
describe: "Name of the worker",
type: "string",
requiresArg: true
},
json: {
describe: "Display output as clean JSON",
type: "boolean",
default: false
}
},
positionalArgs: ["version-id"],
handler: /* @__PURE__ */ __name(async function versionsViewHandler(args, { config }) {
sendMetricsEvent(
"view worker version",
{},
{
sendMetrics: config.send_metrics
}
);
const accountId = await requireAuth(config);
const workerName = args.name ?? config.name;
if (workerName === void 0) {
throw new UserError(
'You need to provide a name of your worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`',
{ telemetryMessage: true }
);
}
const version5 = await fetchVersion(
config,
accountId,
workerName,
args.versionId
);
if (args.json) {
logRaw(JSON.stringify(version5, null, 2));
return;
}
logRaw(
formatLabelledValues({
"Version ID": version5.id,
Created: new Date(version5.metadata["created_on"]).toISOString(),
Author: version5.metadata.author_email,
Source: getVersionSource(version5),
Tag: version5.annotations?.["workers/tag"] || BLANK_INPUT5,
Message: version5.annotations?.["workers/message"] || BLANK_INPUT5
})
);
const scriptInfo = {};
if (version5.resources.script.handlers) {
scriptInfo.Handlers = version5.resources.script.handlers.join(", ");
}
if (version5.resources.script_runtime.compatibility_date) {
scriptInfo["Compatibility Date"] = version5.resources.script_runtime.compatibility_date;
}
if (version5.resources.script_runtime.compatibility_flags) {
scriptInfo["Compatibility Flags"] = version5.resources.script_runtime.compatibility_flags.join(", ");
}
if (Object.keys(scriptInfo).length > 0) {
logRaw("------------------------------------------------------------");
logRaw(formatLabelledValues(scriptInfo));
}
const secrets = version5.resources.bindings.filter(
(binding) => binding.type === "secret_text"
);
if (secrets.length > 0) {
logRaw("------------------------- secrets -------------------------");
for (const secret of secrets) {
logRaw(
formatLabelledValues({
"Secret Name": secret.name
})
);
}
}
const bindings = version5.resources.bindings.filter(
(binding) => binding.type !== "secret_text"
);
if (bindings.length > 0) {
logRaw("------------------------- bindings -------------------------");
const envVars = bindings.filter(
(binding) => binding.type === "plain_text"
);
if (envVars.length > 0) {
logRaw(
`[vars]
` + // ts is having issues typing from the filter
envVars.map((envVar) => `${envVar.name} = "${envVar.text}"`).join("\n")
);
}
const restOfBindings = bindings.filter(
(binding) => binding.type !== "plain_text"
);
for (const binding of restOfBindings) {
const output = printBindingAsToml(binding);
if (output !== null) {
logRaw(output);
logRaw("");
}
}
}
}, "versionsViewHandler")
});
__name(printBindingAsToml, "printBindingAsToml");
}
});
// src/workflows/index.ts
var workflowsNamespace, workflowsInstanceNamespace;
var init_workflows = __esm({
"src/workflows/index.ts"() {
init_import_meta_url();
init_create_command();
workflowsNamespace = createNamespace({
metadata: {
description: "\u{1F501} Manage Workflows",
owner: "Product: Workflows",
status: "stable"
}
});
workflowsInstanceNamespace = createNamespace({
metadata: {
description: "Manage Workflow instances",
owner: "Product: Workflows",
status: "stable"
}
});
}
});
// src/workflows/commands/delete.ts
var workflowsDeleteCommand;
var init_delete10 = __esm({
"src/workflows/commands/delete.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
workflowsDeleteCommand = createCommand({
metadata: {
description: "Delete workflow - when deleting a workflow, it will also delete it's own instances",
owner: "Product: Workflows",
status: "stable"
},
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
await fetchResult(config, `/accounts/${accountId}/workflows/${args.name}`, {
method: "DELETE"
});
logger.log(
`\u2705 Workflow "${args.name}" removed successfully.
Note that running instances might take a few minutes to be properly terminated.`
);
}
});
}
});
// src/workflows/commands/describe.ts
var workflowsDescribeCommand;
var init_describe = __esm({
"src/workflows/commands/describe.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_cfetch();
init_create_command();
init_user2();
init_render_labelled_values();
workflowsDescribeCommand = createCommand({
metadata: {
description: "Describe Workflow resource",
owner: "Product: Workflows",
status: "stable"
},
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
}
},
positionalArgs: ["name"],
async handler(args, { config }) {
const accountId = await requireAuth(config);
const workflow = await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}`
);
const versions2 = await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/versions`
);
const latestVersion = versions2[0];
logRaw(
formatLabelledValues({
Name: workflow.name,
Id: workflow.id,
"Script Name": workflow.script_name,
"Class Name": workflow.class_name,
"Created On": workflow.created_on,
"Modified On": workflow.modified_on
})
);
logRaw(white("Latest Version:"));
logRaw(
formatLabelledValues(
{
Id: latestVersion.id,
"Created On": workflow.created_on,
"Modified On": workflow.modified_on
},
{ indentationCount: 2 }
)
);
}
});
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constants.js
var daysInYear, maxTime, minTime, millisecondsInMinute, minutesInYear, minutesInMonth, minutesInDay, secondsInHour, secondsInDay, secondsInWeek, secondsInYear, secondsInMonth, secondsInQuarter, constructFromSymbol;
var init_constants19 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constants.js"() {
init_import_meta_url();
daysInYear = 365.2425;
maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1e3;
minTime = -maxTime;
millisecondsInMinute = 6e4;
minutesInYear = 525600;
minutesInMonth = 43200;
minutesInDay = 1440;
secondsInHour = 3600;
secondsInDay = secondsInHour * 24;
secondsInWeek = secondsInDay * 7;
secondsInYear = secondsInDay * daysInYear;
secondsInMonth = secondsInYear / 12;
secondsInQuarter = secondsInMonth * 3;
constructFromSymbol = Symbol.for("constructDateFrom");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.js
function constructFrom(date, value) {
if (typeof date === "function") return date(value);
if (date && typeof date === "object" && constructFromSymbol in date)
return date[constructFromSymbol](value);
if (date instanceof Date) return new date.constructor(value);
return new Date(value);
}
var init_constructFrom = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.js"() {
init_import_meta_url();
init_constants19();
__name(constructFrom, "constructFrom");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.js
function toDate3(argument, context2) {
return constructFrom(context2 || argument, argument);
}
var init_toDate = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.js"() {
init_import_meta_url();
init_constructFrom();
__name(toDate3, "toDate");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addDays.js
var init_addDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMonths.js
var init_addMonths = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMonths.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/add.js
var init_add3 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/add.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSaturday.js
var init_isSaturday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSaturday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSunday.js
var init_isSunday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSunday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWeekend.js
var init_isWeekend = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWeekend.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addBusinessDays.js
var init_addBusinessDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addBusinessDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMilliseconds.js
function addMilliseconds(date, amount, options) {
return constructFrom(options?.in || date, +toDate3(date) + amount);
}
var init_addMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMilliseconds.js"() {
init_import_meta_url();
init_constructFrom();
init_toDate();
__name(addMilliseconds, "addMilliseconds");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addHours.js
var init_addHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.js
function getDefaultOptions() {
return defaultOptions2;
}
var defaultOptions2;
var init_defaultOptions = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.js"() {
init_import_meta_url();
defaultOptions2 = {};
__name(getDefaultOptions, "getDefaultOptions");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeek.js
var init_startOfWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeek.js
var init_startOfISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeekYear.js
var init_getISOWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js
function getTimezoneOffsetInMilliseconds(date) {
const _date = toDate3(date);
const utcDate = new Date(
Date.UTC(
_date.getFullYear(),
_date.getMonth(),
_date.getDate(),
_date.getHours(),
_date.getMinutes(),
_date.getSeconds(),
_date.getMilliseconds()
)
);
utcDate.setUTCFullYear(_date.getFullYear());
return +date - +utcDate;
}
var init_getTimezoneOffsetInMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js"() {
init_import_meta_url();
init_toDate();
__name(getTimezoneOffsetInMilliseconds, "getTimezoneOffsetInMilliseconds");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.js
function normalizeDates(context2, ...dates) {
const normalize5 = constructFrom.bind(
null,
context2 || dates.find((date) => typeof date === "object")
);
return dates.map(normalize5);
}
var init_normalizeDates = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.js"() {
init_import_meta_url();
init_constructFrom();
__name(normalizeDates, "normalizeDates");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDay.js
var init_startOfDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarDays.js
var init_differenceInCalendarDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeekYear.js
var init_startOfISOWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeekYear.js
var init_setISOWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addISOWeekYears.js
var init_addISOWeekYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addISOWeekYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMinutes.js
var init_addMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addQuarters.js
var init_addQuarters = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addQuarters.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addSeconds.js
var init_addSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addWeeks.js
var init_addWeeks = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addWeeks.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addYears.js
var init_addYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/areIntervalsOverlapping.js
var init_areIntervalsOverlapping = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/areIntervalsOverlapping.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/max.js
var init_max = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/max.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/min.js
var init_min = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/min.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/clamp.js
var init_clamp = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/clamp.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestIndexTo.js
var init_closestIndexTo = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestIndexTo.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestTo.js
var init_closestTo = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestTo.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.js
function compareAsc(dateLeft, dateRight) {
const diff = +toDate3(dateLeft) - +toDate3(dateRight);
if (diff < 0) return -1;
else if (diff > 0) return 1;
return diff;
}
var init_compareAsc = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.js"() {
init_import_meta_url();
init_toDate();
__name(compareAsc, "compareAsc");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareDesc.js
var init_compareDesc = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareDesc.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.js
function constructNow(date) {
return constructFrom(date, Date.now());
}
var init_constructNow = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.js"() {
init_import_meta_url();
init_constructFrom();
__name(constructNow, "constructNow");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/daysToWeeks.js
var init_daysToWeeks = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/daysToWeeks.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameDay.js
var init_isSameDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isDate.js
var init_isDate = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isDate.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isValid.js
var init_isValid = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isValid.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInBusinessDays.js
var init_differenceInBusinessDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInBusinessDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeekYears.js
var init_differenceInCalendarISOWeekYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeekYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeeks.js
var init_differenceInCalendarISOWeeks = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeeks.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarMonths.js
var init_differenceInCalendarMonths = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarMonths.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getQuarter.js
var init_getQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarQuarters.js
var init_differenceInCalendarQuarters = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarQuarters.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarWeeks.js
var init_differenceInCalendarWeeks = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarWeeks.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarYears.js
var init_differenceInCalendarYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInDays.js
var init_differenceInDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.js
function getRoundingMethod(method) {
return (number) => {
const round = method ? Math[method] : Math.trunc;
const result = round(number);
return result === 0 ? 0 : result;
};
}
var init_getRoundingMethod = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.js"() {
init_import_meta_url();
__name(getRoundingMethod, "getRoundingMethod");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInHours.js
var init_differenceInHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subISOWeekYears.js
var init_subISOWeekYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subISOWeekYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInISOWeekYears.js
var init_differenceInISOWeekYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInISOWeekYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMilliseconds.js
var init_differenceInMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMinutes.js
var init_differenceInMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDay.js
var init_endOfDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMonth.js
var init_endOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLastDayOfMonth.js
var init_isLastDayOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLastDayOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMonths.js
var init_differenceInMonths = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMonths.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInQuarters.js
var init_differenceInQuarters = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInQuarters.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInSeconds.js
var init_differenceInSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInWeeks.js
var init_differenceInWeeks = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInWeeks.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInYears.js
var init_differenceInYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachDayOfInterval.js
var init_eachDayOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachDayOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachHourOfInterval.js
var init_eachHourOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachHourOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMinuteOfInterval.js
var init_eachMinuteOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMinuteOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMonthOfInterval.js
var init_eachMonthOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMonthOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfQuarter.js
var init_startOfQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachQuarterOfInterval.js
var init_eachQuarterOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachQuarterOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekOfInterval.js
var init_eachWeekOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfInterval.js
var init_eachWeekendOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMonth.js
var init_startOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfMonth.js
var init_eachWeekendOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYear.js
var init_endOfYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYear.js
var init_startOfYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfYear.js
var init_eachWeekendOfYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachYearOfInterval.js
var init_eachYearOfInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachYearOfInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDecade.js
var init_endOfDecade = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDecade.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfHour.js
var init_endOfHour = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfHour.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfWeek.js
var init_endOfWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeek.js
var init_endOfISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeekYear.js
var init_endOfISOWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMinute.js
var init_endOfMinute = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMinute.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfQuarter.js
var init_endOfQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfSecond.js
var init_endOfSecond = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfSecond.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfToday.js
var init_endOfToday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfToday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfTomorrow.js
var init_endOfTomorrow = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfTomorrow.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYesterday.js
var init_endOfYesterday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYesterday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatDistance.js
var formatDistanceLocale, formatDistance;
var init_formatDistance = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatDistance.js"() {
init_import_meta_url();
formatDistanceLocale = {
lessThanXSeconds: {
one: "less than a second",
other: "less than {{count}} seconds"
},
xSeconds: {
one: "1 second",
other: "{{count}} seconds"
},
halfAMinute: "half a minute",
lessThanXMinutes: {
one: "less than a minute",
other: "less than {{count}} minutes"
},
xMinutes: {
one: "1 minute",
other: "{{count}} minutes"
},
aboutXHours: {
one: "about 1 hour",
other: "about {{count}} hours"
},
xHours: {
one: "1 hour",
other: "{{count}} hours"
},
xDays: {
one: "1 day",
other: "{{count}} days"
},
aboutXWeeks: {
one: "about 1 week",
other: "about {{count}} weeks"
},
xWeeks: {
one: "1 week",
other: "{{count}} weeks"
},
aboutXMonths: {
one: "about 1 month",
other: "about {{count}} months"
},
xMonths: {
one: "1 month",
other: "{{count}} months"
},
aboutXYears: {
one: "about 1 year",
other: "about {{count}} years"
},
xYears: {
one: "1 year",
other: "{{count}} years"
},
overXYears: {
one: "over 1 year",
other: "over {{count}} years"
},
almostXYears: {
one: "almost 1 year",
other: "almost {{count}} years"
}
};
formatDistance = /* @__PURE__ */ __name((token, count, options) => {
let result;
const tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === "string") {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace("{{count}}", count.toString());
}
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
return "in " + result;
} else {
return result + " ago";
}
}
return result;
}, "formatDistance");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildFormatLongFn.js
function buildFormatLongFn(args) {
return (options = {}) => {
const width = options.width ? String(options.width) : args.defaultWidth;
const format9 = args.formats[width] || args.formats[args.defaultWidth];
return format9;
};
}
var init_buildFormatLongFn = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildFormatLongFn.js"() {
init_import_meta_url();
__name(buildFormatLongFn, "buildFormatLongFn");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatLong.js
var dateFormats, timeFormats, dateTimeFormats, formatLong;
var init_formatLong = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatLong.js"() {
init_import_meta_url();
init_buildFormatLongFn();
dateFormats = {
full: "EEEE, MMMM do, y",
long: "MMMM do, y",
medium: "MMM d, y",
short: "MM/dd/yyyy"
};
timeFormats = {
full: "h:mm:ss a zzzz",
long: "h:mm:ss a z",
medium: "h:mm:ss a",
short: "h:mm a"
};
dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: "{{date}}, {{time}}",
short: "{{date}}, {{time}}"
};
formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: "full"
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: "full"
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: "full"
})
};
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatRelative.js
var formatRelativeLocale, formatRelative;
var init_formatRelative = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatRelative.js"() {
init_import_meta_url();
formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: "P"
};
formatRelative = /* @__PURE__ */ __name((token, _date, _baseDate, _options) => formatRelativeLocale[token], "formatRelative");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildLocalizeFn.js
function buildLocalizeFn(args) {
return (value, options) => {
const context2 = options?.context ? String(options.context) : "standalone";
let valuesArray;
if (context2 === "formatting" && args.formattingValues) {
const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
const width = options?.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
const defaultWidth = args.defaultWidth;
const width = options?.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[width] || args.values[defaultWidth];
}
const index = args.argumentCallback ? args.argumentCallback(value) : value;
return valuesArray[index];
};
}
var init_buildLocalizeFn = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildLocalizeFn.js"() {
init_import_meta_url();
__name(buildLocalizeFn, "buildLocalizeFn");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/localize.js
var eraValues, quarterValues, monthValues, dayValues, dayPeriodValues, formattingDayPeriodValues, ordinalNumber, localize;
var init_localize = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/localize.js"() {
init_import_meta_url();
init_buildLocalizeFn();
eraValues = {
narrow: ["B", "A"],
abbreviated: ["BC", "AD"],
wide: ["Before Christ", "Anno Domini"]
};
quarterValues = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["Q1", "Q2", "Q3", "Q4"],
wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
monthValues = {
narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
abbreviated: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
wide: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
};
dayValues = {
narrow: ["S", "M", "T", "W", "T", "F", "S"],
short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
wide: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]
};
dayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
}
};
formattingDayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
}
};
ordinalNumber = /* @__PURE__ */ __name((dirtyNumber, _options) => {
const number = Number(dirtyNumber);
const rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + "st";
case 2:
return number + "nd";
case 3:
return number + "rd";
}
}
return number + "th";
}, "ordinalNumber");
localize = {
ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: "wide"
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: "wide",
argumentCallback: /* @__PURE__ */ __name((quarter) => quarter - 1, "argumentCallback")
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: "wide"
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: "wide"
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: "wide",
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: "wide"
})
};
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchFn.js
function buildMatchFn(args) {
return (string, options = {}) => {
const width = options.width;
const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
const matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
const matchedString = matchResult[0];
const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
const key = Array.isArray(parsePatterns) ? findIndex2(parsePatterns, (pattern) => pattern.test(matchedString)) : (
// [TODO] -- I challenge you to fix the type
findKey(parsePatterns, (pattern) => pattern.test(matchedString))
);
let value;
value = args.valueCallback ? args.valueCallback(key) : key;
value = options.valueCallback ? (
// [TODO] -- I challenge you to fix the type
options.valueCallback(value)
) : value;
const rest = string.slice(matchedString.length);
return { value, rest };
};
}
function findKey(object, predicate) {
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) {
return key;
}
}
return void 0;
}
function findIndex2(array, predicate) {
for (let key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
return void 0;
}
var init_buildMatchFn = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchFn.js"() {
init_import_meta_url();
__name(buildMatchFn, "buildMatchFn");
__name(findKey, "findKey");
__name(findIndex2, "findIndex");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchPatternFn.js
function buildMatchPatternFn(args) {
return (string, options = {}) => {
const matchResult = string.match(args.matchPattern);
if (!matchResult) return null;
const matchedString = matchResult[0];
const parseResult = string.match(args.parsePattern);
if (!parseResult) return null;
let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
const rest = string.slice(matchedString.length);
return { value, rest };
};
}
var init_buildMatchPatternFn = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchPatternFn.js"() {
init_import_meta_url();
__name(buildMatchPatternFn, "buildMatchPatternFn");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/match.js
var matchOrdinalNumberPattern, parseOrdinalNumberPattern, matchEraPatterns, parseEraPatterns, matchQuarterPatterns, parseQuarterPatterns, matchMonthPatterns, parseMonthPatterns, matchDayPatterns, parseDayPatterns, matchDayPeriodPatterns, parseDayPeriodPatterns, match;
var init_match = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/match.js"() {
init_import_meta_url();
init_buildMatchFn();
init_buildMatchPatternFn();
matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
parseOrdinalNumberPattern = /\d+/i;
matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
parseMonthPatterns = {
narrow: [
/^j/i,
/^f/i,
/^m/i,
/^a/i,
/^m/i,
/^j/i,
/^j/i,
/^a/i,
/^s/i,
/^o/i,
/^n/i,
/^d/i
],
any: [
/^ja/i,
/^f/i,
/^mar/i,
/^ap/i,
/^may/i,
/^jun/i,
/^jul/i,
/^au/i,
/^s/i,
/^o/i,
/^n/i,
/^d/i
]
};
matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: /* @__PURE__ */ __name((value) => parseInt(value, 10), "valueCallback")
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseEraPatterns,
defaultParseWidth: "any"
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseQuarterPatterns,
defaultParseWidth: "any",
valueCallback: /* @__PURE__ */ __name((index) => index + 1, "valueCallback")
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseMonthPatterns,
defaultParseWidth: "any"
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseDayPatterns,
defaultParseWidth: "any"
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: "any",
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: "any"
})
};
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US.js
var enUS;
var init_en_US2 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US.js"() {
init_import_meta_url();
init_formatDistance();
init_formatLong();
init_formatRelative();
init_localize();
init_match();
enUS = {
code: "en-US",
formatDistance,
formatLong,
formatRelative,
localize,
match,
options: {
weekStartsOn: 0,
firstWeekContainsDate: 1
}
};
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultLocale.js
var init_defaultLocale = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultLocale.js"() {
init_import_meta_url();
init_en_US2();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDayOfYear.js
var init_getDayOfYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDayOfYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeek.js
var init_getISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekYear.js
var init_getWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeekYear.js
var init_startOfWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeek.js
var init_getWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/format.js
var init_format3 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/format.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistance.js
var init_formatDistance2 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistance.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceStrict.js
function formatDistanceStrict(laterDate, earlierDate, options) {
const defaultOptions3 = getDefaultOptions();
const locale = options?.locale ?? defaultOptions3.locale ?? enUS;
const comparison = compareAsc(laterDate, earlierDate);
if (isNaN(comparison)) {
throw new RangeError("Invalid time value");
}
const localizeOptions = Object.assign({}, options, {
addSuffix: options?.addSuffix,
comparison
});
const [laterDate_, earlierDate_] = normalizeDates(
options?.in,
...comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]
);
const roundingMethod = getRoundingMethod(options?.roundingMethod ?? "round");
const milliseconds = earlierDate_.getTime() - laterDate_.getTime();
const minutes = milliseconds / millisecondsInMinute;
const timezoneOffset = getTimezoneOffsetInMilliseconds(earlierDate_) - getTimezoneOffsetInMilliseconds(laterDate_);
const dstNormalizedMinutes = (milliseconds - timezoneOffset) / millisecondsInMinute;
const defaultUnit = options?.unit;
let unit;
if (!defaultUnit) {
if (minutes < 1) {
unit = "second";
} else if (minutes < 60) {
unit = "minute";
} else if (minutes < minutesInDay) {
unit = "hour";
} else if (dstNormalizedMinutes < minutesInMonth) {
unit = "day";
} else if (dstNormalizedMinutes < minutesInYear) {
unit = "month";
} else {
unit = "year";
}
} else {
unit = defaultUnit;
}
if (unit === "second") {
const seconds = roundingMethod(milliseconds / 1e3);
return locale.formatDistance("xSeconds", seconds, localizeOptions);
} else if (unit === "minute") {
const roundedMinutes = roundingMethod(minutes);
return locale.formatDistance("xMinutes", roundedMinutes, localizeOptions);
} else if (unit === "hour") {
const hours = roundingMethod(minutes / 60);
return locale.formatDistance("xHours", hours, localizeOptions);
} else if (unit === "day") {
const days = roundingMethod(dstNormalizedMinutes / minutesInDay);
return locale.formatDistance("xDays", days, localizeOptions);
} else if (unit === "month") {
const months = roundingMethod(dstNormalizedMinutes / minutesInMonth);
return months === 12 && defaultUnit !== "month" ? locale.formatDistance("xYears", 1, localizeOptions) : locale.formatDistance("xMonths", months, localizeOptions);
} else {
const years = roundingMethod(dstNormalizedMinutes / minutesInYear);
return locale.formatDistance("xYears", years, localizeOptions);
}
}
var init_formatDistanceStrict = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceStrict.js"() {
init_import_meta_url();
init_defaultLocale();
init_defaultOptions();
init_getRoundingMethod();
init_getTimezoneOffsetInMilliseconds();
init_normalizeDates();
init_compareAsc();
init_constants19();
__name(formatDistanceStrict, "formatDistanceStrict");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNow.js
var init_formatDistanceToNow = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNow.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNowStrict.js
function formatDistanceToNowStrict(date, options) {
return formatDistanceStrict(date, constructNow(date), options);
}
var init_formatDistanceToNowStrict = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNowStrict.js"() {
init_import_meta_url();
init_constructNow();
init_formatDistanceStrict();
__name(formatDistanceToNowStrict, "formatDistanceToNowStrict");
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDuration.js
var init_formatDuration = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDuration.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO.js
var init_formatISO = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO9075.js
var init_formatISO9075 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO9075.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISODuration.js
var init_formatISODuration = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISODuration.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC3339.js
var init_formatRFC3339 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC3339.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC7231.js
var init_formatRFC7231 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC7231.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRelative.js
var init_formatRelative2 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRelative.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/fromUnixTime.js
var init_fromUnixTime = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/fromUnixTime.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDate.js
var init_getDate = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDate.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDay.js
var init_getDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInMonth.js
var init_getDaysInMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLeapYear.js
var init_isLeapYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLeapYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInYear.js
var init_getDaysInYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDecade.js
var init_getDecade = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDecade.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDefaultOptions.js
var init_getDefaultOptions = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDefaultOptions.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getHours.js
var init_getHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISODay.js
var init_getISODay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISODay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeeksInYear.js
var init_getISOWeeksInYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeeksInYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMilliseconds.js
var init_getMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMinutes.js
var init_getMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMonth.js
var init_getMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getOverlappingDaysInIntervals.js
var init_getOverlappingDaysInIntervals = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getOverlappingDaysInIntervals.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getSeconds.js
var init_getSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getTime.js
var init_getTime = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getTime.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getUnixTime.js
var init_getUnixTime = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getUnixTime.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekOfMonth.js
var init_getWeekOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfMonth.js
var init_lastDayOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeeksInMonth.js
var init_getWeeksInMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeeksInMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getYear.js
var init_getYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMilliseconds.js
var init_hoursToMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMinutes.js
var init_hoursToMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToSeconds.js
var init_hoursToSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/interval.js
var init_interval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/interval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intervalToDuration.js
var init_intervalToDuration = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intervalToDuration.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormat.js
var init_intlFormat = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormat.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormatDistance.js
var init_intlFormatDistance = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormatDistance.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isAfter.js
var init_isAfter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isAfter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isBefore.js
var init_isBefore = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isBefore.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isEqual.js
var init_isEqual = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isEqual.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isExists.js
var init_isExists = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isExists.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFirstDayOfMonth.js
var init_isFirstDayOfMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFirstDayOfMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFriday.js
var init_isFriday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFriday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFuture.js
var init_isFuture = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFuture.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/transpose.js
var init_transpose = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/transpose.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeek.js
var init_setWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeek.js
var init_setISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDay.js
var init_setDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISODay.js
var init_setISODay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISODay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse.js
var init_parse2 = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMatch.js
var init_isMatch = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMatch.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMonday.js
var init_isMonday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMonday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isPast.js
var init_isPast = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isPast.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfHour.js
var init_startOfHour = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfHour.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameHour.js
var init_isSameHour = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameHour.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameWeek.js
var init_isSameWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeek.js
var init_isSameISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeekYear.js
var init_isSameISOWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMinute.js
var init_startOfMinute = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMinute.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMinute.js
var init_isSameMinute = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMinute.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMonth.js
var init_isSameMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameQuarter.js
var init_isSameQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfSecond.js
var init_startOfSecond = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfSecond.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameSecond.js
var init_isSameSecond = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameSecond.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameYear.js
var init_isSameYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisHour.js
var init_isThisHour = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisHour.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisISOWeek.js
var init_isThisISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMinute.js
var init_isThisMinute = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMinute.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMonth.js
var init_isThisMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisQuarter.js
var init_isThisQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisSecond.js
var init_isThisSecond = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisSecond.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisWeek.js
var init_isThisWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisYear.js
var init_isThisYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThursday.js
var init_isThursday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThursday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isToday.js
var init_isToday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isToday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTomorrow.js
var init_isTomorrow = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTomorrow.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTuesday.js
var init_isTuesday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTuesday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWednesday.js
var init_isWednesday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWednesday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWithinInterval.js
var init_isWithinInterval = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWithinInterval.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subDays.js
var init_subDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isYesterday.js
var init_isYesterday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isYesterday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfDecade.js
var init_lastDayOfDecade = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfDecade.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfWeek.js
var init_lastDayOfWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeek.js
var init_lastDayOfISOWeek = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeek.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeekYear.js
var init_lastDayOfISOWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfQuarter.js
var init_lastDayOfQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfYear.js
var init_lastDayOfYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lightFormat.js
var init_lightFormat = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lightFormat.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/milliseconds.js
var init_milliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/milliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToHours.js
var init_millisecondsToHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToMinutes.js
var init_millisecondsToMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToSeconds.js
var init_millisecondsToSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToHours.js
var init_minutesToHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToMilliseconds.js
var init_minutesToMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToSeconds.js
var init_minutesToSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToQuarters.js
var init_monthsToQuarters = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToQuarters.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToYears.js
var init_monthsToYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextDay.js
var init_nextDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextFriday.js
var init_nextFriday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextFriday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextMonday.js
var init_nextMonday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextMonday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSaturday.js
var init_nextSaturday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSaturday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSunday.js
var init_nextSunday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSunday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextThursday.js
var init_nextThursday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextThursday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextTuesday.js
var init_nextTuesday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextTuesday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextWednesday.js
var init_nextWednesday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextWednesday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseISO.js
var init_parseISO = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseISO.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseJSON.js
var init_parseJSON = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseJSON.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousDay.js
var init_previousDay = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousDay.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousFriday.js
var init_previousFriday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousFriday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousMonday.js
var init_previousMonday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousMonday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSaturday.js
var init_previousSaturday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSaturday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSunday.js
var init_previousSunday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSunday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousThursday.js
var init_previousThursday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousThursday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousTuesday.js
var init_previousTuesday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousTuesday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousWednesday.js
var init_previousWednesday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousWednesday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToMonths.js
var init_quartersToMonths = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToMonths.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToYears.js
var init_quartersToYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestHours.js
var init_roundToNearestHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestMinutes.js
var init_roundToNearestMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToHours.js
var init_secondsToHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMilliseconds.js
var init_secondsToMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMinutes.js
var init_secondsToMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMonth.js
var init_setMonth = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMonth.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/set.js
var init_set = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/set.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDate.js
var init_setDate = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDate.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDayOfYear.js
var init_setDayOfYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDayOfYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDefaultOptions.js
var init_setDefaultOptions = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDefaultOptions.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setHours.js
var init_setHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMilliseconds.js
var init_setMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMinutes.js
var init_setMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setQuarter.js
var init_setQuarter = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setQuarter.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setSeconds.js
var init_setSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeekYear.js
var init_setWeekYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeekYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setYear.js
var init_setYear = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setYear.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDecade.js
var init_startOfDecade = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDecade.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfToday.js
var init_startOfToday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfToday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfTomorrow.js
var init_startOfTomorrow = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfTomorrow.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYesterday.js
var init_startOfYesterday = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYesterday.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMonths.js
var init_subMonths = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMonths.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/sub.js
var init_sub = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/sub.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subBusinessDays.js
var init_subBusinessDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subBusinessDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subHours.js
var init_subHours = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subHours.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMilliseconds.js
var init_subMilliseconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMilliseconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMinutes.js
var init_subMinutes = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMinutes.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subQuarters.js
var init_subQuarters = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subQuarters.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subSeconds.js
var init_subSeconds = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subSeconds.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subWeeks.js
var init_subWeeks = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subWeeks.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subYears.js
var init_subYears = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subYears.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/weeksToDays.js
var init_weeksToDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/weeksToDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToDays.js
var init_yearsToDays = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToDays.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToMonths.js
var init_yearsToMonths = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToMonths.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToQuarters.js
var init_yearsToQuarters = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToQuarters.js"() {
init_import_meta_url();
}
});
// ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/index.js
var init_date_fns = __esm({
"../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/index.js"() {
init_import_meta_url();
init_add3();
init_addBusinessDays();
init_addDays();
init_addHours();
init_addISOWeekYears();
init_addMilliseconds();
init_addMinutes();
init_addMonths();
init_addQuarters();
init_addSeconds();
init_addWeeks();
init_addYears();
init_areIntervalsOverlapping();
init_clamp();
init_closestIndexTo();
init_closestTo();
init_compareAsc();
init_compareDesc();
init_constructFrom();
init_constructNow();
init_daysToWeeks();
init_differenceInBusinessDays();
init_differenceInCalendarDays();
init_differenceInCalendarISOWeekYears();
init_differenceInCalendarISOWeeks();
init_differenceInCalendarMonths();
init_differenceInCalendarQuarters();
init_differenceInCalendarWeeks();
init_differenceInCalendarYears();
init_differenceInDays();
init_differenceInHours();
init_differenceInISOWeekYears();
init_differenceInMilliseconds();
init_differenceInMinutes();
init_differenceInMonths();
init_differenceInQuarters();
init_differenceInSeconds();
init_differenceInWeeks();
init_differenceInYears();
init_eachDayOfInterval();
init_eachHourOfInterval();
init_eachMinuteOfInterval();
init_eachMonthOfInterval();
init_eachQuarterOfInterval();
init_eachWeekOfInterval();
init_eachWeekendOfInterval();
init_eachWeekendOfMonth();
init_eachWeekendOfYear();
init_eachYearOfInterval();
init_endOfDay();
init_endOfDecade();
init_endOfHour();
init_endOfISOWeek();
init_endOfISOWeekYear();
init_endOfMinute();
init_endOfMonth();
init_endOfQuarter();
init_endOfSecond();
init_endOfToday();
init_endOfTomorrow();
init_endOfWeek();
init_endOfYear();
init_endOfYesterday();
init_format3();
init_formatDistance2();
init_formatDistanceStrict();
init_formatDistanceToNow();
init_formatDistanceToNowStrict();
init_formatDuration();
init_formatISO();
init_formatISO9075();
init_formatISODuration();
init_formatRFC3339();
init_formatRFC7231();
init_formatRelative2();
init_fromUnixTime();
init_getDate();
init_getDay();
init_getDayOfYear();
init_getDaysInMonth();
init_getDaysInYear();
init_getDecade();
init_getDefaultOptions();
init_getHours();
init_getISODay();
init_getISOWeek();
init_getISOWeekYear();
init_getISOWeeksInYear();
init_getMilliseconds();
init_getMinutes();
init_getMonth();
init_getOverlappingDaysInIntervals();
init_getQuarter();
init_getSeconds();
init_getTime();
init_getUnixTime();
init_getWeek();
init_getWeekOfMonth();
init_getWeekYear();
init_getWeeksInMonth();
init_getYear();
init_hoursToMilliseconds();
init_hoursToMinutes();
init_hoursToSeconds();
init_interval();
init_intervalToDuration();
init_intlFormat();
init_intlFormatDistance();
init_isAfter();
init_isBefore();
init_isDate();
init_isEqual();
init_isExists();
init_isFirstDayOfMonth();
init_isFriday();
init_isFuture();
init_isLastDayOfMonth();
init_isLeapYear();
init_isMatch();
init_isMonday();
init_isPast();
init_isSameDay();
init_isSameHour();
init_isSameISOWeek();
init_isSameISOWeekYear();
init_isSameMinute();
init_isSameMonth();
init_isSameQuarter();
init_isSameSecond();
init_isSameWeek();
init_isSameYear();
init_isSaturday();
init_isSunday();
init_isThisHour();
init_isThisISOWeek();
init_isThisMinute();
init_isThisMonth();
init_isThisQuarter();
init_isThisSecond();
init_isThisWeek();
init_isThisYear();
init_isThursday();
init_isToday();
init_isTomorrow();
init_isTuesday();
init_isValid();
init_isWednesday();
init_isWeekend();
init_isWithinInterval();
init_isYesterday();
init_lastDayOfDecade();
init_lastDayOfISOWeek();
init_lastDayOfISOWeekYear();
init_lastDayOfMonth();
init_lastDayOfQuarter();
init_lastDayOfWeek();
init_lastDayOfYear();
init_lightFormat();
init_max();
init_milliseconds();
init_millisecondsToHours();
init_millisecondsToMinutes();
init_millisecondsToSeconds();
init_min();
init_minutesToHours();
init_minutesToMilliseconds();
init_minutesToSeconds();
init_monthsToQuarters();
init_monthsToYears();
init_nextDay();
init_nextFriday();
init_nextMonday();
init_nextSaturday();
init_nextSunday();
init_nextThursday();
init_nextTuesday();
init_nextWednesday();
init_parse2();
init_parseISO();
init_parseJSON();
init_previousDay();
init_previousFriday();
init_previousMonday();
init_previousSaturday();
init_previousSunday();
init_previousThursday();
init_previousTuesday();
init_previousWednesday();
init_quartersToMonths();
init_quartersToYears();
init_roundToNearestHours();
init_roundToNearestMinutes();
init_secondsToHours();
init_secondsToMilliseconds();
init_secondsToMinutes();
init_set();
init_setDate();
init_setDay();
init_setDayOfYear();
init_setDefaultOptions();
init_setHours();
init_setISODay();
init_setISOWeek();
init_setISOWeekYear();
init_setMilliseconds();
init_setMinutes();
init_setMonth();
init_setQuarter();
init_setSeconds();
init_setWeek();
init_setWeekYear();
init_setYear();
init_startOfDay();
init_startOfDecade();
init_startOfHour();
init_startOfISOWeek();
init_startOfISOWeekYear();
init_startOfMinute();
init_startOfMonth();
init_startOfQuarter();
init_startOfSecond();
init_startOfToday();
init_startOfTomorrow();
init_startOfWeek();
init_startOfWeekYear();
init_startOfYear();
init_startOfYesterday();
init_sub();
init_subBusinessDays();
init_subDays();
init_subHours();
init_subISOWeekYears();
init_subMilliseconds();
init_subMinutes();
init_subMonths();
init_subQuarters();
init_subSeconds();
init_subWeeks();
init_subYears();
init_toDate();
init_transpose();
init_weeksToDays();
init_yearsToDays();
init_yearsToMonths();
init_yearsToQuarters();
}
});
// ../../node_modules/.pnpm/itty-time@1.0.6/node_modules/itty-time/index.mjs
var e6, t6, n5, r6;
var init_itty_time = __esm({
"../../node_modules/.pnpm/itty-time@1.0.6/node_modules/itty-time/index.mjs"() {
init_import_meta_url();
e6 = 36e5;
t6 = 24 * e6;
n5 = { year: 315576e5, month: 30 * t6, week: 7 * t6, day: t6, hour: e6, minute: 6e4, second: 1e3, m: 1 };
r6 = /* @__PURE__ */ __name((e7) => {
if (+e7) return +e7;
const [, t7, r7] = e7.match(/^([^ ]+) +(\w\w*?)s?$/) || [];
return +t7 * (n5[r7] || 1);
}, "r");
}
});
// src/workflows/utils.ts
var emojifyInstanceStatus, emojifyInstanceTriggerName, emojifyStepType, validateStatus;
var init_utils14 = __esm({
"src/workflows/utils.ts"() {
init_import_meta_url();
init_errors();
emojifyInstanceStatus = /* @__PURE__ */ __name((status2) => {
switch (status2) {
case "complete":
return "\u2705 Completed";
case "errored":
return "\u274C Errored";
case "unknown":
return "\u2753 Unknown";
case "paused":
return "\u23F8\uFE0F Paused";
case "queued":
return "\u231B Queued";
case "running":
return "\u25B6 Running";
case "terminated":
return "\u{1F6AB} Terminated";
case "waiting":
return "\u23F0 Waiting";
default:
return "\u2753 Unknown";
}
}, "emojifyInstanceStatus");
emojifyInstanceTriggerName = /* @__PURE__ */ __name((status2) => {
switch (status2) {
case "api":
return "\u{1F30E} API";
case "binding":
return "\u{1F517} Binding";
case "cron":
return "\u231B Cron";
case "event":
return "\u{1F4E9} Event";
default:
return "\u2753 Unknown";
}
}, "emojifyInstanceTriggerName");
emojifyStepType = /* @__PURE__ */ __name((type) => {
switch (type) {
case "step":
return "\u{1F3AF} Step";
case "sleep":
return "\u{1F4A4} Sleeping";
case "termination":
return "\u{1F6AB} Termination";
case "waitForEvent":
return "\u{1F440} Waiting for event";
default:
return "\u2753 Unknown";
}
}, "emojifyStepType");
validateStatus = /* @__PURE__ */ __name((status2) => {
switch (status2) {
case "complete":
return "complete";
case "errored":
return "errored";
case "paused":
return "paused";
case "queued":
return "queued";
case "running":
return "running";
case "terminated":
return "terminated";
default:
throw new UserError(
`Looks like you have provided a invalid status "${status2}". Valid statuses are: queued, running, paused, errored, terminated, complete`
);
}
}, "validateStatus");
}
});
// src/workflows/commands/instances/describe.ts
function logStep(args, step) {
logRaw("");
const formattedStep = {};
if (step.type == "sleep" || step.type == "step" || step.type == "waitForEvent") {
formattedStep.Name = step.name;
formattedStep.Type = emojifyStepType(step.type);
if (step.start != void 0) {
formattedStep.Start = new Date(step.start).toLocaleString();
}
if (step.end != void 0) {
formattedStep.End = new Date(step.end).toLocaleString();
}
if (step.start != null && step.end != null) {
formattedStep.Duration = formatDistanceStrict(
new Date(step.end),
new Date(step.start)
);
} else if (step.start != null) {
formattedStep.Duration = formatDistanceStrict(
new Date(step.start),
new Date((/* @__PURE__ */ new Date()).toUTCString().slice(0, -4))
);
}
} else if (step.type == "termination") {
formattedStep.Type = emojifyStepType(step.type);
formattedStep.Trigger = step.trigger.source;
}
if (step.type == "step") {
if (step.success !== null) {
formattedStep.Success = step.success ? "\u2705 Yes" : "\u274C No";
} else {
formattedStep.Success = "\u25B6 Running";
}
if (step.success === null) {
const latestAttempt = step.attempts.at(-1);
let delay = step.config.retries.delay;
if (latestAttempt !== void 0 && latestAttempt.success === false) {
const endDate = new Date(latestAttempt.end);
if (typeof delay === "string") {
delay = r6(delay);
}
const retryDate = addMilliseconds(endDate, delay);
formattedStep["Retries At"] = `${retryDate.toLocaleString()} (in ${formatDistanceToNowStrict(retryDate)} from now)`;
}
}
}
if (step.type == "step" || step.type == "waitForEvent") {
if (step.output !== void 0 && args.stepOutput) {
let output;
try {
output = JSON.stringify(step.output);
} catch {
output = step.output;
}
formattedStep.Output = output.length > args.truncateOutputLimit ? output.substring(0, args.truncateOutputLimit) + "[...output truncated]" : output;
}
}
logger.log(formatLabelledValues(formattedStep, { indentationCount: 2 }));
if (step.type == "step") {
const prettyAttempts = step.attempts.map((val2) => {
const attempt = {};
attempt.Start = new Date(val2.start).toLocaleString();
attempt.End = val2.end == null ? "" : new Date(val2.end).toLocaleString();
if (val2.start != null && val2.end != null) {
attempt.Duration = formatDistanceStrict(
new Date(val2.end),
new Date(val2.start)
);
} else if (val2.start != null) {
attempt.Duration = formatDistanceStrict(
new Date(val2.start),
new Date((/* @__PURE__ */ new Date()).toUTCString().slice(0, -4))
);
}
attempt.State = val2.success == null ? "\u{1F504} Working" : val2.success ? "\u2705 Success" : "\u274C Error";
if (val2.error != null) {
attempt.Error = red(`${val2.error.name}: ${val2.error.message}`);
}
return attempt;
});
logger.table(prettyAttempts);
}
}
function getLastSuccessfulStep(logs) {
let lastSuccessfulStepName = null;
for (const step of logs.steps) {
switch (step.type) {
case "step":
if (step.success == true) {
lastSuccessfulStepName = step.name;
}
break;
case "sleep":
if (step.end != null) {
lastSuccessfulStepName = step.name;
}
break;
case "termination":
break;
}
}
return lastSuccessfulStepName;
}
var workflowsInstancesDescribeCommand;
var init_describe2 = __esm({
"src/workflows/commands/instances/describe.ts"() {
init_import_meta_url();
init_cli();
init_colors();
init_date_fns();
init_itty_time();
init_cfetch();
init_create_command();
init_logger();
init_user2();
init_render_labelled_values();
init_utils14();
workflowsInstancesDescribeCommand = createCommand({
metadata: {
description: "Describe a workflow instance - see its logs, retries and errors",
owner: "Product: Workflows",
status: "stable"
},
positionalArgs: ["name", "id"],
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
id: {
describe: "ID of the instance - instead of an UUID you can type 'latest' to get the latest instance and describe it",
type: "string",
demandOption: false,
default: "latest"
},
"step-output": {
describe: "Don't output the step output since it might clutter the terminal",
type: "boolean",
default: true
},
"truncate-output-limit": {
describe: "Truncate step output after x characters",
type: "number",
default: 5e3
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
let id = args.id;
if (id == "latest") {
const instances = (await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances`
)).sort((a5, b6) => b6.created_on.localeCompare(a5.created_on));
if (instances.length == 0) {
logger.error(
`There are no deployed instances in workflow "${args.name}"`
);
return;
}
logRaw("Describing latest instance:");
id = instances[0].id;
}
const instance = await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances/${id}`
);
const formattedInstance = {
"Workflow Name": args.name,
"Instance Id": id,
"Version Id": instance.versionId,
Status: emojifyInstanceStatus(instance.status),
Trigger: emojifyInstanceTriggerName(instance.trigger.source),
Queued: new Date(instance.queued).toLocaleString()
};
if (instance.success != null) {
formattedInstance.Success = instance.success ? "\u2705 Yes" : "\u274C No";
}
if (instance.start != void 0) {
formattedInstance.Start = new Date(instance.start).toLocaleString();
}
if (instance.end != void 0) {
formattedInstance.End = new Date(instance.end).toLocaleString();
}
if (instance.start != null && instance.end != null) {
formattedInstance.Duration = formatDistanceStrict(
new Date(instance.end),
new Date(instance.start)
);
} else if (instance.start != null) {
formattedInstance.Duration = formatDistanceStrict(
new Date(instance.start),
new Date((/* @__PURE__ */ new Date()).toUTCString().slice(0, -4))
);
}
const lastSuccessfulStepName = getLastSuccessfulStep(instance);
if (lastSuccessfulStepName != null) {
formattedInstance["Last Successful Step"] = lastSuccessfulStepName;
}
if (instance.error != null) {
formattedInstance.Error = red(
`${instance.error.name}: ${instance.error.message}`
);
}
logRaw(formatLabelledValues(formattedInstance));
logRaw(white("Steps:"));
instance.steps.forEach(logStep.bind(false, args));
}
});
__name(logStep, "logStep");
__name(getLastSuccessfulStep, "getLastSuccessfulStep");
}
});
// src/workflows/commands/instances/list.ts
var workflowsInstancesListCommand;
var init_list12 = __esm({
"src/workflows/commands/instances/list.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
init_utils14();
workflowsInstancesListCommand = createCommand({
metadata: {
description: "Instance related commands (list, describe, terminate, pause, resume)",
owner: "Product: Workflows",
status: "stable"
},
positionalArgs: ["name"],
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
reverse: {
describe: "Reverse order of the instances table",
type: "boolean",
default: false
},
status: {
describe: "Filters list by instance status (can be one of: queued, running, paused, errored, terminated, complete)",
type: "string"
},
page: {
describe: 'Show a sepecific page from the listing, can configure page size using "per-page"',
type: "number",
default: 1
},
"per-page": {
describe: "Configure the maximum number of instances to show per page",
type: "number"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const URLParams = new URLSearchParams();
if (args.status !== void 0) {
const validatedStatus = validateStatus(args.status);
URLParams.set("status", validatedStatus);
}
if (args.perPage !== void 0) {
URLParams.set("per_page", args.perPage.toString());
}
URLParams.set("page", args.page.toString());
const instances = await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances`,
void 0,
URLParams
);
if (instances.length === 0) {
logger.warn(
`There are no instances in workflow "${args.name}". You can trigger it with "wrangler workflows trigger ${args.name}"`
);
return;
}
logger.info(
`Showing ${instances.length} instance${instances.length > 1 ? "s" : ""} from page ${args.page}:`
);
const prettierInstances = instances.sort(
(a5, b6) => args.reverse ? a5.modified_on.localeCompare(b6.modified_on) : b6.modified_on.localeCompare(a5.modified_on)
).map((instance) => ({
Id: instance.id,
Version: instance.version_id,
Created: new Date(instance.created_on).toLocaleString(),
Modified: new Date(instance.modified_on).toLocaleString(),
Status: emojifyInstanceStatus(instance.status)
}));
logger.table(prettierInstances);
}
});
}
});
// src/workflows/commands/instances/pause.ts
var workflowsInstancesPauseCommand;
var init_pause = __esm({
"src/workflows/commands/instances/pause.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
workflowsInstancesPauseCommand = createCommand({
metadata: {
description: "Pause a workflow instance",
owner: "Product: Workflows",
status: "stable"
},
positionalArgs: ["name", "id"],
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
id: {
describe: "ID of the instance - instead of an UUID you can type 'latest' to get the latest instance and pause it",
type: "string",
demandOption: true
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
let id = args.id;
if (id == "latest") {
const instances = (await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances`
)).sort((a5, b6) => b6.created_on.localeCompare(a5.created_on));
if (instances.length == 0) {
logger.error(
`There are no deployed instances in workflow "${args.name}"`
);
return;
}
id = instances[0].id;
}
await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances/${id}/status`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ status: "pause" })
}
);
logger.info(
`\u23F8\uFE0F The instance "${id}" from ${args.name} was paused successfully`
);
}
});
}
});
// src/workflows/commands/instances/resume.ts
var workflowsInstancesResumeCommand;
var init_resume = __esm({
"src/workflows/commands/instances/resume.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
workflowsInstancesResumeCommand = createCommand({
metadata: {
description: "Resume a workflow instance",
owner: "Product: Workflows",
status: "stable"
},
positionalArgs: ["name", "id"],
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
id: {
describe: "ID of the instance - instead of an UUID you can type 'latest' to get the latest instance and resume it",
type: "string",
demandOption: true
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
let id = args.id;
if (id == "latest") {
const instances = (await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances`
)).sort((a5, b6) => b6.created_on.localeCompare(a5.created_on));
if (instances.length == 0) {
logger.error(
`There are no deployed instances in workflow "${args.name}"`
);
return;
}
id = instances[0].id;
}
await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances/${id}/status`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ status: "resume" })
}
);
logger.info(
`\u{1F504} The instance "${id}" from ${args.name} was resumed successfully`
);
}
});
}
});
// src/workflows/commands/instances/terminate.ts
var workflowsInstancesTerminateCommand;
var init_terminate = __esm({
"src/workflows/commands/instances/terminate.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
workflowsInstancesTerminateCommand = createCommand({
metadata: {
description: "Terminate a workflow instance",
owner: "Product: Workflows",
status: "stable"
},
positionalArgs: ["name", "id"],
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
id: {
describe: "ID of the instance - instead of an UUID you can type 'latest' to get the latest instance and describe it",
type: "string",
demandOption: true
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
let id = args.id;
if (id == "latest") {
const instances = (await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances`
)).sort((a5, b6) => b6.created_on.localeCompare(a5.created_on));
if (instances.length == 0) {
logger.error(
`There are no deployed instances in workflow "${args.name}"`
);
return;
}
id = instances[0].id;
}
await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances/${id}/status`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ status: "terminate" })
}
);
logger.info(
`\u{1F977} The instance "${id}" from ${args.name} was terminated successfully`
);
}
});
}
});
// src/workflows/commands/instances/terminate-all.ts
var workflowsInstancesTerminateAllCommand;
var init_terminate_all = __esm({
"src/workflows/commands/instances/terminate-all.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_errors();
init_logger();
init_user2();
workflowsInstancesTerminateAllCommand = createCommand({
metadata: {
description: "Terminate all workflow instances",
owner: "Product: Workflows",
status: "stable",
hidden: true
},
positionalArgs: ["name"],
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
status: {
describe: "Filter instances to be terminated by status",
type: "string"
}
},
validateArgs: /* @__PURE__ */ __name((args) => {
const validStatusToTerminate = [
"queued",
"running",
"paused",
"waitingForPause",
"waiting"
];
if (args.status !== void 0 && !validStatusToTerminate.includes(args.status)) {
throw new CommandLineArgsError(
`Provided status "${args.status}" is not valid, it must be one of the following: ${validStatusToTerminate.join(", ")}.`
);
}
}, "validateArgs"),
async handler(args, { config }) {
const accountId = await requireAuth(config);
const maybeURLQueryString = args.status !== void 0 ? new URLSearchParams({
status: args.status
}) : void 0;
const result = await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances/terminate`,
{
method: "PUT"
},
maybeURLQueryString
);
if (result.status === "ok") {
logger.info(
`\u{1F977} A job to terminate instances from Workflow "${args.name}" ${args.status !== void 0 ? `with status "${args.status}"` : ""} has been started. It might take a few minutes to complete.`
);
return;
}
logger.info(
`\u{1F977} A job to terminate instances from Workflow "${args.name}" ${args.status !== void 0 ? `with status "${args.status}"` : ""} is already running. It might take a few minutes to complete.`
);
}
});
}
});
// src/workflows/commands/list.ts
var workflowsListCommand;
var init_list13 = __esm({
"src/workflows/commands/list.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_logger();
init_user2();
workflowsListCommand = createCommand({
metadata: {
description: "List Workflows associated to account",
owner: "Product: Workflows",
status: "stable"
},
args: {
page: {
describe: 'Show a sepecific page from the listing, can configure page size using "per-page"',
type: "number",
default: 1
},
"per-page": {
describe: "Configure the maximum number of workflows to show per page",
type: "number"
}
},
async handler(args, { config }) {
const accountId = await requireAuth(config);
const URLParams = new URLSearchParams();
if (args.perPage !== void 0) {
URLParams.set("per_page", args.perPage.toString());
}
URLParams.set("page", args.page.toString());
const workflows = await fetchResult(
config,
`/accounts/${accountId}/workflows`,
void 0,
URLParams
);
if (workflows.length === 0) {
logger.warn("There are no deployed Workflows in this account");
} else {
logger.info(
`Showing last ${workflows.length} workflow${workflows.length > 1 ? "s" : ""}:`
);
const prettierWorkflows = workflows.sort((a5, b6) => a5.name.localeCompare(b6.name)).map((workflow) => ({
Name: workflow.name,
"Script name": workflow.script_name,
"Class name": workflow.class_name,
Created: new Date(workflow.created_on).toLocaleString(),
Modified: new Date(workflow.modified_on).toLocaleString()
}));
logger.table(prettierWorkflows);
}
}
});
}
});
// src/workflows/commands/trigger.ts
var workflowsTriggerCommand;
var init_trigger = __esm({
"src/workflows/commands/trigger.ts"() {
init_import_meta_url();
init_cfetch();
init_create_command();
init_user2();
workflowsTriggerCommand = createCommand({
metadata: {
description: "Trigger a workflow, creating a new instance. Can optionally take a JSON string to pass a parameter into the workflow instance",
owner: "Product: Workflows",
status: "stable"
},
args: {
name: {
describe: "Name of the workflow",
type: "string",
demandOption: true
},
params: {
describe: "Params for the workflow instance, encoded as a JSON string",
type: "string",
default: ""
},
id: {
describe: "Custom instance ID, if not provided it will default to a random UUIDv4",
type: "string",
default: void 0
}
},
positionalArgs: ["name", "params"],
async handler(args, { config, logger: logger4 }) {
const accountId = await requireAuth(config);
if (args.params.length != 0) {
try {
JSON.parse(args.params);
} catch (e7) {
logger4.error(
`Error while parsing instance parameters: "${args.params}" with ${e7}' `
);
return;
}
}
const response = await fetchResult(
config,
`/accounts/${accountId}/workflows/${args.name}/instances`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
instance_id: args.id,
params: args.params.length != 0 ? JSON.parse(args.params) : void 0
})
}
);
logger4.info(
`\u{1F680} Workflow instance "${response.id}" has been queued successfully`
);
}
});
}
});
// src/index.ts
function createCLIParser(argv) {
const globalFlags = {
v: {
describe: "Show version number",
alias: "version",
type: "boolean"
},
cwd: {
describe: "Run as if Wrangler was started in the specified directory instead of the current working directory",
type: "string",
requiresArg: true
},
config: {
alias: "c",
describe: "Path to Wrangler configuration file",
type: "string",
requiresArg: true
},
env: {
alias: "e",
describe: "Environment to use for operations, and for selecting .env and .dev.vars files",
type: "string",
requiresArg: true
},
"env-file": {
describe: "Path to an .env file to load - can be specified multiple times - values from earlier files are overridden by values in later files",
type: "string",
array: true,
requiresArg: true
},
"experimental-remote-bindings": {
describe: `Experimental: Enable Remote Bindings`,
type: "boolean",
hidden: true,
alias: ["x-remote-bindings"]
},
"experimental-provision": {
describe: `Experimental: Enable automatic resource provisioning`,
type: "boolean",
hidden: true,
alias: ["x-provision"]
}
};
const wrangler = yargs_default(argv).strict().showHelpOnFail(false).fail((msg, error2) => {
if (!error2 || error2.name === "YError") {
error2 = new CommandLineArgsError(msg, {
telemetryMessage: "yargs validation error"
});
}
throw error2;
}).scriptName("wrangler").wrap(null).locale("en_US").version(false).options(globalFlags).check(demandSingleValue("cwd")).middleware((_argv) => {
if (_argv.cwd) {
process.chdir(_argv.cwd);
}
}).check(
demandSingleValue(
"config",
(configArgv) => configArgv["_"][0] === "dev" || configArgv["_"][0] === "types" || configArgv["_"][0] === "pages" && configArgv["_"][1] === "dev"
)
).check(demandSingleValue("env")).check((args) => {
const resolvedEnvFilePaths = (args["env-file"] ?? getDefaultEnvFiles(args.env)).map((p6) => (0, import_node_path56.resolve)(p6));
process.env = loadDotEnv(resolvedEnvFilePaths, {
includeProcessEnv: true,
silent: true
});
writeOutput({
type: "wrangler-session",
version: 1,
wrangler_version: version,
command_line_args: argv,
log_file_path: debugLogFilepath
});
return true;
}).epilogue(
`Please report any issues to ${source_default.hex("#3B818D")(
"https://github.com/cloudflare/workers-sdk/issues/new/choose"
)}`
);
wrangler.updateStrings({
"Commands:": `${source_default.bold("COMMANDS")}`,
"Options:": `${source_default.bold("OPTIONS")}`,
"Positionals:": `${source_default.bold("POSITIONALS")}`,
"Examples:": `${source_default.bold("EXAMPLES")}`
});
wrangler.group(
["config", "cwd", "env", "env-file", "help", "version"],
`${source_default.bold("GLOBAL FLAGS")}`
);
wrangler.help("help", "Show help").alias("h", "help");
const subHelp = {
command: ["*"],
handler: /* @__PURE__ */ __name(async (args) => {
setImmediate(
() => wrangler.parse([...args._.map((a5) => `${a5}`), "--help"])
);
}, "handler")
};
wrangler.command(
["*"],
false,
() => {
},
async (args) => {
if (args._.length > 0) {
throw new CommandLineArgsError(`Unknown command: ${args._}.`);
} else {
if (args.v) {
if (process.stdout.isTTY) {
await printWranglerBanner();
} else {
logger.log(version);
}
} else {
wrangler.showHelp("log");
}
}
}
);
const registerCommand = createRegisterYargsCommand(wrangler, subHelp);
const registry = new CommandRegistry(registerCommand);
registry.define([
{
command: "wrangler docs",
definition: docs
}
]);
registry.registerNamespace("docs");
registry.define([
{
command: "wrangler init",
definition: init
}
]);
registry.registerNamespace("init");
registry.define([
{
command: "wrangler dev",
definition: dev
}
]);
registry.registerNamespace("dev");
registry.define([
{
command: "wrangler deploy",
definition: deployCommand
}
]);
registry.registerNamespace("deploy");
registry.define([
{ command: "wrangler deployments", definition: deploymentsNamespace },
{
command: "wrangler deployments list",
definition: deploymentsListCommand
},
{
command: "wrangler deployments status",
definition: deploymentsStatusCommand
},
{
command: "wrangler deployments view",
definition: deploymentsViewCommand
}
]);
registry.registerNamespace("deployments");
registry.define([
{ command: "wrangler rollback", definition: versionsRollbackCommand }
]);
registry.registerNamespace("rollback");
registry.define([
{
command: "wrangler versions",
definition: versionsNamespace
},
{
command: "wrangler versions view",
definition: versionsViewCommand
},
{
command: "wrangler versions list",
definition: versionsListCommand
},
{
command: "wrangler versions upload",
definition: versionsUploadCommand
},
{
command: "wrangler versions deploy",
definition: versionsDeployCommand
},
{
command: "wrangler versions secret",
definition: versionsSecretNamespace
},
{
command: "wrangler versions secret put",
definition: versionsSecretPutCommand
},
{
command: "wrangler versions secret bulk",
definition: versionsSecretBulkCommand
},
{
command: "wrangler versions secret delete",
definition: versionsSecretDeleteCommand
},
{
command: "wrangler versions secret list",
definition: versionsSecretsListCommand
}
]);
registry.registerNamespace("versions");
registry.define([
{ command: "wrangler triggers", definition: triggersNamespace },
{ command: "wrangler triggers deploy", definition: triggersDeployCommand }
]);
registry.registerNamespace("triggers");
registry.define([{ command: "wrangler delete", definition: deleteCommand3 }]);
registry.registerNamespace("delete");
registry.define([{ command: "wrangler tail", definition: tailCommand }]);
registry.registerNamespace("tail");
registry.define([
{ command: "wrangler secret", definition: secretNamespace },
{ command: "wrangler secret put", definition: secretPutCommand },
{ command: "wrangler secret delete", definition: secretDeleteCommand },
{ command: "wrangler secret list", definition: secretListCommand },
{ command: "wrangler secret bulk", definition: secretBulkCommand }
]);
registry.registerNamespace("secret");
registry.define([{ command: "wrangler types", definition: typesCommand }]);
registry.registerNamespace("types");
registry.define([
{ command: "wrangler kv", definition: kvNamespace },
{ command: "wrangler kv namespace", definition: kvNamespaceNamespace },
{ command: "wrangler kv key", definition: kvKeyNamespace },
{ command: "wrangler kv bulk", definition: kvBulkNamespace },
{
command: "wrangler kv namespace create",
definition: kvNamespaceCreateCommand
},
{
command: "wrangler kv namespace list",
definition: kvNamespaceListCommand
},
{
command: "wrangler kv namespace delete",
definition: kvNamespaceDeleteCommand
},
{
command: "wrangler kv namespace rename",
definition: kvNamespaceRenameCommand
},
{ command: "wrangler kv key put", definition: kvKeyPutCommand },
{ command: "wrangler kv key list", definition: kvKeyListCommand },
{ command: "wrangler kv key get", definition: kvKeyGetCommand },
{ command: "wrangler kv key delete", definition: kvKeyDeleteCommand },
{ command: "wrangler kv bulk get", definition: kvBulkGetCommand },
{ command: "wrangler kv bulk put", definition: kvBulkPutCommand },
{ command: "wrangler kv bulk delete", definition: kvBulkDeleteCommand }
]);
registry.registerNamespace("kv");
registry.define([
{ command: "wrangler queues", definition: queuesNamespace },
{ command: "wrangler queues list", definition: queuesListCommand },
{ command: "wrangler queues create", definition: queuesCreateCommand },
{ command: "wrangler queues update", definition: queuesUpdateCommand },
{ command: "wrangler queues delete", definition: queuesDeleteCommand },
{ command: "wrangler queues info", definition: queuesInfoCommand },
{
command: "wrangler queues consumer",
definition: queuesConsumerNamespace
},
{
command: "wrangler queues pause-delivery",
definition: queuesPauseCommand
},
{
command: "wrangler queues resume-delivery",
definition: queuesResumeCommand
},
{
command: "wrangler queues purge",
definition: queuesPurgeCommand
},
{
command: "wrangler queues subscription",
definition: queuesSubscriptionNamespace
},
{
command: "wrangler queues subscription create",
definition: queuesSubscriptionCreateCommand
},
{
command: "wrangler queues subscription list",
definition: queuesSubscriptionListCommand
},
{
command: "wrangler queues subscription get",
definition: queuesSubscriptionGetCommand
},
{
command: "wrangler queues subscription delete",
definition: queuesSubscriptionDeleteCommand
},
{
command: "wrangler queues subscription update",
definition: queuesSubscriptionUpdateCommand
},
{
command: "wrangler queues consumer add",
definition: queuesConsumerAddCommand
},
{
command: "wrangler queues consumer remove",
definition: queuesConsumerRemoveCommand
},
{
command: "wrangler queues consumer http",
definition: queuesConsumerHttpNamespace
},
{
command: "wrangler queues consumer http add",
definition: queuesConsumerHttpAddCommand
},
{
command: "wrangler queues consumer http remove",
definition: queuesConsumerHttpRemoveCommand
},
{
command: "wrangler queues consumer worker",
definition: queuesConsumerWorkerNamespace
},
{
command: "wrangler queues consumer worker add",
definition: queuesConsumerAddCommand
},
{
command: "wrangler queues consumer worker remove",
definition: queuesConsumerRemoveCommand
}
]);
registry.registerNamespace("queues");
registry.define([
{ command: "wrangler r2", definition: r2Namespace },
{
command: "wrangler r2 object",
definition: r2ObjectNamespace
},
{
command: "wrangler r2 object get",
definition: r2ObjectGetCommand
},
{
command: "wrangler r2 object put",
definition: r2ObjectPutCommand
},
{
command: "wrangler r2 object delete",
definition: r2ObjectDeleteCommand
},
{
command: "wrangler r2 bucket",
definition: r2BucketNamespace
},
{
command: "wrangler r2 bucket create",
definition: r2BucketCreateCommand
},
{
command: "wrangler r2 bucket update",
definition: r2BucketUpdateNamespace
},
{
command: "wrangler r2 bucket update storage-class",
definition: r2BucketUpdateStorageClassCommand
},
{
command: "wrangler r2 bucket list",
definition: r2BucketListCommand
},
{
command: "wrangler r2 bucket info",
definition: r2BucketInfoCommand
},
{
command: "wrangler r2 bucket delete",
definition: r2BucketDeleteCommand
},
{
command: "wrangler r2 bucket sippy",
definition: r2BucketSippyNamespace
},
{
command: "wrangler r2 bucket sippy enable",
definition: r2BucketSippyEnableCommand
},
{
command: "wrangler r2 bucket sippy disable",
definition: r2BucketSippyDisableCommand
},
{
command: "wrangler r2 bucket sippy get",
definition: r2BucketSippyGetCommand
},
{
command: "wrangler r2 bucket catalog",
definition: r2BucketCatalogNamespace
},
{
command: "wrangler r2 bucket catalog enable",
definition: r2BucketCatalogEnableCommand
},
{
command: "wrangler r2 bucket catalog disable",
definition: r2BucketCatalogDisableCommand
},
{
command: "wrangler r2 bucket catalog get",
definition: r2BucketCatalogGetCommand
},
{
command: "wrangler r2 bucket notification",
definition: r2BucketNotificationNamespace
},
{
command: "wrangler r2 bucket notification get",
definition: r2BucketNotificationGetAlias
},
{
command: "wrangler r2 bucket notification list",
definition: r2BucketNotificationListCommand
},
{
command: "wrangler r2 bucket notification create",
definition: r2BucketNotificationCreateCommand
},
{
command: "wrangler r2 bucket notification delete",
definition: r2BucketNotificationDeleteCommand
},
{
command: "wrangler r2 bucket domain",
definition: r2BucketDomainNamespace
},
{
command: "wrangler r2 bucket domain list",
definition: r2BucketDomainListCommand
},
{
command: "wrangler r2 bucket domain get",
definition: r2BucketDomainGetCommand
},
{
command: "wrangler r2 bucket domain add",
definition: r2BucketDomainAddCommand
},
{
command: "wrangler r2 bucket domain remove",
definition: r2BucketDomainRemoveCommand
},
{
command: "wrangler r2 bucket domain update",
definition: r2BucketDomainUpdateCommand
},
{
command: "wrangler r2 bucket dev-url",
definition: r2BucketDevUrlNamespace
},
{
command: "wrangler r2 bucket dev-url get",
definition: r2BucketDevUrlGetCommand
},
{
command: "wrangler r2 bucket dev-url enable",
definition: r2BucketDevUrlEnableCommand
},
{
command: "wrangler r2 bucket dev-url disable",
definition: r2BucketDevUrlDisableCommand
},
{
command: "wrangler r2 bucket lifecycle",
definition: r2BucketLifecycleNamespace
},
{
command: "wrangler r2 bucket lifecycle list",
definition: r2BucketLifecycleListCommand
},
{
command: "wrangler r2 bucket lifecycle add",
definition: r2BucketLifecycleAddCommand
},
{
command: "wrangler r2 bucket lifecycle remove",
definition: r2BucketLifecycleRemoveCommand
},
{
command: "wrangler r2 bucket lifecycle set",
definition: r2BucketLifecycleSetCommand
},
{
command: "wrangler r2 bucket cors",
definition: r2BucketCORSNamespace
},
{
command: "wrangler r2 bucket cors delete",
definition: r2BucketCORSDeleteCommand
},
{
command: "wrangler r2 bucket cors list",
definition: r2BucketCORSListCommand
},
{
command: "wrangler r2 bucket cors set",
definition: r2BucketCORSSetCommand
},
{
command: "wrangler r2 bucket lock",
definition: r2BucketLockNamespace
},
{
command: "wrangler r2 bucket lock list",
definition: r2BucketLockListCommand
},
{
command: "wrangler r2 bucket lock add",
definition: r2BucketLockAddCommand
},
{
command: "wrangler r2 bucket lock remove",
definition: r2BucketLockRemoveCommand
},
{
command: "wrangler r2 bucket lock set",
definition: r2BucketLockSetCommand
}
]);
registry.registerNamespace("r2");
registry.define([
{ command: "wrangler d1", definition: d1Namespace },
{ command: "wrangler d1 list", definition: d1ListCommand },
{ command: "wrangler d1 info", definition: d1InfoCommand },
{ command: "wrangler d1 insights", definition: d1InsightsCommand },
{ command: "wrangler d1 create", definition: d1CreateCommand },
{ command: "wrangler d1 delete", definition: d1DeleteCommand },
{ command: "wrangler d1 execute", definition: d1ExecuteCommand },
{ command: "wrangler d1 export", definition: d1ExportCommand },
{ command: "wrangler d1 time-travel", definition: d1TimeTravelNamespace },
{
command: "wrangler d1 time-travel info",
definition: d1TimeTravelInfoCommand
},
{
command: "wrangler d1 time-travel restore",
definition: d1TimeTravelRestoreCommand
},
{ command: "wrangler d1 migrations", definition: d1MigrationsNamespace },
{
command: "wrangler d1 migrations list",
definition: d1MigrationsListCommand
},
{
command: "wrangler d1 migrations create",
definition: d1MigrationsCreateCommand
},
{
command: "wrangler d1 migrations apply",
definition: d1MigrationsApplyCommand
}
]);
registry.registerNamespace("d1");
registry.define([
{ command: "wrangler vectorize", definition: vectorizeNamespace },
{
command: "wrangler vectorize create",
definition: vectorizeCreateCommand
},
{
command: "wrangler vectorize delete",
definition: vectorizeDeleteCommand
},
{ command: "wrangler vectorize get", definition: vectorizeGetCommand },
{ command: "wrangler vectorize list", definition: vectorizeListCommand },
{
command: "wrangler vectorize list-vectors",
definition: vectorizeListVectorsCommand
},
{ command: "wrangler vectorize query", definition: vectorizeQueryCommand },
{
command: "wrangler vectorize insert",
definition: vectorizeInsertCommand
},
{
command: "wrangler vectorize upsert",
definition: vectorizeUpsertCommand
},
{
command: "wrangler vectorize get-vectors",
definition: vectorizeGetVectorsCommand
},
{
command: "wrangler vectorize delete-vectors",
definition: vectorizeDeleteVectorsCommand
},
{ command: "wrangler vectorize info", definition: vectorizeInfoCommand },
{
command: "wrangler vectorize create-metadata-index",
definition: vectorizeCreateMetadataIndexCommand
},
{
command: "wrangler vectorize list-metadata-index",
definition: vectorizeListMetadataIndexCommand
},
{
command: "wrangler vectorize delete-metadata-index",
definition: vectorizeDeleteMetadataIndexCommand
}
]);
registry.registerNamespace("vectorize");
registry.define([
{ command: "wrangler hyperdrive", definition: hyperdriveNamespace },
{
command: "wrangler hyperdrive create",
definition: hyperdriveCreateCommand
},
{
command: "wrangler hyperdrive delete",
definition: hyperdriveDeleteCommand
},
{ command: "wrangler hyperdrive get", definition: hyperdriveGetCommand },
{ command: "wrangler hyperdrive list", definition: hyperdriveListCommand },
{
command: "wrangler hyperdrive update",
definition: hyperdriveUpdateCommand
}
]);
registry.registerNamespace("hyperdrive");
registry.define([
{ command: "wrangler cert", definition: certNamespace },
{ command: "wrangler cert upload", definition: certUploadNamespace },
{
command: "wrangler cert upload mtls-certificate",
definition: certUploadMtlsCommand
},
{
command: "wrangler cert upload certificate-authority",
definition: certUploadCaCertCommand
},
{ command: "wrangler cert list", definition: certListCommand },
{ command: "wrangler cert delete", definition: certDeleteCommand }
]);
registry.registerNamespace("cert");
registry.define([
{ command: "wrangler pages", definition: pagesNamespace },
{ command: "wrangler pages dev", definition: pagesDevCommand },
{
command: "wrangler pages functions",
definition: pagesFunctionsNamespace
},
{
command: "wrangler pages functions build",
definition: pagesFunctionsBuildCommand
},
{
command: "wrangler pages functions build-env",
definition: pagesFunctionsBuildEnvCommand
},
{
command: "wrangler pages functions optimize-routes",
definition: pagesFunctionsOptimizeRoutesCommand
},
{ command: "wrangler pages project", definition: pagesProjectNamespace },
{
command: "wrangler pages project list",
definition: pagesProjectListCommand
},
{
command: "wrangler pages project create",
definition: pagesProjectCreateCommand
},
{
command: "wrangler pages project delete",
definition: pagesProjectDeleteCommand
},
{
command: "wrangler pages project upload",
definition: pagesProjectUploadCommand
},
{
command: "wrangler pages project validate",
definition: pagesProjectValidateCommand
},
{
command: "wrangler pages deployment",
definition: pagesDeploymentNamespace
},
{
command: "wrangler pages deployment list",
definition: pagesDeploymentListCommand
},
{
command: "wrangler pages deployment create",
definition: pagesDeploymentCreateCommand
},
{
command: "wrangler pages deployment tail",
definition: pagesDeploymentTailCommand
},
{ command: "wrangler pages deploy", definition: pagesDeployCommand },
{ command: "wrangler pages publish", definition: pagesPublishCommand },
{ command: "wrangler pages secret", definition: pagesSecretNamespace },
{ command: "wrangler pages download", definition: pagesDownloadNamespace },
{
command: "wrangler pages download config",
definition: pagesDownloadConfigCommand
},
{ command: "wrangler pages secret put", definition: pagesSecretPutCommand },
{
command: "wrangler pages secret bulk",
definition: pagesSecretBulkCommand
},
{
command: "wrangler pages secret delete",
definition: pagesSecretDeleteCommand
},
{
command: "wrangler pages secret list",
definition: pagesSecretListCommand
}
]);
registry.registerNamespace("pages");
registry.define([
{
command: "wrangler mtls-certificate",
definition: mTlsCertificateNamespace
},
{
command: "wrangler mtls-certificate upload",
definition: mTlsCertificateUploadCommand
},
{
command: "wrangler mtls-certificate list",
definition: mTlsCertificateListCommand
},
{
command: "wrangler mtls-certificate delete",
definition: mTlsCertificateDeleteCommand
}
]);
registry.registerNamespace("mtls-certificate");
wrangler.command("cloudchamber", false, (cloudchamberArgs) => {
return cloudchamber(cloudchamberArgs.command(subHelp), subHelp);
});
wrangler.command("containers", false, (containersArgs) => {
return containers(containersArgs.command(subHelp), subHelp);
});
wrangler.command(
"pubsub",
`\u{1F4EE} Manage Pub/Sub brokers ${source_default.hex(betaCmdColor)("[private beta]")}`,
(pubsubYargs) => {
return pubSubCommands(pubsubYargs, subHelp);
}
);
registry.define([
{
command: "wrangler dispatch-namespace",
definition: dispatchNamespaceNamespace
},
{
command: "wrangler dispatch-namespace list",
definition: dispatchNamespaceListCommand
},
{
command: "wrangler dispatch-namespace get",
definition: dispatchNamespaceGetCommand
},
{
command: "wrangler dispatch-namespace create",
definition: dispatchNamespaceCreateCommand
},
{
command: "wrangler dispatch-namespace delete",
definition: dispatchNamespaceDeleteCommand
},
{
command: "wrangler dispatch-namespace rename",
definition: dispatchNamespaceRenameCommand
}
]);
registry.registerNamespace("dispatch-namespace");
registry.define([
{ command: "wrangler ai", definition: aiNamespace },
{ command: "wrangler ai models", definition: aiModelsCommand },
{ command: "wrangler ai finetune", definition: aiFineTuneNamespace },
{ command: "wrangler ai finetune list", definition: aiFineTuneListCommand },
{
command: "wrangler ai finetune create",
definition: aiFineTuneCreateCommand
}
]);
registry.registerNamespace("ai");
registry.define([
{ command: "wrangler secrets-store", definition: secretsStoreNamespace },
{
command: "wrangler secrets-store store",
definition: secretsStoreStoreNamespace
},
{
command: "wrangler secrets-store store create",
definition: secretsStoreStoreCreateCommand
},
{
command: "wrangler secrets-store store delete",
definition: secretsStoreStoreDeleteCommand
},
{
command: "wrangler secrets-store store list",
definition: secretsStoreStoreListCommand
},
{
command: "wrangler secrets-store secret",
definition: secretsStoreSecretNamespace
},
{
command: "wrangler secrets-store secret create",
definition: secretsStoreSecretCreateCommand
},
{
command: "wrangler secrets-store secret list",
definition: secretsStoreSecretListCommand
},
{
command: "wrangler secrets-store secret get",
definition: secretsStoreSecretGetCommand
},
{
command: "wrangler secrets-store secret update",
definition: secretsStoreSecretUpdateCommand
},
{
command: "wrangler secrets-store secret delete",
definition: secretsStoreSecretDeleteCommand
},
{
command: "wrangler secrets-store secret duplicate",
definition: secretsStoreSecretDuplicateCommand
}
]);
registry.registerNamespace("secrets-store");
registry.define([
{
command: "wrangler workflows",
definition: workflowsNamespace
},
{
command: "wrangler workflows list",
definition: workflowsListCommand
},
{
command: "wrangler workflows describe",
definition: workflowsDescribeCommand
},
{
command: "wrangler workflows delete",
definition: workflowsDeleteCommand
},
{
command: "wrangler workflows trigger",
definition: workflowsTriggerCommand
},
{
command: "wrangler workflows instances",
definition: workflowsInstanceNamespace
},
{
command: "wrangler workflows instances list",
definition: workflowsInstancesListCommand
},
{
command: "wrangler workflows instances describe",
definition: workflowsInstancesDescribeCommand
},
{
command: "wrangler workflows instances terminate",
definition: workflowsInstancesTerminateCommand
},
{
command: "wrangler workflows instances terminate-all",
definition: workflowsInstancesTerminateAllCommand
},
{
command: "wrangler workflows instances pause",
definition: workflowsInstancesPauseCommand
},
{
command: "wrangler workflows instances resume",
definition: workflowsInstancesResumeCommand
}
]);
registry.registerNamespace("workflows");
registry.define([
{
command: "wrangler pipelines",
definition: pipelinesNamespace
},
{
command: "wrangler pipelines create",
definition: pipelinesCreateCommand
},
{
command: "wrangler pipelines list",
definition: pipelinesListCommand
},
{
command: "wrangler pipelines get",
definition: pipelinesGetCommand
},
{
command: "wrangler pipelines update",
definition: pipelinesUpdateCommand
},
{
command: "wrangler pipelines delete",
definition: pipelinesDeleteCommand
}
]);
registry.registerNamespace("pipelines");
registry.define([
{ command: "wrangler hello-world", definition: helloWorldNamespace },
{
command: "wrangler hello-world get",
definition: helloWorldGetCommand
},
{
command: "wrangler hello-world set",
definition: helloWorldSetCommand
}
]);
registry.registerNamespace("hello-world");
registry.define([
{
command: "wrangler login",
definition: loginCommand
}
]);
registry.registerNamespace("login");
registry.define([
{
command: "wrangler logout",
definition: logoutCommand
}
]);
registry.registerNamespace("logout");
registry.define([
{
command: "wrangler whoami",
definition: whoamiCommand
}
]);
registry.registerNamespace("whoami");
registry.define([
{
command: "wrangler telemetry",
definition: telemetryNamespace
},
{
command: "wrangler metrics",
definition: metricsAlias
},
{
command: "wrangler telemetry disable",
definition: telemetryDisableCommand
},
{
command: "wrangler telemetry enable",
definition: telemetryEnableCommand
},
{
command: "wrangler telemetry status",
definition: telemetryStatusCommand
}
]);
registry.registerNamespace("telemetry");
registry.define([
{
command: "wrangler check",
definition: checkNamespace
},
{
command: "wrangler check startup",
definition: checkStartupCommand
}
]);
registry.registerNamespace("check");
registry.define([
{
command: "wrangler build",
definition: buildCommand2
}
]);
registry.registerNamespace("build");
wrangler.version(false);
registry.registerAll();
wrangler.exitProcess(false);
return { wrangler, registry, globalFlags };
}
async function main(argv) {
setupSentry();
checkMacOSVersion({ shouldThrow: false });
const startTime = Date.now();
const { wrangler } = createCLIParser(argv);
let command2;
let metricsArgs;
let dispatcher;
let recordedCommand = false;
const wranglerWithMiddleware = wrangler.middleware(
(args) => {
if (Object.keys(LOGGER_LEVELS).includes(args.logLevel)) {
logger.loggerLevel = args.logLevel;
}
if (recordedCommand) {
return;
}
recordedCommand = true;
try {
const { rawConfig, configPath } = experimental_readRawConfig(args);
dispatcher = getMetricsDispatcher({
sendMetrics: rawConfig.send_metrics,
hasAssets: !!rawConfig.assets?.directory,
configPath
});
} catch (e7) {
logger.debug("Failed to parse config. Disabling metrics dispatcher.", e7);
}
command2 = `wrangler ${args._.join(" ")}`;
metricsArgs = args;
addBreadcrumb2(command2);
dispatcher?.sendCommandEvent(
"wrangler command started",
{
command: command2,
args
},
argv
);
},
/* applyBeforeValidation */
true
);
let cliHandlerThrew = false;
try {
await wranglerWithMiddleware.parse();
const durationMs = Date.now() - startTime;
dispatcher?.sendCommandEvent(
"wrangler command completed",
{
command: command2,
args: metricsArgs,
durationMs,
durationSeconds: durationMs / 1e3,
durationMinutes: durationMs / 1e3 / 60
},
argv
);
} catch (e7) {
cliHandlerThrew = true;
let mayReport = true;
let errorType;
let loggableException = e7;
logger.log("");
if (e7 instanceof CommandLineArgsError) {
logger.error(e7.message);
const { wrangler: helpWrangler } = createCLIParser([...argv, "--help"]);
await helpWrangler.parse();
} else if (isAuthenticationError(e7) || // Is this a Containers/Cloudchamber-based auth error?
// This is different because it uses a custom OpenAPI-based generated client
e7 instanceof UserError && e7.cause instanceof ApiError && e7.cause.status === 403) {
mayReport = false;
errorType = "AuthenticationError";
if (e7.cause instanceof ApiError) {
logger.error(e7.cause);
} else {
(0, import_node_assert23.default)(isAuthenticationError(e7));
logger.log(formatMessage(e7));
}
const envAuth = getAuthFromEnv();
if (envAuth !== void 0 && "apiToken" in envAuth) {
const message = "\u{1F4CE} It looks like you are authenticating Wrangler via a custom API token set in an environment variable.\nPlease ensure it has the correct permissions for this operation.\n";
logger.log(source_default.yellow(message));
}
const accountTag = e7?.accountTag;
let complianceConfig;
try {
complianceConfig = await readConfig(wrangler.arguments, {
hideWarnings: true
});
} catch {
complianceConfig = COMPLIANCE_REGION_CONFIG_UNKNOWN;
}
await whoami(complianceConfig, accountTag);
} else if (e7 instanceof ParseError) {
e7.notes.push({
text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/workers-sdk/issues/new/choose"
});
logger.log(formatMessage(e7));
} else if (e7 instanceof JsonFriendlyFatalError) {
logger.log(e7.message);
} else if (e7 instanceof Error && e7.message.includes("Raw mode is not supported on")) {
mayReport = false;
const currentPlatform = import_node_os8.default.platform();
const thisTerminalIsUnsupported = "This terminal doesn't support raw mode.";
const soWranglerWontWork = "Wrangler uses raw mode to read user input and write output to the terminal, and won't function correctly without it.";
const tryRunningItIn = "Try running your previous command in a terminal that supports raw mode";
const oneOfThese = currentPlatform === "win32" ? ", such as Command Prompt or Powershell." : currentPlatform === "darwin" ? ", such as Terminal.app or iTerm." : ".";
logger.error(
`${thisTerminalIsUnsupported}
${soWranglerWontWork}
${tryRunningItIn}${oneOfThese}`
);
} else if (isBuildFailure(e7)) {
mayReport = false;
errorType = "BuildFailure";
logBuildFailure(e7.errors, e7.warnings);
} else if (isBuildFailureFromCause(e7)) {
mayReport = false;
errorType = "BuildFailure";
logBuildFailure(e7.cause.errors, e7.cause.warnings);
} else {
if (
// Is this a StartDevEnv error event? If so, unwrap the cause, which is usually the user-recognisable error
e7 && typeof e7 === "object" && "type" in e7 && e7.type === "error" && "cause" in e7 && e7.cause instanceof Error
) {
loggableException = e7.cause;
}
logger.error(
loggableException instanceof Error ? loggableException.message : loggableException
);
if (loggableException instanceof Error) {
logger.debug(loggableException.stack);
}
if (!(loggableException instanceof UserError)) {
await logPossibleBugMessage();
}
}
if (
// Only report the error if we didn't just handle it
mayReport && // ...and it's not a user error
!(loggableException instanceof UserError) && // ...and it's not an un-reportable API error
!(loggableException instanceof APIError && !loggableException.reportable)
) {
await captureGlobalException(loggableException);
}
const durationMs = Date.now() - startTime;
dispatcher?.sendCommandEvent(
"wrangler command errored",
{
command: command2,
args: metricsArgs,
durationMs,
durationSeconds: durationMs / 1e3,
durationMinutes: durationMs / 1e3 / 60,
errorType: errorType ?? (e7 instanceof Error ? e7.constructor.name : void 0),
errorMessage: e7 instanceof UserError ? e7.telemetryMessage : void 0
},
argv
);
throw e7;
} finally {
try {
if (typeof vitest === "undefined") {
process.disconnect?.();
}
await closeSentry();
const controller = new AbortController();
await Promise.race([
Promise.allSettled(dispatcher?.requests ?? []),
(0, import_promises31.setTimeout)(1e3, void 0, controller)
// Ensure we don't hang indefinitely
]).then(() => controller.abort());
} catch (e7) {
logger.error(e7);
if (!cliHandlerThrew) {
throw e7;
}
}
}
}
var import_node_assert23, import_node_os8, import_node_path56, import_promises31, import_undici20;
var init_src2 = __esm({
"src/index.ts"() {
init_import_meta_url();
import_node_assert23 = __toESM(require("assert"));
import_node_os8 = __toESM(require("os"));
import_node_path56 = require("path");
import_promises31 = require("timers/promises");
init_cli();
init_containers_shared();
init_source();
import_undici20 = __toESM(require_undici());
init_yargs();
init_package();
init_ai();
init_createFinetune();
init_listCatalog();
init_listFinetune();
init_build3();
init_cert();
init_commands9();
init_cloudchamber();
init_config2();
init_dot_env();
init_containers2();
init_core2();
init_CommandRegistry();
init_register_yargs_command();
init_d1();
init_create();
init_delete2();
init_execute();
init_export();
init_info();
init_insights();
init_list();
init_migrations();
init_apply2();
init_create3();
init_list3();
init_timeTravel();
init_info2();
init_restore();
init_delete3();
init_deploy4();
init_deploy8();
init_build_failures();
init_dev2();
init_dispatch_namespace();
init_docs();
init_misc_variables();
init_errors();
init_hello_world();
init_create4();
init_delete4();
init_get();
init_hyperdrive();
init_list4();
init_update();
init_init();
init_kv();
init_logger();
init_metrics();
init_commands();
init_cli3();
init_output();
init_pages();
init_build4();
init_build_env();
init_deploy6();
init_deployment_tails();
init_deployments2();
init_dev();
init_download_config();
init_functions();
init_projects();
init_secret2();
init_upload();
init_validate2();
init_parse();
init_pipelines();
init_create5();
init_delete5();
init_get2();
init_list5();
init_update2();
init_pubsub_commands();
init_commands6();
init_consumer();
init_http_pull();
init_add();
init_remove();
init_worker();
init_add2();
init_remove2();
init_create6();
init_delete6();
init_info3();
init_list6();
init_pause_resume();
init_purge();
init_subscription();
init_create7();
init_delete7();
init_get3();
init_list7();
init_update3();
init_update4();
init_r2();
init_bucket();
init_catalog();
init_cors();
init_domain();
init_lifecycle();
init_lock();
init_notification();
init_object();
init_public_dev_url();
init_sippy();
init_secret();
init_secrets_store();
init_commands7();
init_sentry();
init_tail();
init_triggers();
init_type_generation();
init_user2();
init_commands8();
init_whoami();
init_constants5();
init_log_file();
init_logPossibleBugMessage();
init_create8();
init_createMetadataIndex();
init_delete8();
init_deleteByIds();
init_deleteMetadataIndex();
init_get4();
init_getByIds();
init_vectorize();
init_info4();
init_insert();
init_list8();
init_listMetadataIndex();
init_listVectors();
init_query();
init_upsert();
init_versions();
init_deploy7();
init_deployments3();
init_list10();
init_status();
init_view();
init_list9();
init_rollback();
init_secrets();
init_bulk();
init_delete9();
init_list11();
init_put();
init_upload2();
init_view2();
init_workflows();
init_delete10();
init_describe();
init_describe2();
init_list12();
init_pause();
init_resume();
init_terminate();
init_terminate_all();
init_list13();
init_trigger();
init_wrangler_banner();
if (proxy) {
(0, import_undici20.setGlobalDispatcher)(new import_undici20.ProxyAgent(proxy));
logger.log(
`Proxy environment variables detected. We'll use your proxy for fetch requests.`
);
}
__name(createCLIParser, "createCLIParser");
__name(main, "main");
}
});
// src/check/commands.ts
async function checkStartupHandler({
outfile,
args,
workerBundle,
pages
}, { config }) {
if (workerBundle === void 0) {
const tmpDir = getWranglerTmpDir(void 0, "startup-profile");
workerBundle = import_path26.default.join(tmpDir.path, "worker.bundle");
if (config.pages_build_output_dir || pages) {
log("Pages project detected");
log("");
}
if (logger.loggerLevel !== "debug") {
logger.loggerLevel = "error";
}
await spinnerWhile({
promise: /* @__PURE__ */ __name(async () => {
const { wrangler } = createCLIParser(
config.pages_build_output_dir || pages ? [
"pages",
"functions",
"build",
...args?.split(" ") ?? [],
`--outfile=${workerBundle}`
] : [
"deploy",
...args?.split(" ") ?? [],
"--dry-run",
`--outfile=${workerBundle}`
]
);
await wrangler.parse();
}, "promise"),
startMessage: "Building your Worker",
endMessage: source_default.green("Worker Built! \u{1F389}")
});
logger.resetLoggerLevel();
}
const cpuProfileResult = await spinnerWhile({
promise: analyseBundle(workerBundle),
startMessage: "Analysing",
endMessage: source_default.green("Startup phase analysed")
});
await (0, import_promises33.writeFile)(outfile, JSON.stringify(await cpuProfileResult));
log(
`CPU Profile written to ${outfile}. Load it into the Chrome DevTools profiler (or directly in VSCode) to view a flamegraph.`
);
}
async function getEntryValue(entry) {
if (entry instanceof Blob) {
return new Uint8Array(await entry.arrayBuffer());
} else {
return entry;
}
}
function getModuleType(entry) {
if (entry instanceof Blob) {
const type = ModuleTypeToRuleType[mimeTypeModuleType[entry.type]];
if (!type) {
throw new Error(
`Unable to determine module type for ${entry.type} mime type`
);
}
return type;
} else {
return "Text";
}
}
async function convertWorkerBundleToModules(workerBundle) {
return await Promise.all(
[...workerBundle.entries()].filter(
(m6) => m6[1] instanceof Blob && m6[1].type !== "application/source-map"
).map(
async (m6) => ({
type: getModuleType(m6[1]),
path: m6[0],
contents: await getEntryValue(m6[1])
})
)
);
}
async function parseFormDataFromFile(file) {
const bundle = await (0, import_promises32.readFile)(file);
const firstLine = bundle.findIndex((v7) => v7 === 10);
const boundary = Uint8Array.prototype.slice.call(bundle, 2, firstLine).toString();
return await new Response(bundle, {
headers: {
"Content-Type": "multipart/form-data; boundary=" + boundary
}
}).formData();
}
async function analyseBundle(workerBundle) {
if (typeof workerBundle === "string") {
workerBundle = await parseFormDataFromFile(workerBundle);
}
const metadata = JSON.parse(workerBundle.get("metadata"));
if (!("main_module" in metadata)) {
throw new UserError(
"`wrangler check startup` does not support service-worker format Workers. Refer to https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ for migration guidance."
);
}
const mf = new import_miniflare21.Miniflare({
name: "profiler",
compatibilityDate: metadata.compatibility_date,
compatibilityFlags: metadata.compatibility_flags,
modulesRoot: "/",
modules: [
{
type: "ESModule",
// Make sure the entrypoint path doesn't conflict with a user worker module
path: (0, import_crypto7.randomUUID)(),
contents: (
/* javascript */
`
async function startup() {
await import("${metadata.main_module}");
}
export default {
async fetch() {
await startup()
return new Response("ok")
}
}
`
)
},
...await convertWorkerBundleToModules(workerBundle)
],
inspectorPort: 0
});
await mf.ready;
const inspectorUrl = await mf.getInspectorURL();
const ws = new import_websocket.default(new URL("/core:user:profiler", inspectorUrl.href));
await import_node_events3.default.once(ws, "open");
ws.send(JSON.stringify({ id: 1, method: "Profiler.enable", params: {} }));
ws.send(JSON.stringify({ id: 2, method: "Profiler.start", params: {} }));
const cpuProfileResult = new Promise((accept) => {
ws.addEventListener("message", (e7) => {
const data = JSON.parse(e7.data);
if (data.method === "Profiler.stop") {
void mf.dispose().then(() => accept(data.result.profile));
}
});
});
await (await mf.dispatchFetch("https://example.com")).text();
ws.send(JSON.stringify({ id: 3, method: "Profiler.stop", params: {} }));
return cpuProfileResult;
}
var import_crypto7, import_promises32, import_node_events3, import_promises33, import_path26, import_miniflare21, mimeTypeModuleType, checkNamespace, checkStartupCommand;
var init_commands9 = __esm({
"src/check/commands.ts"() {
init_import_meta_url();
import_crypto7 = require("crypto");
import_promises32 = require("fs/promises");
import_node_events3 = __toESM(require("events"));
import_promises33 = require("fs/promises");
import_path26 = __toESM(require("path"));
init_cli();
init_interactive();
init_source();
import_miniflare21 = require("miniflare");
init_wrapper();
init_src2();
init_create_command();
init_create_worker_upload_form();
init_module_collection();
init_errors();
init_logger();
init_paths();
mimeTypeModuleType = flipObject(moduleTypeMimeType);
checkNamespace = createNamespace({
metadata: {
description: "\u2611\uFE0E Run checks on your Worker",
owner: "Workers: Authoring and Testing",
status: "alpha",
hidden: true
}
});
__name(checkStartupHandler, "checkStartupHandler");
checkStartupCommand = createCommand({
args: {
outfile: {
describe: "Output file for startup phase cpuprofile",
type: "string",
default: "worker-startup.cpuprofile"
},
workerBundle: {
alias: "worker",
describe: "Path to a prebuilt worker bundle i.e the output of `wrangler deploy --outfile worker.bundle",
type: "string"
},
pages: {
describe: "Force this project to be treated as a Pages project",
type: "boolean"
},
args: {
describe: "Additional arguments passed to `wrangler deploy` or `wrangler pages functions build` e.g. `--no-bundle`",
type: "string"
}
},
validateArgs({ args, workerBundle }) {
if (workerBundle && args) {
throw new UserError(
"`--args` and `--worker` are mutually exclusive\u2014please only specify one"
);
}
if (args?.includes("outfile") || args?.includes("outdir")) {
throw new UserError(
"`--args` should not contain `--outfile` or `--outdir`"
);
}
},
metadata: {
description: "\u231B Profile your Worker's startup performance",
owner: "Workers: Authoring and Testing",
status: "alpha"
},
handler: checkStartupHandler
});
__name(getEntryValue, "getEntryValue");
__name(getModuleType, "getModuleType");
__name(convertWorkerBundleToModules, "convertWorkerBundleToModules");
__name(parseFormDataFromFile, "parseFormDataFromFile");
__name(analyseBundle, "analyseBundle");
}
});
// src/utils/friendly-validator-errors.ts
async function helpIfErrorIsSizeOrScriptStartup(err, dependencies, workerBundle, projectRoot) {
if (errIsScriptSize(err)) {
return await diagnoseScriptSizeError(err, dependencies);
}
if (errIsStartupErr(err)) {
return await diagnoseStartupError(err, workerBundle, projectRoot);
}
return null;
}
function diagnoseScriptSizeError(err, dependencies) {
let message = esm_default2`
Your Worker failed validation because it exceeded size limits.
${err.text}
${err.notes.map((note) => ` - ${note.text}`).join("\n")}
`;
const dependenciesMessage = getOffendingDependenciesMessage(dependencies);
if (dependenciesMessage) {
message += dependenciesMessage;
}
return message;
}
async function diagnoseStartupError(err, workerBundle, projectRoot) {
let errorMessage = esm_default2`
Your Worker failed validation because it exceeded startup limits.
${err.text}
${err.notes.map((note) => ` - ${note.text}`).join("\n")}
To ensure fast responses, there are constraints on Worker startup, such as how much CPU it can use, or how long it can take. Your Worker has hit one of these startup limits. Try reducing the amount of work done during startup (outside the event handler), either by removing code or relocating it inside the event handler.
Refer to https://developers.cloudflare.com/workers/platform/limits/#worker-startup-time for more details`;
try {
const cpuProfile = await analyseBundle(workerBundle);
const tmpDir = await getWranglerTmpDir(
projectRoot,
"startup-profile",
false
);
const profile = import_node_path57.default.relative(
projectRoot ?? process.cwd(),
import_node_path57.default.join(tmpDir.path, `worker.cpuprofile`)
);
await (0, import_promises34.writeFile)(profile, JSON.stringify(cpuProfile));
errorMessage += esm_default2`
A CPU Profile of your Worker's startup phase has been written to ${profile} - load it into the Chrome DevTools profiler (or directly in VSCode) to view a flamegraph.`;
} catch (profilingError) {
logger.debug(
`An error occurred while trying to locally profile the Worker: ${profilingError}`
);
}
return errorMessage;
}
function getOffendingDependenciesMessage(dependencies) {
const dependenciesSorted = Object.entries(dependencies);
if (dependenciesSorted.length === 0) {
return null;
}
dependenciesSorted.sort(
([, aData], [, bData]) => bData.bytesInOutput - aData.bytesInOutput
);
const topLargest = dependenciesSorted.slice(0, 5);
const ONE_KIB_BYTES2 = 1024;
return [
"",
`Here are the ${topLargest.length} largest dependencies included in your script:`,
"",
...topLargest.map(
([dep, data]) => `- ${dep} - ${(data.bytesInOutput / ONE_KIB_BYTES2).toFixed(2)} KiB`
),
"",
"If these are unnecessary, consider removing them",
""
].join("\n");
}
function errIsScriptSize(err) {
if (!(err instanceof ParseError)) {
return false;
}
if ("code" in err && err.code === 10027) {
return true;
}
return false;
}
function errIsStartupErr(err) {
if (!(err instanceof ParseError)) {
return false;
}
if ("code" in err && err.code === 10021 && /startup/i.test(err.notes[0]?.text)) {
return true;
}
return false;
}
var import_promises34, import_node_path57;
var init_friendly_validator_errors = __esm({
"src/utils/friendly-validator-errors.ts"() {
init_import_meta_url();
import_promises34 = require("fs/promises");
import_node_path57 = __toESM(require("path"));
init_esm2();
init_commands9();
init_logger();
init_parse();
init_paths();
__name(helpIfErrorIsSizeOrScriptStartup, "helpIfErrorIsSizeOrScriptStartup");
__name(diagnoseScriptSizeError, "diagnoseScriptSizeError");
__name(diagnoseStartupError, "diagnoseStartupError");
__name(getOffendingDependenciesMessage, "getOffendingDependenciesMessage");
__name(errIsScriptSize, "errIsScriptSize");
__name(errIsStartupErr, "errIsStartupErr");
}
});
// src/deploy/config-diffs.ts
function getRemoteConfigDiff(remoteConfig, localConfig) {
const diff = new Diff(
JSON.stringify(
normalizeRemoteConfigAsLocal(remoteConfig, localConfig),
null,
2
),
JSON.stringify(localConfig, null, 2)
);
return {
diff,
nonDestructive: configDiffOnlyHasAdditionsIfAny(diff)
};
}
function configDiffOnlyHasAdditionsIfAny(diff) {
const diffLines = diff.toString().split("\n");
let currentRemovalIdx = 0;
while (currentRemovalIdx !== -1) {
const nextRemovalIdx = diffLines.findIndex((line, idx) => {
if (idx < currentRemovalIdx) {
return false;
}
const withoutLeadingSpaces = line.replace(/^\s*/, "");
return withoutLeadingSpaces.startsWith(red("-"));
});
if (nextRemovalIdx === -1) {
return true;
}
currentRemovalIdx = nextRemovalIdx;
const lineAtIdx = diffLines[currentRemovalIdx];
const nextLine = diffLines[currentRemovalIdx + 1] ?? "";
const lineAtIdxButAdditionAndWithComma = `${lineAtIdx.replace(red("-"), green("+"))},`;
const onlyACommaWasAdded = nextLine === lineAtIdxButAdditionAndWithComma;
if (!onlyACommaWasAdded) {
return false;
}
currentRemovalIdx++;
}
return true;
}
function normalizeRemoteConfigAsLocal(remoteConfig, localConfig) {
let normalizedRemote = structuredClone(remoteConfig);
Object.entries(localConfig).forEach(([key, value]) => {
if (!remoteConfigKeys.has(key) || // We also include `main` here since this field can easily change but
// it changing does not really constitute a relevant config change
key === "main") {
normalizedRemote[key] = value;
}
});
cleanupRemoteDefault({
remoteObj: normalizedRemote,
localObj: localConfig,
field: "observability",
remoteDefaultValue: {
enabled: true,
head_sampling_rate: 1
}
});
if (normalizedRemote.observability && localConfig.observability) {
cleanupRemoteDefault({
remoteObj: normalizedRemote.observability,
localObj: localConfig.observability,
field: "enabled",
remoteDefaultValue: true
});
cleanupRemoteDefault({
remoteObj: normalizedRemote.observability,
localObj: localConfig.observability,
field: "head_sampling_rate",
remoteDefaultValue: 1
});
if (normalizedRemote.observability.logs && localConfig.observability.logs) {
cleanupRemoteDefault({
remoteObj: normalizedRemote.observability.logs,
localObj: localConfig.observability.logs,
field: "enabled",
remoteDefaultValue: true
});
}
}
cleanupRemoteDefault({
remoteObj: normalizedRemote,
localObj: localConfig,
field: "workers_dev",
remoteDefaultValue: true
});
normalizedRemote = orderObjectFields(
normalizedRemote,
localConfig
);
return normalizedRemote;
}
function cleanupRemoteDefault({
field,
localObj,
remoteObj,
remoteDefaultValue
}) {
if (deepStrictEqual(remoteObj[field], remoteDefaultValue)) {
if (!(field in localObj)) {
delete remoteObj[field];
}
if (localObj[field] === void 0) {
remoteObj[field] = void 0;
}
}
}
function orderObjectFields(source, target) {
const targetKeysIndexesMap = Object.fromEntries(
Object.keys(target).map((key, i5) => [key, i5])
);
const orderedSource = Object.fromEntries(
Object.entries(source).sort(([keyA], [keyB]) => {
if (keyA in target && !(keyB in target)) {
return -1;
}
if (!(keyA in target) && keyB in target) {
return 1;
}
if (!(keyA in target) && !(keyB in target)) {
return 0;
}
return targetKeysIndexesMap[keyA] - targetKeysIndexesMap[keyB];
})
);
for (const [key, value] of Object.entries(orderedSource)) {
if (typeof value === "object" && value !== null && !Array.isArray(value) && typeof target[key] === "object" && target[key] !== null && !Array.isArray(target[key])) {
orderedSource[key] = orderObjectFields(
value,
target[key]
);
}
}
return orderedSource;
}
function deepStrictEqual(source, target) {
try {
import_node_assert24.default.deepStrictEqual(source, target);
return true;
} catch {
return false;
}
}
var import_node_assert24, remoteConfigKeys;
var init_config_diffs = __esm({
"src/deploy/config-diffs.ts"() {
init_import_meta_url();
import_node_assert24 = __toESM(require("assert"));
init_colors();
init_diff();
__name(getRemoteConfigDiff, "getRemoteConfigDiff");
__name(configDiffOnlyHasAdditionsIfAny, "configDiffOnlyHasAdditionsIfAny");
__name(normalizeRemoteConfigAsLocal, "normalizeRemoteConfigAsLocal");
__name(cleanupRemoteDefault, "cleanupRemoteDefault");
__name(orderObjectFields, "orderObjectFields");
remoteConfigKeys = /* @__PURE__ */ new Set([
"name",
"main",
"workers_dev",
"compatibility_date",
"compatibility_flags",
"routes",
"placement",
"limits",
"migrations",
"triggers",
"tail_consumers",
"observability",
"vars",
"kv_namespaces",
"durable_objects",
"d1_databases",
"browser",
"ai",
"images",
"r2_buckets",
"secrets_store_secrets",
"unsafe_hello_world",
"services",
"analytics_engine_datasets",
"dispatch_namespaces",
"logfwdr",
"wasm_modules",
"text_blobs",
"data_blobs",
"version_metadata",
"send_email",
"queues",
"vectorize",
"hyperdrive",
"mtls_certificates",
"pipelines",
"unsafe",
"workflows"
]);
__name(deepStrictEqual, "deepStrictEqual");
}
});
// src/deploy/deploy.ts
function renderRoute(route) {
let result = "";
if (typeof route === "string") {
result = route;
} else {
result = route.pattern;
const isCustomDomain = Boolean(
"custom_domain" in route && route.custom_domain
);
if (isCustomDomain && "zone_id" in route) {
result += ` (custom domain - zone id: ${route.zone_id})`;
} else if (isCustomDomain && "zone_name" in route) {
result += ` (custom domain - zone name: ${route.zone_name})`;
} else if (isCustomDomain) {
result += ` (custom domain)`;
} else if ("zone_id" in route) {
result += ` (zone id: ${route.zone_id})`;
} else if ("zone_name" in route) {
result += ` (zone name: ${route.zone_name})`;
}
}
return result;
}
async function publishCustomDomains(complianceConfig, workerUrl, accountId, domains) {
const options = {
override_scope: true,
override_existing_origin: false,
override_existing_dns_record: false
};
const origins = domains.map((domainRoute) => {
return {
hostname: domainRoute.pattern,
zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : void 0,
zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : void 0
};
});
const fail = /* @__PURE__ */ __name(() => {
return [
domains.length > 1 ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again` : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`
];
}, "fail");
if (!process.stdout.isTTY) {
options.override_existing_origin = true;
options.override_existing_dns_record = true;
} else {
const changeset = await fetchResult(
complianceConfig,
`${workerUrl}/domains/changeset?replace_state=true`,
{
method: "POST",
body: JSON.stringify(origins),
headers: {
"Content-Type": "application/json"
}
}
);
const updatesRequired = changeset.updated.filter(
(domain2) => domain2.modified
);
if (updatesRequired.length > 0) {
const existing = await Promise.all(
updatesRequired.map(
(domain2) => fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/domains/records/${domain2.id}`
)
)
);
const existingRendered = existing.map(
(domain2) => ` \u2022 ${domain2.hostname} (used as a domain for "${domain2.service}")`
).join("\n");
const message = `Custom Domains already exist for these domains:
${existingRendered}
Update them to point to this script instead?`;
if (!await confirm(message)) {
return fail();
}
options.override_existing_origin = true;
}
if (changeset.conflicting.length > 0) {
const conflicitingRendered = changeset.conflicting.map((domain2) => ` \u2022 ${domain2.hostname}`).join("\n");
const message = `You already have DNS records that conflict for these Custom Domains:
${conflicitingRendered}
Update them to point to this script instead?`;
if (!await confirm(message)) {
return fail();
}
options.override_existing_dns_record = true;
}
}
await fetchResult(complianceConfig, `${workerUrl}/domains/records`, {
method: "PUT",
body: JSON.stringify({ ...options, origins }),
headers: {
"Content-Type": "application/json"
}
});
return domains.map((domain2) => renderRoute(domain2));
}
async function deploy(props) {
const { config, accountId, name: name2, entry } = props;
let workerTag = null;
let versionId = null;
let workerExists = true;
if (!props.dispatchNamespace && accountId) {
try {
const serviceMetaData = await fetchResult(config, `/accounts/${accountId}/workers/services/${name2}`);
const {
default_environment: { script }
} = serviceMetaData;
workerTag = script.tag;
if (script.last_deployed_from === "dash") {
let configDiff;
if (getFlag("DEPLOY_REMOTE_DIFF_CHECK")) {
const remoteWorkerConfig = await downloadWorkerConfig(
accountId,
name2,
entry.file,
serviceMetaData.default_environment.environment
);
let rawConfig;
if (config.configPath) {
try {
rawConfig = parseRawConfigFile(config.configPath);
} catch {
}
if (rawConfig) {
configDiff = getRemoteConfigDiff(remoteWorkerConfig, rawConfig);
}
}
}
if (configDiff) {
if (!configDiff.nonDestructive) {
logger.warn(
`Your local configuration differs from the remote configuration of your Worker set via the Cloudflare Dashboard:
${configDiff.diff}
Deploying the Worker will override the remote configuration with your local one.`
);
if (!await confirm("Would you like to continue?")) {
return { versionId, workerTag };
}
}
} else {
logger.warn(
`You are about to publish a Workers Service that was last published via the Cloudflare Dashboard.
Edits that have been made via the dashboard will be overridden by your local code and config.`
);
if (!await confirm("Would you like to continue?")) {
return { versionId, workerTag };
}
}
} else if (script.last_deployed_from === "api") {
logger.warn(
`You are about to publish a Workers Service that was last updated via the script API.
Edits that have been made via the script API will be overridden by your local code and config.`
);
if (!await confirm("Would you like to continue?")) {
return { versionId, workerTag };
}
}
} catch (e7) {
if (e7.code !== 10090) {
throw e7;
} else {
workerExists = false;
}
}
}
const compatibilityDate = props.compatibilityDate ?? config.compatibility_date;
const compatibilityFlags = props.compatibilityFlags ?? config.compatibility_flags;
if (!compatibilityDate) {
const compatibilityDateStr = formatCompatibilityDate(/* @__PURE__ */ new Date());
throw new UserError(
`A compatibility_date is required when publishing. Add the following to your ${configFileName(config.configPath)} file:
\`\`\`
${formatConfigSnippet({ compatibility_date: compatibilityDateStr }, config.configPath, false)}
\`\`\`
Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`,
{ telemetryMessage: "missing compatibility date when deploying" }
);
}
const domainRoutes = (props.domains || []).map((domain2) => ({
pattern: domain2,
custom_domain: true
}));
const routes = props.routes ?? config.routes ?? (config.route ? [config.route] : []);
const allRoutes = [...routes, ...domainRoutes];
validateRoutes3(allRoutes, props.assetsOptions);
const jsxFactory = props.jsxFactory || config.jsx_factory;
const jsxFragment = props.jsxFragment || config.jsx_fragment;
const keepVars = props.keepVars || config.keep_vars;
const minify = props.minify ?? config.minify;
const nodejsCompatMode = validateNodeCompatMode(
compatibilityDate,
compatibilityFlags,
{
noBundle: props.noBundle ?? config.no_bundle
}
);
if (props.noBundle && minify) {
logger.warn(
"`--minify` and `--no-bundle` can't be used together. If you want to minify your Worker and disable Wrangler's bundling, please minify as part of your own bundling process."
);
}
const scriptName = props.name;
(0, import_node_assert25.default)(
!config.site || config.site.bucket,
"A [site] definition requires a `bucket` field with a path to the site's assets directory."
);
if (props.outDir) {
(0, import_node_fs33.mkdirSync)(props.outDir, { recursive: true });
const readmePath = import_node_path58.default.join(props.outDir, "README.md");
(0, import_node_fs33.writeFileSync)(
readmePath,
`This folder contains the built output assets for the worker "${scriptName}" generated at ${(/* @__PURE__ */ new Date()).toISOString()}.`
);
}
const destination = props.outDir ?? getWranglerTmpDir(props.projectRoot, "deploy");
const envName = props.env ?? "production";
const start = Date.now();
const prod = Boolean(props.legacyEnv || !props.env);
const notProd = !prod;
const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
const workerUrl = props.dispatchNamespace ? `/accounts/${accountId}/workers/dispatch/namespaces/${props.dispatchNamespace}/scripts/${scriptName}` : notProd ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}` : `/accounts/${accountId}/workers/scripts/${scriptName}`;
const { format: format9 } = props.entry;
if (!props.dispatchNamespace && prod && accountId && scriptName) {
const yes = await confirmLatestDeploymentOverwrite(
config,
accountId,
scriptName
);
if (!yes) {
cancel("Aborting deploy...");
return { versionId, workerTag };
}
}
if (!props.isWorkersSite && Boolean(props.legacyAssetPaths) && format9 === "service-worker") {
throw new UserError(
"You cannot use the service-worker format with an `assets` directory yet. For information on how to migrate to the module-worker format, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/",
{ telemetryMessage: true }
);
}
if (config.wasm_modules && format9 === "modules") {
throw new UserError(
"You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code",
{ telemetryMessage: true }
);
}
if (config.text_blobs && format9 === "modules") {
throw new UserError(
`You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure \`[rules]\` in your ${configFileName(config.configPath)} file`,
{ telemetryMessage: "[text_blobs] with an ES module worker" }
);
}
if (config.data_blobs && format9 === "modules") {
throw new UserError(
`You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure \`[rules]\` in your ${configFileName(config.configPath)} file`,
{ telemetryMessage: "[data_blobs] with an ES module worker" }
);
}
let sourceMapSize;
const normalisedContainerConfig = await getNormalizedContainerOptions(
config,
props
);
try {
if (props.noBundle) {
const destinationDir = typeof destination === "string" ? destination : destination.path;
(0, import_node_fs33.mkdirSync)(destinationDir, { recursive: true });
(0, import_node_fs33.writeFileSync)(
import_node_path58.default.join(destinationDir, import_node_path58.default.basename(props.entry.file)),
(0, import_node_fs33.readFileSync)(props.entry.file, "utf-8")
);
}
const entryDirectory = import_node_path58.default.dirname(props.entry.file);
const moduleCollector = createModuleCollector({
wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences(
entryDirectory,
props.entry.file
),
entry: props.entry,
// `moduleCollector` doesn't get used when `props.noBundle` is set, so
// `findAdditionalModules` always defaults to `false`
findAdditionalModules: config.find_additional_modules ?? false,
rules: props.rules,
preserveFileNames: config.preserve_file_names ?? false
});
const uploadSourceMaps = props.uploadSourceMaps ?? config.upload_source_maps;
const {
modules,
dependencies,
resolvedEntryPointPath,
bundleType,
...bundle
} = props.noBundle ? await noBundleWorker(props.entry, props.rules, props.outDir) : await bundleWorker(
props.entry,
typeof destination === "string" ? destination : destination.path,
{
metafile: props.metafile,
bundle: true,
additionalModules: [],
moduleCollector,
doBindings: config.durable_objects.bindings,
workflowBindings: config.workflows ?? [],
jsxFactory,
jsxFragment,
tsconfig: props.tsconfig ?? config.tsconfig,
minify,
keepNames: config.keep_names ?? true,
sourcemap: uploadSourceMaps,
nodejsCompatMode,
compatibilityDate,
compatibilityFlags,
define: { ...config.define, ...props.defines },
checkFetch: false,
alias: config.alias,
// We want to know if the build is for development or publishing
// This could potentially cause issues as we no longer have identical behaviour between dev and deploy?
targetConsumer: "deploy",
local: false,
projectRoot: props.projectRoot,
defineNavigatorUserAgent: isNavigatorDefined(
compatibilityDate,
compatibilityFlags
),
plugins: [logBuildOutput(nodejsCompatMode)],
// Pages specific options used by wrangler pages commands
entryName: void 0,
inject: void 0,
isOutfile: void 0,
external: void 0,
// These options are dev-only
testScheduled: void 0,
watch: void 0
}
);
for (const module3 of modules) {
const modulePath = module3.filePath === void 0 ? module3.name : import_node_path58.default.relative("", module3.filePath);
const bytesInOutput = typeof module3.content === "string" ? Buffer.byteLength(module3.content) : module3.content.byteLength;
dependencies[modulePath] = { bytesInOutput };
}
const content = (0, import_node_fs33.readFileSync)(resolvedEntryPointPath, {
encoding: "utf-8"
});
const migrations = !props.dryRun ? await getMigrationsToUpload(scriptName, {
accountId,
config,
legacyEnv: props.legacyEnv,
env: props.env,
dispatchNamespace: props.dispatchNamespace
}) : void 0;
const assetsJwt = props.assetsOptions && !props.dryRun ? await syncAssets(
config,
accountId,
props.assetsOptions.directory,
scriptName,
props.dispatchNamespace
) : void 0;
const workersSitesAssets = await syncWorkersSite(
config,
accountId,
// When we're using the newer service environments, we wouldn't
// have added the env name on to the script name. However, we must
// include it in the kv namespace name regardless (since there's no
// concept of service environments for kv namespaces yet).
scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
props.legacyAssetPaths,
false,
props.dryRun,
props.oldAssetTtl
);
const bindings = getBindings({
...config,
kv_namespaces: config.kv_namespaces.concat(
workersSitesAssets.namespace ? { binding: "__STATIC_CONTENT", id: workersSitesAssets.namespace } : []
),
vars: { ...config.vars, ...props.vars },
text_blobs: {
...config.text_blobs,
...workersSitesAssets.manifest && format9 === "service-worker" && {
__STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST"
}
}
});
if (workersSitesAssets.manifest) {
modules.push({
name: "__STATIC_CONTENT_MANIFEST",
filePath: void 0,
content: JSON.stringify(workersSitesAssets.manifest),
type: "text"
});
}
const placement = config.placement?.mode === "smart" ? { mode: "smart", hint: config.placement.hint } : void 0;
const entryPointName = import_node_path58.default.basename(resolvedEntryPointPath);
const main2 = {
name: entryPointName,
filePath: resolvedEntryPointPath,
content,
type: bundleType
};
const worker = {
name: scriptName,
main: main2,
bindings,
migrations,
modules,
containers: config.containers ?? void 0,
sourceMaps: uploadSourceMaps ? loadSourceMaps(main2, modules, bundle) : void 0,
compatibility_date: compatibilityDate,
compatibility_flags: compatibilityFlags,
keepVars,
keepSecrets: keepVars,
// keepVars implies keepSecrets
logpush: props.logpush !== void 0 ? props.logpush : config.logpush,
placement,
tail_consumers: config.tail_consumers,
limits: config.limits,
assets: props.assetsOptions && assetsJwt ? {
jwt: assetsJwt,
routerConfig: props.assetsOptions.routerConfig,
assetConfig: props.assetsOptions.assetConfig,
_redirects: props.assetsOptions._redirects,
_headers: props.assetsOptions._headers,
run_worker_first: props.assetsOptions.run_worker_first
} : void 0,
observability: config.observability
};
sourceMapSize = worker.sourceMaps?.reduce(
(acc, m6) => acc + m6.content.length,
0
);
await printBundleSize(
{ name: import_node_path58.default.basename(resolvedEntryPointPath), content },
modules
);
const withoutStaticAssets = {
...bindings,
kv_namespaces: config.kv_namespaces,
text_blobs: config.text_blobs
};
const maskedVars = { ...withoutStaticAssets.vars };
for (const key of Object.keys(maskedVars)) {
if (maskedVars[key] !== config.vars[key]) {
maskedVars[key] = "(hidden)";
}
}
const canUseNewVersionsDeploymentsApi = workerExists && props.dispatchNamespace === void 0 && prod && format9 === "modules" && migrations === void 0 && !config.first_party_worker && config.containers === void 0;
let workerBundle;
const dockerPath = getDockerPath();
if (normalisedContainerConfig.length) {
const hasDockerfiles = normalisedContainerConfig.some(
(container) => "dockerfile" in container
);
if (hasDockerfiles) {
await verifyDockerInstalled(dockerPath, false);
}
}
if (props.dryRun) {
if (normalisedContainerConfig.length) {
for (const container of normalisedContainerConfig) {
if ("dockerfile" in container) {
await buildContainer(
container,
workerTag ?? "worker-tag",
props.dryRun,
dockerPath
);
}
}
}
workerBundle = createWorkerUploadForm(worker);
printBindings(
{ ...withoutStaticAssets, vars: maskedVars },
config.tail_consumers,
{ warnIfNoBindings: true }
);
} else {
(0, import_node_assert25.default)(accountId, "Missing accountId");
if (getFlag("RESOURCES_PROVISION")) {
await provisionBindings(
bindings,
accountId,
scriptName,
props.experimentalAutoCreate,
props.config
);
}
workerBundle = createWorkerUploadForm(worker);
await ensureQueuesExistByConfig(config);
let bindingsPrinted = false;
try {
let result;
if (canUseNewVersionsDeploymentsApi) {
const versionResult = await retryOnAPIFailure(
async () => fetchResult(
config,
`/accounts/${accountId}/workers/scripts/${scriptName}/versions`,
{
method: "POST",
body: workerBundle,
headers: await getMetricsUsageHeaders(config.send_metrics)
}
)
);
const versionMap = /* @__PURE__ */ new Map();
versionMap.set(versionResult.id, 100);
await createDeployment(
props.config,
accountId,
scriptName,
versionMap,
void 0
);
await patchNonVersionedScriptSettings(
props.config,
accountId,
scriptName,
{
tail_consumers: worker.tail_consumers,
logpush: worker.logpush,
// If the user hasn't specified observability assume that they want it disabled if they have it on.
// This is a no-op in the event that they don't have observability enabled, but will remove observability
// if it has been removed from their Wrangler configuration file
observability: worker.observability ?? { enabled: false }
}
);
result = {
id: null,
// fpw - ignore
etag: versionResult.resources.script.etag,
pipeline_hash: null,
// fpw - ignore
mutable_pipeline_id: null,
// fpw - ignore
deployment_id: versionResult.id,
// version id not deployment id but easier to adapt here
startup_time_ms: versionResult.startup_time_ms
};
} else {
result = await retryOnAPIFailure(
async () => fetchResult(
config,
workerUrl,
{
method: "PUT",
body: workerBundle,
headers: await getMetricsUsageHeaders(config.send_metrics)
},
new import_node_url9.URLSearchParams({
// pass excludeScript so the whole body of the
// script doesn't get included in the response
excludeScript: "true"
})
)
);
}
if (result.startup_time_ms) {
logger.log("Worker Startup Time:", result.startup_time_ms, "ms");
}
bindingsPrinted = true;
printBindings(
{ ...withoutStaticAssets, vars: maskedVars },
config.tail_consumers
);
versionId = parseNonHyphenedUuid(result.deployment_id);
if (config.first_party_worker) {
if (result.id) {
logger.log("Worker ID: ", result.id);
}
if (result.etag) {
logger.log("Worker ETag: ", result.etag);
}
if (result.pipeline_hash) {
logger.log("Worker PipelineHash: ", result.pipeline_hash);
}
if (result.mutable_pipeline_id) {
logger.log(
"Worker Mutable PipelineID (Development ONLY!):",
result.mutable_pipeline_id
);
}
}
} catch (err) {
if (!bindingsPrinted) {
printBindings(
{ ...withoutStaticAssets, vars: maskedVars },
config.tail_consumers
);
}
const message = await helpIfErrorIsSizeOrScriptStartup(
err,
dependencies,
workerBundle,
props.projectRoot
);
if (message !== null) {
logger.error(message);
}
if (err instanceof APIError && "code" in err && err.code === 10021 && err.notes.length > 0) {
err.preventReport();
if (err.notes[0].text === "binding DB of type d1 must have a valid `id` specified [code: 10021]") {
throw new UserError(
"You must use a real database in the database_id configuration. You can find your databases using 'wrangler d1 list', or read how to develop locally with D1 here: https://developers.cloudflare.com/d1/configuration/local-development",
{ telemetryMessage: true }
);
}
const maybeNameToFilePath = /* @__PURE__ */ __name((moduleName) => {
if (bundleType === "commonjs") {
return resolvedEntryPointPath;
}
if (moduleName === entryPointName) {
return resolvedEntryPointPath;
}
for (const module3 of modules) {
if (moduleName === module3.name) {
return module3.filePath;
}
}
}, "maybeNameToFilePath");
const retrieveSourceMap = /* @__PURE__ */ __name((moduleName) => maybeRetrieveFileSourceMap(maybeNameToFilePath(moduleName)), "retrieveSourceMap");
err.notes[0].text = getSourceMappedString(
err.notes[0].text,
retrieveSourceMap
);
}
throw err;
}
}
if (props.outFile) {
(0, import_node_fs33.mkdirSync)(import_node_path58.default.dirname(props.outFile), { recursive: true });
const serializedFormData = await new import_undici21.Response(workerBundle).arrayBuffer();
(0, import_node_fs33.writeFileSync)(props.outFile, Buffer.from(serializedFormData));
}
} finally {
if (typeof destination !== "string") {
destination.remove();
}
}
if (props.dryRun) {
logger.log(`--dry-run: exiting now.`);
return { versionId, workerTag };
}
const uploadMs = Date.now() - start;
logger.log("Uploaded", workerName, formatTime(uploadMs));
if (props.dispatchNamespace !== void 0) {
deployWfpUserWorker(props.dispatchNamespace, versionId);
return { versionId, workerTag };
}
if (normalisedContainerConfig.length) {
(0, import_node_assert25.default)(versionId && accountId);
await deployContainers(config, normalisedContainerConfig, {
versionId,
accountId,
scriptName,
dryRun: props.dryRun ?? false
});
}
const targets = await triggersDeploy({
...props,
routes: allRoutes
});
logger.log("Current Version ID:", versionId);
return {
sourceMapSize,
versionId,
workerTag,
targets: targets ?? []
};
}
function deployWfpUserWorker(dispatchNamespace, versionId) {
logger.log(" Dispatch Namespace:", dispatchNamespace);
logger.log("Current Version ID:", versionId);
}
function formatTime(duration) {
return `(${(duration / 1e3).toFixed(2)} sec)`;
}
async function publishRoutes(complianceConfig, routes, {
workerUrl,
scriptName,
notProd,
accountId
}) {
try {
return await fetchResult(complianceConfig, `${workerUrl}/routes`, {
// Note: PUT will delete previous routes on this script.
method: "PUT",
body: JSON.stringify(
routes.map(
(route) => typeof route !== "object" ? { pattern: route } : route
)
),
headers: {
"Content-Type": "application/json"
}
});
} catch (e7) {
if (isAuthenticationError(e7)) {
return await publishRoutesFallback(complianceConfig, routes, {
scriptName,
notProd,
accountId
});
} else {
throw e7;
}
}
}
async function publishRoutesFallback(complianceConfig, routes, {
scriptName,
notProd,
accountId
}) {
if (notProd) {
throw new UserError(
"Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\nEither turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth",
{ telemetryMessage: true }
);
}
logger.warn(
"The current authentication token does not have 'All Zones' permissions.\nFalling back to using the zone-based API endpoint to update each route individually.\nNote that there is no access to routes associated with zones that the API token does not have permission for.\nExisting routes for this Worker in such zones will not be deleted."
);
const deployedRoutes = [];
const queue = new PQueue({ concurrency: 10 });
const queuePromises = [];
const zoneIdCache = /* @__PURE__ */ new Map();
const activeZones = /* @__PURE__ */ new Map();
const routesToDeploy = /* @__PURE__ */ new Map();
for (const route of routes) {
queuePromises.push(
queue.add(async () => {
const zone = await getZoneForRoute(
complianceConfig,
{ route, accountId },
zoneIdCache
);
if (zone) {
activeZones.set(zone.id, zone.host);
routesToDeploy.set(
typeof route === "string" ? route : route.pattern,
zone.id
);
}
})
);
}
await Promise.all(queuePromises.splice(0, queuePromises.length));
const allRoutes = /* @__PURE__ */ new Map();
const alreadyDeployedRoutes = /* @__PURE__ */ new Set();
for (const [zone, host] of activeZones) {
queuePromises.push(
queue.add(async () => {
try {
for (const { pattern, script } of await fetchListResult(complianceConfig, `/zones/${zone}/workers/routes`)) {
allRoutes.set(pattern, script);
if (script === scriptName) {
alreadyDeployedRoutes.add(pattern);
}
}
} catch (e7) {
if (isAuthenticationError(e7)) {
e7.notes.push({
text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`
});
}
throw e7;
}
})
);
}
await Promise.all(queuePromises);
for (const [routePattern, zoneId] of routesToDeploy.entries()) {
if (allRoutes.has(routePattern)) {
const knownScript = allRoutes.get(routePattern);
if (knownScript === scriptName) {
alreadyDeployedRoutes.delete(routePattern);
continue;
} else {
throw new UserError(
`The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`,
{ telemetryMessage: "route already associated with another worker" }
);
}
}
const { pattern } = await fetchResult(
complianceConfig,
`/zones/${zoneId}/workers/routes`,
{
method: "POST",
body: JSON.stringify({
pattern: routePattern,
script: scriptName
}),
headers: {
"Content-Type": "application/json"
}
}
);
deployedRoutes.push(pattern);
}
if (alreadyDeployedRoutes.size) {
logger.warn(
"Previously deployed routes:\nThe following routes were already associated with this worker, and have not been deleted:\n" + [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"
`) + "If these routes are not wanted then you can remove them in the dashboard."
);
}
return deployedRoutes;
}
function isAuthenticationError(e7) {
return e7 instanceof ParseError && e7.code === 1e4;
}
async function updateQueueConsumers(scriptName, config) {
const consumers = config.queues.consumers || [];
const updateConsumers = [];
for (const consumer of consumers) {
const queue = await getQueue(config, consumer.queue);
if (consumer.type === "http_pull") {
const body = {
type: consumer.type,
dead_letter_queue: consumer.dead_letter_queue,
settings: {
batch_size: consumer.max_batch_size,
max_retries: consumer.max_retries,
visibility_timeout_ms: consumer.visibility_timeout_ms,
retry_delay: consumer.retry_delay
}
};
const existingConsumer = queue.consumers && queue.consumers[0];
if (existingConsumer) {
updateConsumers.push(
putConsumerById(
config,
queue.queue_id,
existingConsumer.consumer_id,
body
).then(() => [`Consumer for ${consumer.queue}`])
);
continue;
}
updateConsumers.push(
postConsumer(config, consumer.queue, body).then(() => [
`Consumer for ${consumer.queue}`
])
);
} else {
if (scriptName === void 0) {
throw new UserError(
"Script name is required to update queue consumers",
{ telemetryMessage: true }
);
}
const body = {
type: "worker",
dead_letter_queue: consumer.dead_letter_queue,
script_name: scriptName,
settings: {
batch_size: consumer.max_batch_size,
max_retries: consumer.max_retries,
max_wait_time_ms: consumer.max_batch_timeout !== void 0 ? 1e3 * consumer.max_batch_timeout : void 0,
max_concurrency: consumer.max_concurrency,
retry_delay: consumer.retry_delay
}
};
const existingConsumer = queue.consumers.filter(
(c6) => c6.script === scriptName || c6.service === scriptName
).length > 0;
const envName = void 0;
if (existingConsumer) {
updateConsumers.push(
putConsumer(config, consumer.queue, scriptName, envName, body).then(
() => [`Consumer for ${consumer.queue}`]
)
);
continue;
}
updateConsumers.push(
postConsumer(config, consumer.queue, body).then(() => [
`Consumer for ${consumer.queue}`
])
);
}
}
return updateConsumers;
}
var import_node_assert25, import_node_fs33, import_node_path58, import_node_url9, import_undici21, validateRoutes3;
var init_deploy8 = __esm({
"src/deploy/deploy.ts"() {
init_import_meta_url();
import_node_assert25 = __toESM(require("assert"));
import_node_fs33 = require("fs");
import_node_path58 = __toESM(require("path"));
import_node_url9 = require("url");
init_cli();
init_containers_shared();
init_dist2();
import_undici21 = __toESM(require_undici());
init_assets();
init_cfetch();
init_deploy2();
init_config2();
init_config3();
init_bindings();
init_bundle();
init_bundle_reporter();
init_create_worker_upload_form();
init_log_build_output();
init_module_collection();
init_no_bundle_worker();
init_node_compat();
init_source_maps();
init_dialogs();
init_durable();
init_misc_variables();
init_errors();
init_experimental_flags();
init_init();
init_logger();
init_metrics();
init_navigator_user_agent();
init_parse();
init_paths();
init_client2();
init_sites();
init_sourcemap();
init_deploy3();
init_compatibility_date();
init_friendly_validator_errors();
init_print_bindings();
init_retry();
init_api();
init_deploy7();
init_zones();
init_config_diffs();
validateRoutes3 = /* @__PURE__ */ __name((routes, assets) => {
const invalidRoutes = {};
const mountedAssetRoutes = [];
for (const route of routes) {
if (typeof route !== "string" && route.custom_domain) {
if (route.pattern.includes("*")) {
invalidRoutes[route.pattern] ??= [];
invalidRoutes[route.pattern].push(
`Wildcard operators (*) are not allowed in Custom Domains`
);
}
if (route.pattern.includes("/")) {
invalidRoutes[route.pattern] ??= [];
invalidRoutes[route.pattern].push(
`Paths are not allowed in Custom Domains`
);
}
} else if (
// If we have Assets but we're not always hitting the Worker then validate
assets?.directory !== void 0 && assets.routerConfig.invoke_user_worker_ahead_of_assets !== true
) {
const pattern = typeof route === "string" ? route : route.pattern;
const components = pattern.split("/");
if (!(components.length === 2 && components[1] === "*")) {
mountedAssetRoutes.push(pattern);
}
}
}
if (Object.keys(invalidRoutes).length > 0) {
throw new UserError(
`Invalid Routes:
` + Object.entries(invalidRoutes).map(([route, errors]) => `${route}:
` + errors.join("\n")).join(`
`)
);
}
if (mountedAssetRoutes.length > 0 && assets?.directory !== void 0) {
const relativeAssetsDir = import_node_path58.default.relative(process.cwd(), assets.directory);
logger.once.warn(
`Warning: The following routes will attempt to serve Assets on a configured path:
${mountedAssetRoutes.map((route) => {
const routeNoScheme = route.replace(/https?:\/\//g, "");
const assetPath = import_node_path58.default.join(
relativeAssetsDir,
routeNoScheme.substring(routeNoScheme.indexOf("/"))
);
return ` \u2022 ${route} (Will match assets: ${assetPath})`;
}).join("\n")}` + (assets?.routerConfig.has_user_worker ? "\n\nRequests not matching an asset will be forwarded to the Worker's code." : "")
);
}
}, "validateRoutes");
__name(renderRoute, "renderRoute");
__name(publishCustomDomains, "publishCustomDomains");
__name(deploy, "deploy");
__name(deployWfpUserWorker, "deployWfpUserWorker");
__name(formatTime, "formatTime");
__name(publishRoutes, "publishRoutes");
__name(publishRoutesFallback, "publishRoutesFallback");
__name(isAuthenticationError, "isAuthenticationError");
__name(updateQueueConsumers, "updateQueueConsumers");
}
});
// src/assets.ts
function logAssetUpload(line, diffCount) {
const level = logger.loggerLevel;
if (LOGGER_LEVELS[level] >= LOGGER_LEVELS.debug) {
logger.debug(line);
} else if (diffCount < MAX_DIFF_LINES2) {
logger.info(line);
} else if (diffCount === MAX_DIFF_LINES2) {
const msg = " (truncating changed assets log, set `WRANGLER_LOG=debug` environment variable to see full diff)";
logger.info(source_default.dim(msg));
}
return diffCount++;
}
function logAssetsUploadStatus(numberFilesToUpload, uploadedAssetsCount, uploadedAssetFiles) {
logger.info(
`Uploaded ${uploadedAssetsCount} of ${numberFilesToUpload} assets`
);
uploadedAssetFiles.forEach((file) => logger.debug(`\u2728 ${file}`));
}
function logReadFilesFromDirectory(directory, assetFiles) {
logger.info(
`\u2728 Read ${assetFiles.length} file${assetFiles.length === 1 ? "" : "s"} from the assets directory ${directory}`
);
assetFiles.forEach((file) => logger.debug(`/${file}`));
}
function getAssetsBasePath(config, assetsCommandLineArg) {
return assetsCommandLineArg ? process.cwd() : path61.resolve(path61.dirname(config.configPath ?? "wrangler.toml"));
}
function getAssetsOptions(args, config, overrides) {
if (!overrides && !config.assets && !args.assets) {
return;
}
const assets = {
...config.assets,
...args.assets && { directory: args.assets },
...overrides
};
if (assets.directory === void 0) {
throw new UserError(
"The `assets` property in your configuration is missing the required `directory` property.",
{ telemetryMessage: true }
);
}
if (assets.directory === "") {
throw new UserError("`The assets directory cannot be an empty string.", {
telemetryMessage: true
});
}
const assetsBasePath = getAssetsBasePath(config, args.assets);
const directory = path61.resolve(assetsBasePath, assets.directory);
if (!(0, import_node_fs34.existsSync)(directory)) {
const sourceOfTruthMessage = args.assets ? '"--assets" command line argument' : '"assets.directory" field in your configuration file';
throw new NonExistentAssetsDirError(
`The directory specified by the ${sourceOfTruthMessage} does not exist:
${directory}`,
{
telemetryMessage: `The assets directory specified does not exist`
}
);
}
const routerConfig = {
has_user_worker: Boolean(args.script || config.main)
};
if (typeof config.assets?.run_worker_first === "boolean") {
routerConfig.invoke_user_worker_ahead_of_assets = config.assets.run_worker_first;
} else if (Array.isArray(config.assets?.run_worker_first)) {
routerConfig.static_routing = parseStaticRouting(
config.assets.run_worker_first
);
}
if (routerConfig.invoke_user_worker_ahead_of_assets && !config?.assets?.binding) {
logger.warn(
"run_worker_first=true set without an assets binding\nSetting run_worker_first to true will always invoke your Worker script.\nTo fetch your assets from your Worker, please set the [assets.binding] key in your configuration file.\n\nRead more: https://developers.cloudflare.com/workers/static-assets/binding/#binding"
);
}
if (!routerConfig.has_user_worker && (routerConfig.invoke_user_worker_ahead_of_assets === true || routerConfig.static_routing)) {
throw new UserError(
"Cannot set run_worker_first without a Worker script.\nPlease remove run_worker_first from your configuration file, or provide a Worker script in your configuration file (`main`).",
{ telemetryMessage: true }
);
}
const _redirects = maybeGetFile(path61.join(directory, REDIRECTS_FILENAME));
const _headers = maybeGetFile(path61.join(directory, HEADERS_FILENAME));
const assetConfig = {
html_handling: config.assets?.html_handling,
not_found_handling: config.assets?.not_found_handling,
// The _redirects and _headers files are parsed in Miniflare in dev and parsing is not required for deploy
compatibility_date: config.compatibility_date,
compatibility_flags: config.compatibility_flags
};
return {
directory,
binding: assets.binding,
routerConfig,
assetConfig,
_redirects,
_headers,
// raw static routing rules for upload. routerConfig.static_routing contains the rules processed for dev.
run_worker_first: config.assets?.run_worker_first
};
}
function validateAssetsArgsAndConfig(args, config) {
if ("legacy" in args ? args.assets && args.legacy.site : (args.assets || config?.assets) && (args.site || config?.site)) {
throw new UserError(
"Cannot use assets and Workers Sites in the same Worker.\nPlease remove either the `site` or `assets` field from your configuration file.",
{ telemetryMessage: true }
);
}
const noOpEntrypoint = path61.resolve(
getBasePath(),
"templates/no-op-worker.js"
);
if ("legacy" in args ? args.entrypoint === noOpEntrypoint && args.assets?.binding : !(args.script || config?.main) && config?.assets?.binding) {
throw new UserError(
"Cannot use assets with a binding in an assets-only Worker.\nPlease remove the asset binding from your configuration file, or provide a Worker script in your configuration file (`main`).",
{ telemetryMessage: true }
);
}
if (config?.placement?.mode === "smart" && config?.assets?.run_worker_first === true) {
logger.warn(
"Turning on Smart Placement in a Worker that is using assets and run_worker_first set to true means that your entire Worker could be moved to run closer to your data source, and all requests will go to that Worker before serving assets.\nThis could result in poor performance as round trip times could increase when serving assets.\n\nRead more: https://developers.cloudflare.com/workers/static-assets/binding/#smart-placement"
);
}
}
function errorOnLegacyPagesWorkerJSAsset(file, hasAssetsIgnoreFile) {
if (!hasAssetsIgnoreFile) {
const workerJsType = file === WORKER_JS_FILENAME ? "file" : file.startsWith(WORKER_JS_FILENAME) ? "directory" : null;
if (workerJsType !== null) {
throw new UserError(
dedent2`
Uploading a Pages ${WORKER_JS_FILENAME} ${workerJsType} as an asset.
This could expose your private server-side code to the public Internet. Is this intended?
If you do not want to upload this ${workerJsType}, either remove it or add an "${CF_ASSETS_IGNORE_FILENAME}" file, to the root of your asset directory, containing "${WORKER_JS_FILENAME}" to avoid uploading.
If you do want to upload this ${workerJsType}, you can add an empty "${CF_ASSETS_IGNORE_FILENAME}" file, to the root of your asset directory, to hide this error.
`,
{ telemetryMessage: true }
);
}
}
}
var import_node_assert26, import_node_fs34, import_promises35, path61, import_undici22, BULK_UPLOAD_CONCURRENCY2, MAX_UPLOAD_ATTEMPTS2, MAX_UPLOAD_GATEWAY_ERRORS2, MAX_DIFF_LINES2, syncAssets, buildAssetManifest, NonExistentAssetsDirError, WORKER_JS_FILENAME;
var init_assets = __esm({
"src/assets.ts"() {
init_import_meta_url();
import_node_assert26 = __toESM(require("assert"));
import_node_fs34 = require("fs");
import_promises35 = require("fs/promises");
path61 = __toESM(require("path"));
init_parseStaticRouting();
init_constants2();
init_helpers2();
init_source();
init_dist2();
init_pretty_bytes();
import_undici22 = __toESM(require_undici());
init_cfetch();
init_deploy8();
init_errors();
init_logger();
init_hash();
init_upload();
init_parse();
init_paths();
init_dedent();
BULK_UPLOAD_CONCURRENCY2 = 3;
MAX_UPLOAD_ATTEMPTS2 = 5;
MAX_UPLOAD_GATEWAY_ERRORS2 = 5;
MAX_DIFF_LINES2 = 100;
syncAssets = /* @__PURE__ */ __name(async (complianceConfig, accountId, assetDirectory, scriptName, dispatchNamespace) => {
(0, import_node_assert26.default)(accountId, "Missing accountId");
logger.info("\u{1F300} Building list of assets...");
const manifest = await buildAssetManifest(assetDirectory);
const url4 = dispatchNamespace ? `/accounts/${accountId}/workers/dispatch/namespaces/${dispatchNamespace}/scripts/${scriptName}/assets-upload-session` : `/accounts/${accountId}/workers/scripts/${scriptName}/assets-upload-session`;
logger.info("\u{1F300} Starting asset upload...");
const initializeAssetsResponse = await fetchResult(
complianceConfig,
url4,
{
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ manifest })
}
);
if (initializeAssetsResponse.buckets.flat().length === 0) {
if (!initializeAssetsResponse.jwt) {
throw new FatalError(
"Could not find assets information to attach to deployment. Please try again.",
1,
{ telemetryMessage: true }
);
}
logger.info(
`No updated asset files to upload. Proceeding with deployment...`
);
return initializeAssetsResponse.jwt;
}
const numberFilesToUpload = initializeAssetsResponse.buckets.flat().length;
logger.info(
`\u{1F300} Found ${numberFilesToUpload} new or modified static asset${numberFilesToUpload > 1 ? "s" : ""} to upload. Proceeding with upload...`
);
const manifestLookup = Object.entries(manifest);
let assetLogCount = 0;
const assetBuckets = initializeAssetsResponse.buckets.map((bucket) => {
return bucket.map((fileHash) => {
const manifestEntry = manifestLookup.find(
(file) => file[1].hash === fileHash
);
if (manifestEntry === void 0) {
throw new FatalError(
`A file was requested that does not appear to exist.`,
1,
{
telemetryMessage: "A file was requested that does not appear to exist. (asset manifest upload)"
}
);
}
assetLogCount = logAssetUpload(`+ ${manifestEntry[0]}`, assetLogCount);
return manifestEntry;
});
});
const queue = new PQueue({ concurrency: BULK_UPLOAD_CONCURRENCY2 });
const queuePromises = [];
let attempts = 0;
const start = Date.now();
let completionJwt = "";
let uploadedAssetsCount = 0;
for (const [bucketIndex, bucket] of assetBuckets.entries()) {
attempts = 0;
let gatewayErrors = 0;
const doUpload = /* @__PURE__ */ __name(async () => {
const payload = new import_undici22.FormData();
const uploadedFiles = [];
for (const manifestEntry of bucket) {
const absFilePath = path61.join(assetDirectory, manifestEntry[0]);
uploadedFiles.push(manifestEntry[0]);
payload.append(
manifestEntry[1].hash,
new File(
[(await (0, import_promises35.readFile)(absFilePath)).toString("base64")],
manifestEntry[1].hash,
{
// Most formdata body encoders (incl. undici's) will override with "application/octet-stream" if you use a falsy value here
// Additionally, it appears that undici doesn't support non-standard main types (e.g. "null")
// So, to make it easier for any other clients, we'll just parse "application/null" on the API
// to mean actually null (signal to not send a Content-Type header with the response)
type: getContentType(absFilePath) ?? "application/null"
}
),
manifestEntry[1].hash
);
}
try {
const res = await fetchResult(
complianceConfig,
`/accounts/${accountId}/workers/assets/upload?base64=true`,
{
method: "POST",
headers: {
Authorization: `Bearer ${initializeAssetsResponse.jwt}`
},
body: payload
}
);
uploadedAssetsCount += bucket.length;
logAssetsUploadStatus(
numberFilesToUpload,
uploadedAssetsCount,
uploadedFiles
);
return res;
} catch (e7) {
if (attempts < MAX_UPLOAD_ATTEMPTS2) {
logger.info(source_default.dim(`Asset upload failed. Retrying...
`, e7));
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, attempts) * 1e3)
);
if (e7 instanceof APIError && e7.isGatewayError()) {
queue.concurrency = 1;
await new Promise(
(resolvePromise) => setTimeout(resolvePromise, Math.pow(2, gatewayErrors) * 5e3)
);
gatewayErrors++;
if (gatewayErrors >= MAX_UPLOAD_GATEWAY_ERRORS2) {
attempts++;
}
} else {
attempts++;
}
return doUpload();
} else if (isJwtExpired(initializeAssetsResponse.jwt)) {
throw new FatalError(
`Upload took too long.
Asset upload took too long on bucket ${bucketIndex + 1}/${initializeAssetsResponse.buckets.length}. Please try again.
Assets already uploaded have been saved, so the next attempt will automatically resume from this point.`,
void 0,
{ telemetryMessage: "Asset upload took too long" }
);
} else {
throw e7;
}
}
}, "doUpload");
queuePromises.push(
queue.add(
() => doUpload().then((res) => {
completionJwt = res.jwt || completionJwt;
})
)
);
}
queue.on("error", (error2) => {
logger.error(error2.message);
throw error2;
});
await Promise.all(queuePromises);
if (!completionJwt) {
throw new FatalError(
"Failed to complete asset upload. Please try again.",
1,
{ telemetryMessage: true }
);
}
const uploadMs = Date.now() - start;
const skipped = Object.keys(manifest).length - numberFilesToUpload;
const skippedMessage = skipped > 0 ? `(${skipped} already uploaded) ` : "";
logger.log(
`\u2728 Success! Uploaded ${numberFilesToUpload} file${numberFilesToUpload > 1 ? "s" : ""} ${skippedMessage}${formatTime(uploadMs)}
`
);
return completionJwt;
}, "syncAssets");
buildAssetManifest = /* @__PURE__ */ __name(async (dir) => {
const files = await (0, import_promises35.readdir)(dir, { recursive: true });
logReadFilesFromDirectory(dir, files);
const manifest = {};
let counter = 0;
const { assetsIgnoreFunction, assetsIgnoreFilePresent } = await createAssetsIgnoreFunction(dir);
await Promise.all(
files.map(async (relativeFilepath) => {
if (assetsIgnoreFunction(relativeFilepath)) {
logger.debug("Ignoring asset:", relativeFilepath);
return;
}
const filepath = path61.join(dir, relativeFilepath);
const filestat = await (0, import_promises35.stat)(filepath);
if (filestat.isSymbolicLink() || filestat.isDirectory()) {
return;
} else {
errorOnLegacyPagesWorkerJSAsset(
relativeFilepath,
assetsIgnoreFilePresent
);
if (counter >= MAX_ASSET_COUNT2) {
throw new UserError(
`Maximum number of assets exceeded.
Cloudflare Workers supports up to ${MAX_ASSET_COUNT2.toLocaleString()} assets in a version. We found ${counter.toLocaleString()} files in the specified assets directory "${dir}".
Ensure your assets directory contains a maximum of ${MAX_ASSET_COUNT2.toLocaleString()} files, and that you have specified your assets directory correctly.`,
{ telemetryMessage: "Maximum number of assets exceeded" }
);
}
if (filestat.size > MAX_ASSET_SIZE2) {
throw new UserError(
`Asset too large.
Cloudflare Workers supports assets with sizes of up to ${prettyBytes(
MAX_ASSET_SIZE2,
{
binary: true
}
)}. We found a file ${filepath} with a size of ${prettyBytes(
filestat.size,
{
binary: true
}
)}.
Ensure all assets in your assets directory "${dir}" conform with the Workers maximum size requirement.`,
{ telemetryMessage: "Asset too large" }
);
}
manifest[normalizeFilePath(relativeFilepath)] = {
hash: hashFile(filepath),
size: filestat.size
};
counter++;
}
})
);
return manifest;
}, "buildAssetManifest");
__name(logAssetUpload, "logAssetUpload");
__name(logAssetsUploadStatus, "logAssetsUploadStatus");
__name(logReadFilesFromDirectory, "logReadFilesFromDirectory");
__name(getAssetsBasePath, "getAssetsBasePath");
NonExistentAssetsDirError = class extends UserError {
static {
__name(this, "NonExistentAssetsDirError");
}
};
__name(getAssetsOptions, "getAssetsOptions");
__name(validateAssetsArgsAndConfig, "validateAssetsArgsAndConfig");
WORKER_JS_FILENAME = "_worker.js";
__name(errorOnLegacyPagesWorkerJSAsset, "errorOnLegacyPagesWorkerJSAsset");
}
});
// src/type-generation/helpers.ts
var import_fs27, import_workerd2, checkTypesDiff;
var init_helpers8 = __esm({
"src/type-generation/helpers.ts"() {
init_import_meta_url();
import_fs27 = require("fs");
import_workerd2 = require("workerd");
init_logger();
init_type_generation();
checkTypesDiff = /* @__PURE__ */ __name(async (config, entry) => {
if (!entry.file.endsWith(".ts")) {
return;
}
let maybeExistingTypesFileLines;
try {
maybeExistingTypesFileLines = (0, import_fs27.readFileSync)(
"./worker-configuration.d.ts",
"utf-8"
).split("\n");
} catch {
return;
}
const existingEnvHeader = maybeExistingTypesFileLines.find(
(line) => line.startsWith("// Generated by Wrangler by running")
);
const maybeExistingHash = existingEnvHeader?.match(/hash: (?<hash>.*)\)/)?.groups?.hash;
const previousStrictVars = existingEnvHeader?.match(
/--strict-vars(=|\s)(?<result>true|false)/
)?.groups?.result;
const previousEnvInterface = existingEnvHeader?.match(
/--env-interface(=|\s)(?<result>[a-zA-Z][a-zA-Z0-9_]*)/
)?.groups?.result;
let newEnvHeader;
try {
const { envHeader } = await generateEnvTypes(
config,
{ strictVars: previousStrictVars === "false" ? false : true },
previousEnvInterface ?? "Env",
"worker-configuration.d.ts",
entry,
/* @__PURE__ */ new Map(),
// don't log anything
false
);
newEnvHeader = envHeader;
} catch (e7) {
logger.error(e7);
}
const newHash = newEnvHeader?.match(/hash: (?<hash>.*)\)/)?.groups?.hash;
const existingRuntimeHeader = maybeExistingTypesFileLines.find(
(line) => line.startsWith("// Runtime types generated with")
);
const newRuntimeHeader = `// Runtime types generated with workerd@${import_workerd2.version} ${config.compatibility_date} ${config.compatibility_flags.sort().join(",")}`;
const envOutOfDate = existingEnvHeader && maybeExistingHash !== newHash;
const runtimeOutOfDate = existingRuntimeHeader && existingRuntimeHeader !== newRuntimeHeader;
return envOutOfDate || runtimeOutOfDate;
}, "checkTypesDiff");
}
});
// src/utils/memoizeGetPort.ts
function memoizeGetPort(defaultPort, host) {
let portValue;
let cachedHost = host;
return async (forHost = host) => {
if (forHost !== cachedHost) {
portValue = void 0;
cachedHost = forHost;
}
portValue = portValue ?? await getPorts({ port: defaultPort, host });
return portValue;
};
}
var init_memoizeGetPort = __esm({
"src/utils/memoizeGetPort.ts"() {
init_import_meta_url();
init_get_port();
__name(memoizeGetPort, "memoizeGetPort");
}
});
// src/api/startDevWorker/ConfigController.ts
async function resolveDevConfig(config, input) {
const auth = /* @__PURE__ */ __name(async () => {
if (input.dev?.remote) {
const isLoggedIn = await loginOrRefreshIfRequired(config);
if (!isLoggedIn) {
throw new UserError(
"You must be logged in to use wrangler dev in remote mode. Try logging in, or run wrangler dev --local."
);
}
}
if (input.dev?.auth) {
return unwrapHook(input.dev.auth, config);
}
return {
accountId: await requireAuth(config),
apiToken: requireApiToken()
};
}, "auth");
const localPersistencePath = getLocalPersistencePath(
input.dev?.persist,
config
);
const { host, routes } = await getHostAndRoutes(
{
host: input.dev?.origin?.hostname,
routes: input.triggers?.filter(
(t7) => t7.type === "route"
),
assets: input?.assets
},
config
);
if (input.dev?.remote) {
const { accountId } = await auth();
(0, import_node_assert27.default)(accountId, "Account ID must be provided for remote dev");
await getZoneIdForPreview(config, { host, routes, accountId });
}
const initialIp = input.dev?.server?.hostname ?? config.dev.ip;
const initialIpListenCheck = initialIp === "*" ? "0.0.0.0" : initialIp;
const useContainers = config.dev.enable_containers && config.containers?.length;
return {
auth,
remote: input.dev?.remote,
server: {
hostname: input.dev?.server?.hostname || config.dev.ip,
port: input.dev?.server?.port ?? config.dev.port ?? await getLocalPort(initialIpListenCheck),
secure: input.dev?.server?.secure ?? config.dev.local_protocol === "https",
httpsKeyPath: input.dev?.server?.httpsKeyPath,
httpsCertPath: input.dev?.server?.httpsCertPath
},
inspector: input.dev?.inspector === false ? false : {
port: input.dev?.inspector?.port ?? config.dev.inspector_port ?? await getInspectorPort()
},
origin: {
secure: input.dev?.origin?.secure ?? config.dev.upstream_protocol === "https",
hostname: host ?? getInferredHost(routes, config.configPath)
},
liveReload: input.dev?.liveReload || false,
testScheduled: input.dev?.testScheduled,
// absolute resolved path
persist: localPersistencePath,
registry: input.dev?.registry,
bindVectorizeToProd: input.dev?.bindVectorizeToProd ?? false,
multiworkerPrimary: input.dev?.multiworkerPrimary,
imagesLocalMode: input.dev?.imagesLocalMode ?? false,
experimentalRemoteBindings: input.dev?.experimentalRemoteBindings ?? getFlag("REMOTE_BINDINGS"),
enableContainers: input.dev?.enableContainers ?? config.dev.enable_containers,
dockerPath: input.dev?.dockerPath ?? getDockerPath(),
containerEngine: useContainers ? input.dev?.containerEngine ?? config.dev.container_engine ?? resolveDockerHost(input.dev?.dockerPath ?? getDockerPath()) : void 0,
containerBuildId: input.dev?.containerBuildId
};
}
async function resolveBindings(config, input) {
const bindings = getBindings2(
config,
input.env,
input.envFiles,
!input.dev?.remote,
{
kv: extractBindingsOfType("kv_namespace", input.bindings),
vars: Object.fromEntries(
extractBindingsOfType("plain_text", input.bindings).map((b6) => [
b6.binding,
b6.value
])
),
durableObjects: extractBindingsOfType(
"durable_object_namespace",
input.bindings
),
r2: extractBindingsOfType("r2_bucket", input.bindings),
services: extractBindingsOfType("service", input.bindings),
d1Databases: extractBindingsOfType("d1", input.bindings),
ai: extractBindingsOfType("ai", input.bindings)?.[0],
version_metadata: extractBindingsOfType(
"version_metadata",
input.bindings
)?.[0]
},
input.dev?.experimentalRemoteBindings
);
const printCurrentBindings = /* @__PURE__ */ __name((registry) => {
const maskedVars = maskVars(bindings, config);
printBindings(
{
...bindings,
vars: maskedVars
},
input.tailConsumers ?? config.tail_consumers,
{
registry,
local: !input.dev?.remote,
imagesLocalMode: input.dev?.imagesLocalMode,
name: config.name,
vectorizeBindToProd: input.dev?.bindVectorizeToProd
}
);
}, "printCurrentBindings");
printCurrentBindings(
input.dev?.registry ? (0, import_miniflare22.getWorkerRegistry)(input.dev.registry) : null
);
return {
bindings: {
...input.bindings,
...convertCfWorkerInitBindingsToBindings(bindings)
},
unsafe: bindings.unsafe,
printCurrentBindings
};
}
async function resolveTriggers(config, input) {
const { routes } = await getHostAndRoutes(
{
host: input.dev?.origin?.hostname,
routes: input.triggers?.filter(
(t7) => t7.type === "route"
),
assets: input?.assets
},
config
);
const devRoutes = routes?.map(
(r7) => typeof r7 === "string" ? {
type: "route",
pattern: r7
} : { type: "route", ...r7 }
) ?? [];
const queueConsumers = config.queues.consumers?.map(
(c6) => ({
...c6,
type: "queue-consumer"
})
) ?? [];
const crons = config.triggers.crons?.map((c6) => ({
cron: c6,
type: "cron"
})) ?? [];
return [...devRoutes, ...queueConsumers, ...crons];
}
async function resolveConfig(config, input) {
if (config.pages_build_output_dir && input.dev?.multiworkerPrimary === false) {
throw new UserError(
`You cannot use a Pages project as a service binding target.
If you are trying to develop Pages and Workers together, please use \`wrangler pages dev\`. Note the first config file specified must be for the Pages project`
);
}
const legacySite = unwrapHook(input.legacy?.site, config);
const entry = await getEntry(
{
script: input.entrypoint,
moduleRoot: input.build?.moduleRoot,
// getEntry only needs to know if assets was specified.
// The actualy value is not relevant here, which is why not passing
// the entire Assets object is fine.
assets: input?.assets
},
config,
"dev"
);
const nodejsCompatMode = unwrapHook(input.build?.nodejsCompatMode, config);
const { bindings, unsafe, printCurrentBindings } = await resolveBindings(
config,
input
);
const assetsOptions = getAssetsOptions(
{
assets: input?.assets,
script: input.entrypoint
},
config
);
const resolved = {
name: getScriptName({ name: input.name, env: input.env }, config) ?? "worker",
config: config.configPath,
compatibilityDate: getDevCompatibilityDate(config, input.compatibilityDate),
compatibilityFlags: input.compatibilityFlags ?? config.compatibility_flags,
complianceRegion: input.complianceRegion ?? config.compliance_region,
entrypoint: entry.file,
projectRoot: entry.projectRoot,
bindings,
migrations: input.migrations ?? config.migrations,
sendMetrics: input.sendMetrics ?? config.send_metrics,
triggers: await resolveTriggers(config, input),
env: input.env,
envFiles: input.envFiles,
build: {
alias: input.build?.alias ?? config.alias,
additionalModules: input.build?.additionalModules ?? [],
processEntrypoint: Boolean(input.build?.processEntrypoint),
bundle: input.build?.bundle ?? !config.no_bundle,
findAdditionalModules: input.build?.findAdditionalModules ?? config.find_additional_modules,
moduleRoot: entry.moduleRoot,
moduleRules: input.build?.moduleRules ?? getRules(config),
minify: input.build?.minify ?? config.minify,
keepNames: input.build?.keepNames ?? config.keep_names,
define: { ...config.define, ...input.build?.define },
custom: {
command: input.build?.custom?.command ?? config.build?.command,
watch: input.build?.custom?.watch ?? config.build?.watch_dir,
workingDirectory: input.build?.custom?.workingDirectory ?? config.build?.cwd
},
format: entry.format,
nodejsCompatMode: nodejsCompatMode ?? null,
jsxFactory: input.build?.jsxFactory || config.jsx_factory,
jsxFragment: input.build?.jsxFragment || config.jsx_fragment,
tsconfig: input.build?.tsconfig ?? config.tsconfig,
exports: entry.exports
},
containers: await getNormalizedContainerOptions(config, {}),
dev: await resolveDevConfig(config, input),
legacy: {
site: legacySite,
enableServiceEnvironments: input.legacy?.enableServiceEnvironments ?? !isLegacyEnv(config)
},
unsafe: {
capnp: input.unsafe?.capnp ?? unsafe?.capnp,
metadata: input.unsafe?.metadata ?? unsafe?.metadata
},
assets: assetsOptions,
tailConsumers: config.tail_consumers ?? []
};
if (extractBindingsOfType("analytics_engine", resolved.bindings).length && !resolved.dev.remote && resolved.build.format === "service-worker") {
logger.warn(
"Analytics Engine is not supported locally when using the service-worker format. Please migrate to the module worker format: https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/"
);
}
validateAssetsArgsAndConfig(resolved);
const services = extractBindingsOfType("service", resolved.bindings);
if (services && services.length > 0 && resolved.dev?.remote) {
logger.warn(
`This worker is bound to live services: ${services.map(
(service) => `${service.name} (${service.service}${service.environment ? `@${service.environment}` : ""}${service.entrypoint ? `#${service.entrypoint}` : ""})`
).join(", ")}`
);
}
if (!resolved.dev?.origin?.secure && resolved.dev?.remote) {
logger.warn(
"Setting upstream-protocol to http is not currently supported for remote mode.\nIf this is required in your project, please add your use case to the following issue:\nhttps://github.com/cloudflare/workers-sdk/issues/583."
);
}
const needsPulling = resolved.containers.some(
(c6) => "image_uri" in c6 && c6.image_uri
);
if (needsPulling && !resolved.dev.remote) {
await fillOpenAPIConfiguration(config, containersScope);
}
const queues = extractBindingsOfType("queue", resolved.bindings);
if (resolved.dev.remote && (queues?.length || resolved.triggers?.some((t7) => t7.type === "queue-consumer"))) {
logger.warn("Queues are not yet supported in wrangler dev remote mode.");
}
if (resolved.dev.remote) {
if (resolved.dev.enableContainers && resolved.containers && resolved.containers.length > 0) {
logger.warn(
"Containers are only supported in local mode, to suppress this warning set `dev.enable_containers` to `false` or pass `--enable-containers=false` to the `wrangler dev` command"
);
}
const classNamesWhichUseSQLite = getClassNamesWhichUseSQLite(
resolved.migrations
);
if (resolved.dev.remote && Array.from(classNamesWhichUseSQLite.values()).some((v7) => v7)) {
logger.warn("SQLite in Durable Objects is only supported in local mode.");
}
}
const typesChanged = await checkTypesDiff(config, entry);
if (typesChanged) {
logger.log(
"\u2753 Your types might be out of date. Re-run `wrangler types` to ensure your types are correct."
);
}
return { config: resolved, printCurrentBindings };
}
var import_node_assert27, import_node_path59, import_miniflare22, getInspectorPort, getLocalPort, ConfigController;
var init_ConfigController = __esm({
"src/api/startDevWorker/ConfigController.ts"() {
init_import_meta_url();
import_node_assert27 = __toESM(require("assert"));
import_node_path59 = __toESM(require("path"));
init_containers_shared();
init_esm4();
import_miniflare22 = require("miniflare");
init_assets();
init_common();
init_config2();
init_containers2();
init_config3();
init_entry();
init_dev2();
init_class_names_sqlite();
init_get_local_persistence_path();
init_misc_variables();
init_errors();
init_experimental_flags();
init_logger();
init_helpers8();
init_user2();
init_compatibility_date();
init_constants5();
init_getRules();
init_getScriptName();
init_isLegacyEnv();
init_memoizeGetPort();
init_print_bindings();
init_zones();
init_BaseController();
init_events();
init_utils2();
getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT, "127.0.0.1");
getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT, "localhost");
__name(resolveDevConfig, "resolveDevConfig");
__name(resolveBindings, "resolveBindings");
__name(resolveTriggers, "resolveTriggers");
__name(resolveConfig, "resolveConfig");
ConfigController = class extends Controller {
static {
__name(this, "ConfigController");
}
latestInput;
latestConfig;
#printCurrentBindings;
#configWatcher;
#abortController;
async #ensureWatchingConfig(configPath) {
await this.#configWatcher?.close();
if (configPath) {
this.#configWatcher = watch(configPath, {
persistent: true,
ignoreInitial: true
}).on("change", async (_event) => {
logger.debug(`${import_node_path59.default.basename(configPath)} changed...`);
(0, import_node_assert27.default)(
this.latestInput,
"Cannot be watching config without having first set an input"
);
void this.#updateConfig(this.latestInput);
});
}
}
set(input, throwErrors = false) {
return runWithLogLevel(
input.dev?.logLevel,
() => this.#updateConfig(input, throwErrors)
);
}
patch(input) {
(0, import_node_assert27.default)(
this.latestInput,
"Cannot call updateConfig without previously calling setConfig"
);
const config = {
...this.latestInput,
...input
};
return runWithLogLevel(
config.dev?.logLevel,
() => this.#updateConfig(config)
);
}
async #updateConfig(input, throwErrors = false) {
this.#abortController?.abort();
this.#abortController = new AbortController();
const signal = this.#abortController.signal;
this.latestInput = input;
try {
const fileConfig = readConfig(
{
script: input.entrypoint,
config: input.config,
env: input.env,
"dispatch-namespace": void 0,
"legacy-env": !input.legacy?.enableServiceEnvironments,
remote: !!input.dev?.remote,
upstreamProtocol: input.dev?.origin?.secure === void 0 ? void 0 : input.dev?.origin?.secure ? "https" : "http",
localProtocol: input.dev?.server?.secure === void 0 ? void 0 : input.dev?.server?.secure ? "https" : "http"
},
{ useRedirectIfAvailable: true }
);
if (typeof vitest === "undefined") {
void this.#ensureWatchingConfig(fileConfig.configPath);
}
const { config: resolvedConfig, printCurrentBindings } = await resolveConfig(fileConfig, input);
if (signal.aborted) {
return;
}
this.latestConfig = resolvedConfig;
this.#printCurrentBindings = printCurrentBindings;
this.emitConfigUpdateEvent(resolvedConfig);
return this.latestConfig;
} catch (err) {
if (throwErrors) {
throw err;
} else {
this.emitErrorEvent({
type: "error",
reason: "Error resolving config",
cause: castErrorCause(err),
source: "ConfigController",
data: void 0
});
}
}
}
// ******************
// Event Handlers
// ******************
onDevRegistryUpdate(event) {
this.#printCurrentBindings?.(event.registry);
}
async teardown() {
logger.debug("ConfigController teardown beginning...");
await this.#configWatcher?.close();
logger.debug("ConfigController teardown complete");
}
// *********************
// Event Dispatchers
// *********************
emitConfigUpdateEvent(config) {
this.emit("configUpdate", { type: "configUpdate", config });
}
};
}
});
// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/wrangler/templates/startDevWorker/InspectorProxyWorker.ts
var import_node_path60, scriptPath2, InspectorProxyWorker_default;
var init_InspectorProxyWorker = __esm({
"embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/wrangler/templates/startDevWorker/InspectorProxyWorker.ts"() {
init_import_meta_url();
import_node_path60 = __toESM(require("path"));
scriptPath2 = import_node_path60.default.resolve(__dirname, "..", "wrangler-dist/InspectorProxyWorker.js");
InspectorProxyWorker_default = scriptPath2;
}
});
// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/wrangler/templates/startDevWorker/ProxyWorker.ts
var import_node_path61, scriptPath3, ProxyWorker_default;
var init_ProxyWorker = __esm({
"embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/wrangler/templates/startDevWorker/ProxyWorker.ts"() {
init_import_meta_url();
import_node_path61 = __toESM(require("path"));
scriptPath3 = import_node_path61.default.resolve(__dirname, "..", "wrangler-dist/ProxyWorker.js");
ProxyWorker_default = scriptPath3;
}
});
// src/api/startDevWorker/bundle-allowed-paths.ts
function isAllowedSourcePath(bundle, filePath) {
const allowed = getBundleReferencedPaths(bundle);
return allowed.sourcePaths.has(filePath);
}
function isAllowedSourceMapPath(bundle, filePath) {
const allowed = getBundleReferencedPaths(bundle);
return allowed.sourceMapPaths.has(filePath);
}
function getBundleReferencedPaths(bundle) {
let allowed = bundleReferencedPathsCache.get(bundle);
if (allowed !== void 0) {
return allowed;
}
allowed = { sourcePaths: /* @__PURE__ */ new Set(), sourceMapPaths: /* @__PURE__ */ new Set() };
bundleReferencedPathsCache.set(bundle, allowed);
for (const sourcePath of getBundleSourcePaths(bundle)) {
const sourceMappingURL = maybeGetSourceMappingURL(sourcePath);
if (sourceMappingURL === void 0) {
continue;
}
const sourceMappingPath = (0, import_node_url10.fileURLToPath)(sourceMappingURL);
allowed.sourceMapPaths.add(sourceMappingPath);
const sourceMapData = import_node_fs35.default.readFileSync(sourceMappingPath, "utf8");
const sourceMap = JSON.parse(sourceMapData);
const sourceRoot = sourceMap.sourceRoot ?? "";
for (const source of sourceMap.sources) {
const sourceURL = new URL(
import_node_path62.default.posix.join(sourceRoot, source),
sourceMappingURL
);
allowed.sourcePaths.add((0, import_node_url10.fileURLToPath)(sourceURL));
}
}
return allowed;
}
function* getBundleSourcePaths(bundle) {
yield bundle.path;
for (const module3 of bundle.modules) {
if (module3.type !== "esm" && module3.type !== "commonjs") {
continue;
}
if (module3.filePath === void 0) {
continue;
}
yield module3.filePath;
}
}
function maybeGetSourceMappingURL(sourcePath) {
const source = import_node_fs35.default.readFileSync(sourcePath, "utf8");
const sourceMappingURLIndex = source.lastIndexOf("//# sourceMappingURL=");
if (sourceMappingURLIndex === -1) {
return;
}
const sourceMappingURLMatch = source.substring(sourceMappingURLIndex).match(/^\/\/# sourceMappingURL=(.+)/);
(0, import_node_assert28.default)(sourceMappingURLMatch !== null);
const sourceMappingURLSpecifier = sourceMappingURLMatch[1];
const sourceURL = (0, import_node_url10.pathToFileURL)(sourcePath);
try {
const sourceMappingURL = new URL(sourceMappingURLSpecifier, sourceURL);
if (sourceMappingURL.protocol !== "file:") {
return;
}
return sourceMappingURL;
} catch {
}
}
var import_node_assert28, import_node_fs35, import_node_path62, import_node_url10, bundleReferencedPathsCache;
var init_bundle_allowed_paths = __esm({
"src/api/startDevWorker/bundle-allowed-paths.ts"() {
init_import_meta_url();
import_node_assert28 = __toESM(require("assert"));
import_node_fs35 = __toESM(require("fs"));
import_node_path62 = __toESM(require("path"));
import_node_url10 = require("url");
__name(isAllowedSourcePath, "isAllowedSourcePath");
__name(isAllowedSourceMapPath, "isAllowedSourceMapPath");
bundleReferencedPathsCache = /* @__PURE__ */ new WeakMap();
__name(getBundleReferencedPaths, "getBundleReferencedPaths");
__name(getBundleSourcePaths, "getBundleSourcePaths");
__name(maybeGetSourceMappingURL, "maybeGetSourceMappingURL");
}
});
// src/dev/inspect.ts
function logConsoleMessage(evt) {
const args = [];
for (const ro of evt.args) {
switch (ro.type) {
case "string":
case "number":
case "boolean":
case "undefined":
case "symbol":
case "bigint":
if (typeof ro.value === "string") {
ro.value = getSourceMappedString(ro.value);
}
args.push(ro.value);
break;
case "function":
args.push(`[Function: ${ro.description ?? "<no-description>"}]`);
break;
case "object":
if (!ro.preview) {
args.push(
ro.subtype === "null" ? "null" : ro.description ?? "<no-description>"
);
} else {
args.push(ro.preview.description ?? "<no-description>");
switch (ro.preview.subtype) {
case "array":
args.push(
"[ " + ro.preview.properties.map(({ value }) => {
return value;
}).join(", ") + (ro.preview.overflow ? "..." : "") + " ]"
);
break;
case "weakmap":
case "map":
if (ro.preview.entries === void 0) {
args.push("{}");
} else {
args.push(
"{\n" + ro.preview.entries.map(({ key, value }) => {
return ` ${key?.description ?? "<unknown>"} => ${value.description}`;
}).join(",\n") + (ro.preview.overflow ? "\n ..." : "") + "\n}"
);
}
break;
case "weakset":
case "set":
if (ro.preview.entries === void 0) {
args.push("{}");
} else {
args.push(
"{ " + ro.preview.entries.map(({ value }) => {
return `${value.description}`;
}).join(", ") + (ro.preview.overflow ? ", ..." : "") + " }"
);
}
break;
case "regexp":
break;
case "date":
break;
case "generator":
args.push(ro.preview.properties[0].value || "");
break;
case "promise":
if (ro.preview.properties[0].value === "pending") {
args.push(`{<${ro.preview.properties[0].value}>}`);
} else {
args.push(
`{<${ro.preview.properties[0].value}>: ${ro.preview.properties[1].value}}`
);
}
break;
case "node":
case "iterator":
case "proxy":
case "typedarray":
case "arraybuffer":
case "dataview":
case "webassemblymemory":
case "wasmvalue":
break;
case "error":
default:
args.push(
"{\n" + ro.preview.properties.map(({ name: name2, value }) => {
return ` ${name2}: ${value}`;
}).join(",\n") + (ro.preview.overflow ? "\n ..." : "") + "\n}"
);
}
}
break;
default:
args.push(ro.description || ro.unserializableValue || "\u{1F98B}");
break;
}
}
const method = mapConsoleAPIMessageTypeToConsoleMethod[evt.type];
if (method in console) {
switch (method) {
case "dir":
logger.console(
"dir",
...args
);
break;
case "table":
logger.table(args.map((value) => ({ value })));
break;
default:
logger.console(method, ...args);
break;
}
} else {
logger.warn(`Unsupported console method: ${method}`);
logger.warn("console event:", evt);
}
}
function maybeHandleNetworkLoadResource(url4, bundle, tmpDir) {
if (typeof url4 === "string") {
url4 = new import_node_url11.URL(url4);
}
if (url4.protocol !== "file:") {
return;
}
const filePath = (0, import_node_url11.fileURLToPath)(url4);
if (isAllowedSourceMapPath(bundle, filePath)) {
const sourceMap = JSON.parse((0, import_fs28.readFileSync)(filePath, "utf-8"));
sourceMap.x_google_ignoreList = sourceMap.sources.map((source, i5) => {
if (source.includes("wrangler/templates")) {
return i5;
}
if (tmpDir !== void 0 && import_path27.default.resolve(sourceMap?.sourceRoot ?? "", source).includes(tmpDir)) {
return i5;
}
}).filter((i5) => i5 !== void 0);
return JSON.stringify(sourceMap);
}
if (isAllowedSourcePath(bundle, filePath)) {
return (0, import_fs28.readFileSync)(filePath, "utf-8");
}
}
var import_fs28, import_node_os9, import_node_url11, import_path27, import_open2, mapConsoleAPIMessageTypeToConsoleMethod, openInspector;
var init_inspect2 = __esm({
"src/dev/inspect.ts"() {
init_import_meta_url();
import_fs28 = require("fs");
import_node_os9 = __toESM(require("os"));
import_node_url11 = require("url");
import_path27 = __toESM(require("path"));
import_open2 = __toESM(require_open());
init_bundle_allowed_paths();
init_logger();
init_sourcemap();
mapConsoleAPIMessageTypeToConsoleMethod = {
log: "log",
debug: "debug",
info: "info",
warning: "warn",
error: "error",
dir: "dir",
dirxml: "dirxml",
table: "table",
trace: "trace",
clear: "clear",
count: "count",
assert: "assert",
profile: "profile",
profileEnd: "profileEnd",
timeEnd: "timeEnd",
startGroup: "group",
startGroupCollapsed: "groupCollapsed",
endGroup: "groupEnd"
};
__name(logConsoleMessage, "logConsoleMessage");
__name(maybeHandleNetworkLoadResource, "maybeHandleNetworkLoadResource");
openInspector = /* @__PURE__ */ __name(async (inspectorPort, worker) => {
const query = new URLSearchParams();
query.set("theme", "systemPreferred");
query.set("ws", `127.0.0.1:${inspectorPort}/ws`);
if (worker) {
query.set("domain", worker);
}
query.set("debugger", "true");
const url4 = `https://devtools.devprod.cloudflare.dev/js_app?${query.toString()}`;
const errorMessage = "Failed to open inspector.\nInspector depends on having a Chromium-based browser installed, maybe you need to install one?";
let braveBrowser;
switch (import_node_os9.default.platform()) {
case "darwin":
case "win32":
braveBrowser = "Brave";
break;
default:
braveBrowser = "brave";
}
const childProcess2 = await (0, import_open2.default)(url4, {
app: [
{
name: import_open2.default.apps.chrome
},
{
name: braveBrowser
},
{
name: import_open2.default.apps.edge
},
{
name: import_open2.default.apps.firefox
}
]
});
childProcess2.on("error", () => {
logger.warn(errorMessage);
});
}, "openInspector");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/forge.js
var require_forge = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/forge.js"(exports2, module3) {
init_import_meta_url();
module3.exports = {
// default options
options: {
usePureJavaScript: false
}
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/baseN.js
var require_baseN = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/baseN.js"(exports2, module3) {
init_import_meta_url();
var api = {};
module3.exports = api;
var _reverseAlphabets = {};
api.encode = function(input, alphabet, maxline) {
if (typeof alphabet !== "string") {
throw new TypeError('"alphabet" must be a string.');
}
if (maxline !== void 0 && typeof maxline !== "number") {
throw new TypeError('"maxline" must be a number.');
}
var output = "";
if (!(input instanceof Uint8Array)) {
output = _encodeWithByteBuffer(input, alphabet);
} else {
var i5 = 0;
var base = alphabet.length;
var first = alphabet.charAt(0);
var digits = [0];
for (i5 = 0; i5 < input.length; ++i5) {
for (var j6 = 0, carry = input[i5]; j6 < digits.length; ++j6) {
carry += digits[j6] << 8;
digits[j6] = carry % base;
carry = carry / base | 0;
}
while (carry > 0) {
digits.push(carry % base);
carry = carry / base | 0;
}
}
for (i5 = 0; input[i5] === 0 && i5 < input.length - 1; ++i5) {
output += first;
}
for (i5 = digits.length - 1; i5 >= 0; --i5) {
output += alphabet[digits[i5]];
}
}
if (maxline) {
var regex2 = new RegExp(".{1," + maxline + "}", "g");
output = output.match(regex2).join("\r\n");
}
return output;
};
api.decode = function(input, alphabet) {
if (typeof input !== "string") {
throw new TypeError('"input" must be a string.');
}
if (typeof alphabet !== "string") {
throw new TypeError('"alphabet" must be a string.');
}
var table = _reverseAlphabets[alphabet];
if (!table) {
table = _reverseAlphabets[alphabet] = [];
for (var i5 = 0; i5 < alphabet.length; ++i5) {
table[alphabet.charCodeAt(i5)] = i5;
}
}
input = input.replace(/\s/g, "");
var base = alphabet.length;
var first = alphabet.charAt(0);
var bytes = [0];
for (var i5 = 0; i5 < input.length; i5++) {
var value = table[input.charCodeAt(i5)];
if (value === void 0) {
return;
}
for (var j6 = 0, carry = value; j6 < bytes.length; ++j6) {
carry += bytes[j6] * base;
bytes[j6] = carry & 255;
carry >>= 8;
}
while (carry > 0) {
bytes.push(carry & 255);
carry >>= 8;
}
}
for (var k6 = 0; input[k6] === first && k6 < input.length - 1; ++k6) {
bytes.push(0);
}
if (typeof Buffer !== "undefined") {
return Buffer.from(bytes.reverse());
}
return new Uint8Array(bytes.reverse());
};
function _encodeWithByteBuffer(input, alphabet) {
var i5 = 0;
var base = alphabet.length;
var first = alphabet.charAt(0);
var digits = [0];
for (i5 = 0; i5 < input.length(); ++i5) {
for (var j6 = 0, carry = input.at(i5); j6 < digits.length; ++j6) {
carry += digits[j6] << 8;
digits[j6] = carry % base;
carry = carry / base | 0;
}
while (carry > 0) {
digits.push(carry % base);
carry = carry / base | 0;
}
}
var output = "";
for (i5 = 0; input.at(i5) === 0 && i5 < input.length() - 1; ++i5) {
output += first;
}
for (i5 = digits.length - 1; i5 >= 0; --i5) {
output += alphabet[digits[i5]];
}
return output;
}
__name(_encodeWithByteBuffer, "_encodeWithByteBuffer");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/util.js
var require_util10 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/util.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
var baseN = require_baseN();
var util3 = module3.exports = forge.util = forge.util || {};
(function() {
if (typeof process !== "undefined" && process.nextTick && !process.browser) {
util3.nextTick = process.nextTick;
if (typeof setImmediate === "function") {
util3.setImmediate = setImmediate;
} else {
util3.setImmediate = util3.nextTick;
}
return;
}
if (typeof setImmediate === "function") {
util3.setImmediate = function() {
return setImmediate.apply(void 0, arguments);
};
util3.nextTick = function(callback) {
return setImmediate(callback);
};
return;
}
util3.setImmediate = function(callback) {
setTimeout(callback, 0);
};
if (typeof window !== "undefined" && typeof window.postMessage === "function") {
let handler2 = function(event) {
if (event.source === window && event.data === msg) {
event.stopPropagation();
var copy = callbacks.slice();
callbacks.length = 0;
copy.forEach(function(callback) {
callback();
});
}
};
var handler = handler2;
__name(handler2, "handler");
var msg = "forge.setImmediate";
var callbacks = [];
util3.setImmediate = function(callback) {
callbacks.push(callback);
if (callbacks.length === 1) {
window.postMessage(msg, "*");
}
};
window.addEventListener("message", handler2, true);
}
if (typeof MutationObserver !== "undefined") {
var now = Date.now();
var attr = true;
var div = document.createElement("div");
var callbacks = [];
new MutationObserver(function() {
var copy = callbacks.slice();
callbacks.length = 0;
copy.forEach(function(callback) {
callback();
});
}).observe(div, { attributes: true });
var oldSetImmediate = util3.setImmediate;
util3.setImmediate = function(callback) {
if (Date.now() - now > 15) {
now = Date.now();
oldSetImmediate(callback);
} else {
callbacks.push(callback);
if (callbacks.length === 1) {
div.setAttribute("a", attr = !attr);
}
}
};
}
util3.nextTick = util3.setImmediate;
})();
util3.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node;
util3.globalScope = function() {
if (util3.isNodejs) {
return global;
}
return typeof self === "undefined" ? window : self;
}();
util3.isArray = Array.isArray || function(x6) {
return Object.prototype.toString.call(x6) === "[object Array]";
};
util3.isArrayBuffer = function(x6) {
return typeof ArrayBuffer !== "undefined" && x6 instanceof ArrayBuffer;
};
util3.isArrayBufferView = function(x6) {
return x6 && util3.isArrayBuffer(x6.buffer) && x6.byteLength !== void 0;
};
function _checkBitsParam(n6) {
if (!(n6 === 8 || n6 === 16 || n6 === 24 || n6 === 32)) {
throw new Error("Only 8, 16, 24, or 32 bits supported: " + n6);
}
}
__name(_checkBitsParam, "_checkBitsParam");
util3.ByteBuffer = ByteStringBuffer;
function ByteStringBuffer(b6) {
this.data = "";
this.read = 0;
if (typeof b6 === "string") {
this.data = b6;
} else if (util3.isArrayBuffer(b6) || util3.isArrayBufferView(b6)) {
if (typeof Buffer !== "undefined" && b6 instanceof Buffer) {
this.data = b6.toString("binary");
} else {
var arr = new Uint8Array(b6);
try {
this.data = String.fromCharCode.apply(null, arr);
} catch (e7) {
for (var i5 = 0; i5 < arr.length; ++i5) {
this.putByte(arr[i5]);
}
}
}
} else if (b6 instanceof ByteStringBuffer || typeof b6 === "object" && typeof b6.data === "string" && typeof b6.read === "number") {
this.data = b6.data;
this.read = b6.read;
}
this._constructedStringLength = 0;
}
__name(ByteStringBuffer, "ByteStringBuffer");
util3.ByteStringBuffer = ByteStringBuffer;
var _MAX_CONSTRUCTED_STRING_LENGTH = 4096;
util3.ByteStringBuffer.prototype._optimizeConstructedString = function(x6) {
this._constructedStringLength += x6;
if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {
this.data.substr(0, 1);
this._constructedStringLength = 0;
}
};
util3.ByteStringBuffer.prototype.length = function() {
return this.data.length - this.read;
};
util3.ByteStringBuffer.prototype.isEmpty = function() {
return this.length() <= 0;
};
util3.ByteStringBuffer.prototype.putByte = function(b6) {
return this.putBytes(String.fromCharCode(b6));
};
util3.ByteStringBuffer.prototype.fillWithByte = function(b6, n6) {
b6 = String.fromCharCode(b6);
var d6 = this.data;
while (n6 > 0) {
if (n6 & 1) {
d6 += b6;
}
n6 >>>= 1;
if (n6 > 0) {
b6 += b6;
}
}
this.data = d6;
this._optimizeConstructedString(n6);
return this;
};
util3.ByteStringBuffer.prototype.putBytes = function(bytes) {
this.data += bytes;
this._optimizeConstructedString(bytes.length);
return this;
};
util3.ByteStringBuffer.prototype.putString = function(str) {
return this.putBytes(util3.encodeUtf8(str));
};
util3.ByteStringBuffer.prototype.putInt16 = function(i5) {
return this.putBytes(
String.fromCharCode(i5 >> 8 & 255) + String.fromCharCode(i5 & 255)
);
};
util3.ByteStringBuffer.prototype.putInt24 = function(i5) {
return this.putBytes(
String.fromCharCode(i5 >> 16 & 255) + String.fromCharCode(i5 >> 8 & 255) + String.fromCharCode(i5 & 255)
);
};
util3.ByteStringBuffer.prototype.putInt32 = function(i5) {
return this.putBytes(
String.fromCharCode(i5 >> 24 & 255) + String.fromCharCode(i5 >> 16 & 255) + String.fromCharCode(i5 >> 8 & 255) + String.fromCharCode(i5 & 255)
);
};
util3.ByteStringBuffer.prototype.putInt16Le = function(i5) {
return this.putBytes(
String.fromCharCode(i5 & 255) + String.fromCharCode(i5 >> 8 & 255)
);
};
util3.ByteStringBuffer.prototype.putInt24Le = function(i5) {
return this.putBytes(
String.fromCharCode(i5 & 255) + String.fromCharCode(i5 >> 8 & 255) + String.fromCharCode(i5 >> 16 & 255)
);
};
util3.ByteStringBuffer.prototype.putInt32Le = function(i5) {
return this.putBytes(
String.fromCharCode(i5 & 255) + String.fromCharCode(i5 >> 8 & 255) + String.fromCharCode(i5 >> 16 & 255) + String.fromCharCode(i5 >> 24 & 255)
);
};
util3.ByteStringBuffer.prototype.putInt = function(i5, n6) {
_checkBitsParam(n6);
var bytes = "";
do {
n6 -= 8;
bytes += String.fromCharCode(i5 >> n6 & 255);
} while (n6 > 0);
return this.putBytes(bytes);
};
util3.ByteStringBuffer.prototype.putSignedInt = function(i5, n6) {
if (i5 < 0) {
i5 += 2 << n6 - 1;
}
return this.putInt(i5, n6);
};
util3.ByteStringBuffer.prototype.putBuffer = function(buffer) {
return this.putBytes(buffer.getBytes());
};
util3.ByteStringBuffer.prototype.getByte = function() {
return this.data.charCodeAt(this.read++);
};
util3.ByteStringBuffer.prototype.getInt16 = function() {
var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1);
this.read += 2;
return rval;
};
util3.ByteStringBuffer.prototype.getInt24 = function() {
var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2);
this.read += 3;
return rval;
};
util3.ByteStringBuffer.prototype.getInt32 = function() {
var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3);
this.read += 4;
return rval;
};
util3.ByteStringBuffer.prototype.getInt16Le = function() {
var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8;
this.read += 2;
return rval;
};
util3.ByteStringBuffer.prototype.getInt24Le = function() {
var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16;
this.read += 3;
return rval;
};
util3.ByteStringBuffer.prototype.getInt32Le = function() {
var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24;
this.read += 4;
return rval;
};
util3.ByteStringBuffer.prototype.getInt = function(n6) {
_checkBitsParam(n6);
var rval = 0;
do {
rval = (rval << 8) + this.data.charCodeAt(this.read++);
n6 -= 8;
} while (n6 > 0);
return rval;
};
util3.ByteStringBuffer.prototype.getSignedInt = function(n6) {
var x6 = this.getInt(n6);
var max = 2 << n6 - 2;
if (x6 >= max) {
x6 -= max << 1;
}
return x6;
};
util3.ByteStringBuffer.prototype.getBytes = function(count) {
var rval;
if (count) {
count = Math.min(this.length(), count);
rval = this.data.slice(this.read, this.read + count);
this.read += count;
} else if (count === 0) {
rval = "";
} else {
rval = this.read === 0 ? this.data : this.data.slice(this.read);
this.clear();
}
return rval;
};
util3.ByteStringBuffer.prototype.bytes = function(count) {
return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count);
};
util3.ByteStringBuffer.prototype.at = function(i5) {
return this.data.charCodeAt(this.read + i5);
};
util3.ByteStringBuffer.prototype.setAt = function(i5, b6) {
this.data = this.data.substr(0, this.read + i5) + String.fromCharCode(b6) + this.data.substr(this.read + i5 + 1);
return this;
};
util3.ByteStringBuffer.prototype.last = function() {
return this.data.charCodeAt(this.data.length - 1);
};
util3.ByteStringBuffer.prototype.copy = function() {
var c6 = util3.createBuffer(this.data);
c6.read = this.read;
return c6;
};
util3.ByteStringBuffer.prototype.compact = function() {
if (this.read > 0) {
this.data = this.data.slice(this.read);
this.read = 0;
}
return this;
};
util3.ByteStringBuffer.prototype.clear = function() {
this.data = "";
this.read = 0;
return this;
};
util3.ByteStringBuffer.prototype.truncate = function(count) {
var len = Math.max(0, this.length() - count);
this.data = this.data.substr(this.read, len);
this.read = 0;
return this;
};
util3.ByteStringBuffer.prototype.toHex = function() {
var rval = "";
for (var i5 = this.read; i5 < this.data.length; ++i5) {
var b6 = this.data.charCodeAt(i5);
if (b6 < 16) {
rval += "0";
}
rval += b6.toString(16);
}
return rval;
};
util3.ByteStringBuffer.prototype.toString = function() {
return util3.decodeUtf8(this.bytes());
};
function DataBuffer(b6, options) {
options = options || {};
this.read = options.readOffset || 0;
this.growSize = options.growSize || 1024;
var isArrayBuffer3 = util3.isArrayBuffer(b6);
var isArrayBufferView = util3.isArrayBufferView(b6);
if (isArrayBuffer3 || isArrayBufferView) {
if (isArrayBuffer3) {
this.data = new DataView(b6);
} else {
this.data = new DataView(b6.buffer, b6.byteOffset, b6.byteLength);
}
this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength;
return;
}
this.data = new DataView(new ArrayBuffer(0));
this.write = 0;
if (b6 !== null && b6 !== void 0) {
this.putBytes(b6);
}
if ("writeOffset" in options) {
this.write = options.writeOffset;
}
}
__name(DataBuffer, "DataBuffer");
util3.DataBuffer = DataBuffer;
util3.DataBuffer.prototype.length = function() {
return this.write - this.read;
};
util3.DataBuffer.prototype.isEmpty = function() {
return this.length() <= 0;
};
util3.DataBuffer.prototype.accommodate = function(amount, growSize) {
if (this.length() >= amount) {
return this;
}
growSize = Math.max(growSize || this.growSize, amount);
var src = new Uint8Array(
this.data.buffer,
this.data.byteOffset,
this.data.byteLength
);
var dst = new Uint8Array(this.length() + growSize);
dst.set(src);
this.data = new DataView(dst.buffer);
return this;
};
util3.DataBuffer.prototype.putByte = function(b6) {
this.accommodate(1);
this.data.setUint8(this.write++, b6);
return this;
};
util3.DataBuffer.prototype.fillWithByte = function(b6, n6) {
this.accommodate(n6);
for (var i5 = 0; i5 < n6; ++i5) {
this.data.setUint8(b6);
}
return this;
};
util3.DataBuffer.prototype.putBytes = function(bytes, encoding) {
if (util3.isArrayBufferView(bytes)) {
var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var len = src.byteLength - src.byteOffset;
this.accommodate(len);
var dst = new Uint8Array(this.data.buffer, this.write);
dst.set(src);
this.write += len;
return this;
}
if (util3.isArrayBuffer(bytes)) {
var src = new Uint8Array(bytes);
this.accommodate(src.byteLength);
var dst = new Uint8Array(this.data.buffer);
dst.set(src, this.write);
this.write += src.byteLength;
return this;
}
if (bytes instanceof util3.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util3.isArrayBufferView(bytes.data)) {
var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());
this.accommodate(src.byteLength);
var dst = new Uint8Array(bytes.data.byteLength, this.write);
dst.set(src);
this.write += src.byteLength;
return this;
}
if (bytes instanceof util3.ByteStringBuffer) {
bytes = bytes.data;
encoding = "binary";
}
encoding = encoding || "binary";
if (typeof bytes === "string") {
var view;
if (encoding === "hex") {
this.accommodate(Math.ceil(bytes.length / 2));
view = new Uint8Array(this.data.buffer, this.write);
this.write += util3.binary.hex.decode(bytes, view, this.write);
return this;
}
if (encoding === "base64") {
this.accommodate(Math.ceil(bytes.length / 4) * 3);
view = new Uint8Array(this.data.buffer, this.write);
this.write += util3.binary.base64.decode(bytes, view, this.write);
return this;
}
if (encoding === "utf8") {
bytes = util3.encodeUtf8(bytes);
encoding = "binary";
}
if (encoding === "binary" || encoding === "raw") {
this.accommodate(bytes.length);
view = new Uint8Array(this.data.buffer, this.write);
this.write += util3.binary.raw.decode(view);
return this;
}
if (encoding === "utf16") {
this.accommodate(bytes.length * 2);
view = new Uint16Array(this.data.buffer, this.write);
this.write += util3.text.utf16.encode(view);
return this;
}
throw new Error("Invalid encoding: " + encoding);
}
throw Error("Invalid parameter: " + bytes);
};
util3.DataBuffer.prototype.putBuffer = function(buffer) {
this.putBytes(buffer);
buffer.clear();
return this;
};
util3.DataBuffer.prototype.putString = function(str) {
return this.putBytes(str, "utf16");
};
util3.DataBuffer.prototype.putInt16 = function(i5) {
this.accommodate(2);
this.data.setInt16(this.write, i5);
this.write += 2;
return this;
};
util3.DataBuffer.prototype.putInt24 = function(i5) {
this.accommodate(3);
this.data.setInt16(this.write, i5 >> 8 & 65535);
this.data.setInt8(this.write, i5 >> 16 & 255);
this.write += 3;
return this;
};
util3.DataBuffer.prototype.putInt32 = function(i5) {
this.accommodate(4);
this.data.setInt32(this.write, i5);
this.write += 4;
return this;
};
util3.DataBuffer.prototype.putInt16Le = function(i5) {
this.accommodate(2);
this.data.setInt16(this.write, i5, true);
this.write += 2;
return this;
};
util3.DataBuffer.prototype.putInt24Le = function(i5) {
this.accommodate(3);
this.data.setInt8(this.write, i5 >> 16 & 255);
this.data.setInt16(this.write, i5 >> 8 & 65535, true);
this.write += 3;
return this;
};
util3.DataBuffer.prototype.putInt32Le = function(i5) {
this.accommodate(4);
this.data.setInt32(this.write, i5, true);
this.write += 4;
return this;
};
util3.DataBuffer.prototype.putInt = function(i5, n6) {
_checkBitsParam(n6);
this.accommodate(n6 / 8);
do {
n6 -= 8;
this.data.setInt8(this.write++, i5 >> n6 & 255);
} while (n6 > 0);
return this;
};
util3.DataBuffer.prototype.putSignedInt = function(i5, n6) {
_checkBitsParam(n6);
this.accommodate(n6 / 8);
if (i5 < 0) {
i5 += 2 << n6 - 1;
}
return this.putInt(i5, n6);
};
util3.DataBuffer.prototype.getByte = function() {
return this.data.getInt8(this.read++);
};
util3.DataBuffer.prototype.getInt16 = function() {
var rval = this.data.getInt16(this.read);
this.read += 2;
return rval;
};
util3.DataBuffer.prototype.getInt24 = function() {
var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2);
this.read += 3;
return rval;
};
util3.DataBuffer.prototype.getInt32 = function() {
var rval = this.data.getInt32(this.read);
this.read += 4;
return rval;
};
util3.DataBuffer.prototype.getInt16Le = function() {
var rval = this.data.getInt16(this.read, true);
this.read += 2;
return rval;
};
util3.DataBuffer.prototype.getInt24Le = function() {
var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8;
this.read += 3;
return rval;
};
util3.DataBuffer.prototype.getInt32Le = function() {
var rval = this.data.getInt32(this.read, true);
this.read += 4;
return rval;
};
util3.DataBuffer.prototype.getInt = function(n6) {
_checkBitsParam(n6);
var rval = 0;
do {
rval = (rval << 8) + this.data.getInt8(this.read++);
n6 -= 8;
} while (n6 > 0);
return rval;
};
util3.DataBuffer.prototype.getSignedInt = function(n6) {
var x6 = this.getInt(n6);
var max = 2 << n6 - 2;
if (x6 >= max) {
x6 -= max << 1;
}
return x6;
};
util3.DataBuffer.prototype.getBytes = function(count) {
var rval;
if (count) {
count = Math.min(this.length(), count);
rval = this.data.slice(this.read, this.read + count);
this.read += count;
} else if (count === 0) {
rval = "";
} else {
rval = this.read === 0 ? this.data : this.data.slice(this.read);
this.clear();
}
return rval;
};
util3.DataBuffer.prototype.bytes = function(count) {
return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count);
};
util3.DataBuffer.prototype.at = function(i5) {
return this.data.getUint8(this.read + i5);
};
util3.DataBuffer.prototype.setAt = function(i5, b6) {
this.data.setUint8(i5, b6);
return this;
};
util3.DataBuffer.prototype.last = function() {
return this.data.getUint8(this.write - 1);
};
util3.DataBuffer.prototype.copy = function() {
return new util3.DataBuffer(this);
};
util3.DataBuffer.prototype.compact = function() {
if (this.read > 0) {
var src = new Uint8Array(this.data.buffer, this.read);
var dst = new Uint8Array(src.byteLength);
dst.set(src);
this.data = new DataView(dst);
this.write -= this.read;
this.read = 0;
}
return this;
};
util3.DataBuffer.prototype.clear = function() {
this.data = new DataView(new ArrayBuffer(0));
this.read = this.write = 0;
return this;
};
util3.DataBuffer.prototype.truncate = function(count) {
this.write = Math.max(0, this.length() - count);
this.read = Math.min(this.read, this.write);
return this;
};
util3.DataBuffer.prototype.toHex = function() {
var rval = "";
for (var i5 = this.read; i5 < this.data.byteLength; ++i5) {
var b6 = this.data.getUint8(i5);
if (b6 < 16) {
rval += "0";
}
rval += b6.toString(16);
}
return rval;
};
util3.DataBuffer.prototype.toString = function(encoding) {
var view = new Uint8Array(this.data, this.read, this.length());
encoding = encoding || "utf8";
if (encoding === "binary" || encoding === "raw") {
return util3.binary.raw.encode(view);
}
if (encoding === "hex") {
return util3.binary.hex.encode(view);
}
if (encoding === "base64") {
return util3.binary.base64.encode(view);
}
if (encoding === "utf8") {
return util3.text.utf8.decode(view);
}
if (encoding === "utf16") {
return util3.text.utf16.decode(view);
}
throw new Error("Invalid encoding: " + encoding);
};
util3.createBuffer = function(input, encoding) {
encoding = encoding || "raw";
if (input !== void 0 && encoding === "utf8") {
input = util3.encodeUtf8(input);
}
return new util3.ByteBuffer(input);
};
util3.fillString = function(c6, n6) {
var s5 = "";
while (n6 > 0) {
if (n6 & 1) {
s5 += c6;
}
n6 >>>= 1;
if (n6 > 0) {
c6 += c6;
}
}
return s5;
};
util3.xorBytes = function(s1, s22, n6) {
var s32 = "";
var b6 = "";
var t7 = "";
var i5 = 0;
var c6 = 0;
for (; n6 > 0; --n6, ++i5) {
b6 = s1.charCodeAt(i5) ^ s22.charCodeAt(i5);
if (c6 >= 10) {
s32 += t7;
t7 = "";
c6 = 0;
}
t7 += String.fromCharCode(b6);
++c6;
}
s32 += t7;
return s32;
};
util3.hexToBytes = function(hex) {
var rval = "";
var i5 = 0;
if (hex.length & true) {
i5 = 1;
rval += String.fromCharCode(parseInt(hex[0], 16));
}
for (; i5 < hex.length; i5 += 2) {
rval += String.fromCharCode(parseInt(hex.substr(i5, 2), 16));
}
return rval;
};
util3.bytesToHex = function(bytes) {
return util3.createBuffer(bytes).toHex();
};
util3.int32ToBytes = function(i5) {
return String.fromCharCode(i5 >> 24 & 255) + String.fromCharCode(i5 >> 16 & 255) + String.fromCharCode(i5 >> 8 & 255) + String.fromCharCode(i5 & 255);
};
var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var _base64Idx = [
/*43 -43 = 0*/
/*'+', 1, 2, 3,'/' */
62,
-1,
-1,
-1,
63,
/*'0','1','2','3','4','5','6','7','8','9' */
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
/*15, 16, 17,'=', 19, 20, 21 */
-1,
-1,
-1,
64,
-1,
-1,
-1,
/*65 - 43 = 22*/
/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
/*91 - 43 = 48 */
/*48, 49, 50, 51, 52, 53 */
-1,
-1,
-1,
-1,
-1,
-1,
/*97 - 43 = 54*/
/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51
];
var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
util3.encode64 = function(input, maxline) {
var line = "";
var output = "";
var chr1, chr2, chr3;
var i5 = 0;
while (i5 < input.length) {
chr1 = input.charCodeAt(i5++);
chr2 = input.charCodeAt(i5++);
chr3 = input.charCodeAt(i5++);
line += _base64.charAt(chr1 >> 2);
line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4);
if (isNaN(chr2)) {
line += "==";
} else {
line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6);
line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63);
}
if (maxline && line.length > maxline) {
output += line.substr(0, maxline) + "\r\n";
line = line.substr(maxline);
}
}
output += line;
return output;
};
util3.decode64 = function(input) {
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
var output = "";
var enc1, enc2, enc3, enc4;
var i5 = 0;
while (i5 < input.length) {
enc1 = _base64Idx[input.charCodeAt(i5++) - 43];
enc2 = _base64Idx[input.charCodeAt(i5++) - 43];
enc3 = _base64Idx[input.charCodeAt(i5++) - 43];
enc4 = _base64Idx[input.charCodeAt(i5++) - 43];
output += String.fromCharCode(enc1 << 2 | enc2 >> 4);
if (enc3 !== 64) {
output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2);
if (enc4 !== 64) {
output += String.fromCharCode((enc3 & 3) << 6 | enc4);
}
}
}
return output;
};
util3.encodeUtf8 = function(str) {
return unescape(encodeURIComponent(str));
};
util3.decodeUtf8 = function(str) {
return decodeURIComponent(escape(str));
};
util3.binary = {
raw: {},
hex: {},
base64: {},
base58: {},
baseN: {
encode: baseN.encode,
decode: baseN.decode
}
};
util3.binary.raw.encode = function(bytes) {
return String.fromCharCode.apply(null, bytes);
};
util3.binary.raw.decode = function(str, output, offset) {
var out = output;
if (!out) {
out = new Uint8Array(str.length);
}
offset = offset || 0;
var j6 = offset;
for (var i5 = 0; i5 < str.length; ++i5) {
out[j6++] = str.charCodeAt(i5);
}
return output ? j6 - offset : out;
};
util3.binary.hex.encode = util3.bytesToHex;
util3.binary.hex.decode = function(hex, output, offset) {
var out = output;
if (!out) {
out = new Uint8Array(Math.ceil(hex.length / 2));
}
offset = offset || 0;
var i5 = 0, j6 = offset;
if (hex.length & 1) {
i5 = 1;
out[j6++] = parseInt(hex[0], 16);
}
for (; i5 < hex.length; i5 += 2) {
out[j6++] = parseInt(hex.substr(i5, 2), 16);
}
return output ? j6 - offset : out;
};
util3.binary.base64.encode = function(input, maxline) {
var line = "";
var output = "";
var chr1, chr2, chr3;
var i5 = 0;
while (i5 < input.byteLength) {
chr1 = input[i5++];
chr2 = input[i5++];
chr3 = input[i5++];
line += _base64.charAt(chr1 >> 2);
line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4);
if (isNaN(chr2)) {
line += "==";
} else {
line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6);
line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63);
}
if (maxline && line.length > maxline) {
output += line.substr(0, maxline) + "\r\n";
line = line.substr(maxline);
}
}
output += line;
return output;
};
util3.binary.base64.decode = function(input, output, offset) {
var out = output;
if (!out) {
out = new Uint8Array(Math.ceil(input.length / 4) * 3);
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
offset = offset || 0;
var enc1, enc2, enc3, enc4;
var i5 = 0, j6 = offset;
while (i5 < input.length) {
enc1 = _base64Idx[input.charCodeAt(i5++) - 43];
enc2 = _base64Idx[input.charCodeAt(i5++) - 43];
enc3 = _base64Idx[input.charCodeAt(i5++) - 43];
enc4 = _base64Idx[input.charCodeAt(i5++) - 43];
out[j6++] = enc1 << 2 | enc2 >> 4;
if (enc3 !== 64) {
out[j6++] = (enc2 & 15) << 4 | enc3 >> 2;
if (enc4 !== 64) {
out[j6++] = (enc3 & 3) << 6 | enc4;
}
}
}
return output ? j6 - offset : out.subarray(0, j6);
};
util3.binary.base58.encode = function(input, maxline) {
return util3.binary.baseN.encode(input, _base58, maxline);
};
util3.binary.base58.decode = function(input, maxline) {
return util3.binary.baseN.decode(input, _base58, maxline);
};
util3.text = {
utf8: {},
utf16: {}
};
util3.text.utf8.encode = function(str, output, offset) {
str = util3.encodeUtf8(str);
var out = output;
if (!out) {
out = new Uint8Array(str.length);
}
offset = offset || 0;
var j6 = offset;
for (var i5 = 0; i5 < str.length; ++i5) {
out[j6++] = str.charCodeAt(i5);
}
return output ? j6 - offset : out;
};
util3.text.utf8.decode = function(bytes) {
return util3.decodeUtf8(String.fromCharCode.apply(null, bytes));
};
util3.text.utf16.encode = function(str, output, offset) {
var out = output;
if (!out) {
out = new Uint8Array(str.length * 2);
}
var view = new Uint16Array(out.buffer);
offset = offset || 0;
var j6 = offset;
var k6 = offset;
for (var i5 = 0; i5 < str.length; ++i5) {
view[k6++] = str.charCodeAt(i5);
j6 += 2;
}
return output ? j6 - offset : out;
};
util3.text.utf16.decode = function(bytes) {
return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));
};
util3.deflate = function(api, bytes, raw) {
bytes = util3.decode64(api.deflate(util3.encode64(bytes)).rval);
if (raw) {
var start = 2;
var flg = bytes.charCodeAt(1);
if (flg & 32) {
start = 6;
}
bytes = bytes.substring(start, bytes.length - 4);
}
return bytes;
};
util3.inflate = function(api, bytes, raw) {
var rval = api.inflate(util3.encode64(bytes)).rval;
return rval === null ? null : util3.decode64(rval);
};
var _setStorageObject = /* @__PURE__ */ __name(function(api, id, obj) {
if (!api) {
throw new Error("WebStorage not available.");
}
var rval;
if (obj === null) {
rval = api.removeItem(id);
} else {
obj = util3.encode64(JSON.stringify(obj));
rval = api.setItem(id, obj);
}
if (typeof rval !== "undefined" && rval.rval !== true) {
var error2 = new Error(rval.error.message);
error2.id = rval.error.id;
error2.name = rval.error.name;
throw error2;
}
}, "_setStorageObject");
var _getStorageObject = /* @__PURE__ */ __name(function(api, id) {
if (!api) {
throw new Error("WebStorage not available.");
}
var rval = api.getItem(id);
if (api.init) {
if (rval.rval === null) {
if (rval.error) {
var error2 = new Error(rval.error.message);
error2.id = rval.error.id;
error2.name = rval.error.name;
throw error2;
}
rval = null;
} else {
rval = rval.rval;
}
}
if (rval !== null) {
rval = JSON.parse(util3.decode64(rval));
}
return rval;
}, "_getStorageObject");
var _setItem = /* @__PURE__ */ __name(function(api, id, key, data) {
var obj = _getStorageObject(api, id);
if (obj === null) {
obj = {};
}
obj[key] = data;
_setStorageObject(api, id, obj);
}, "_setItem");
var _getItem = /* @__PURE__ */ __name(function(api, id, key) {
var rval = _getStorageObject(api, id);
if (rval !== null) {
rval = key in rval ? rval[key] : null;
}
return rval;
}, "_getItem");
var _removeItem = /* @__PURE__ */ __name(function(api, id, key) {
var obj = _getStorageObject(api, id);
if (obj !== null && key in obj) {
delete obj[key];
var empty2 = true;
for (var prop in obj) {
empty2 = false;
break;
}
if (empty2) {
obj = null;
}
_setStorageObject(api, id, obj);
}
}, "_removeItem");
var _clearItems = /* @__PURE__ */ __name(function(api, id) {
_setStorageObject(api, id, null);
}, "_clearItems");
var _callStorageFunction = /* @__PURE__ */ __name(function(func, args, location) {
var rval = null;
if (typeof location === "undefined") {
location = ["web", "flash"];
}
var type;
var done = false;
var exception = null;
for (var idx in location) {
type = location[idx];
try {
if (type === "flash" || type === "both") {
if (args[0] === null) {
throw new Error("Flash local storage not available.");
}
rval = func.apply(this, args);
done = type === "flash";
}
if (type === "web" || type === "both") {
args[0] = localStorage;
rval = func.apply(this, args);
done = true;
}
} catch (ex) {
exception = ex;
}
if (done) {
break;
}
}
if (!done) {
throw exception;
}
return rval;
}, "_callStorageFunction");
util3.setItem = function(api, id, key, data, location) {
_callStorageFunction(_setItem, arguments, location);
};
util3.getItem = function(api, id, key, location) {
return _callStorageFunction(_getItem, arguments, location);
};
util3.removeItem = function(api, id, key, location) {
_callStorageFunction(_removeItem, arguments, location);
};
util3.clearItems = function(api, id, location) {
_callStorageFunction(_clearItems, arguments, location);
};
util3.isEmpty = function(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
util3.format = function(format9) {
var re = /%./g;
var match2;
var part;
var argi = 0;
var parts = [];
var last = 0;
while (match2 = re.exec(format9)) {
part = format9.substring(last, re.lastIndex - 2);
if (part.length > 0) {
parts.push(part);
}
last = re.lastIndex;
var code = match2[0][1];
switch (code) {
case "s":
case "o":
if (argi < arguments.length) {
parts.push(arguments[argi++ + 1]);
} else {
parts.push("<?>");
}
break;
// FIXME: do proper formating for numbers, etc
//case 'f':
//case 'd':
case "%":
parts.push("%");
break;
default:
parts.push("<%" + code + "?>");
}
}
parts.push(format9.substring(last));
return parts.join("");
};
util3.formatNumber = function(number, decimals, dec_point, thousands_sep) {
var n6 = number, c6 = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
var d6 = dec_point === void 0 ? "," : dec_point;
var t7 = thousands_sep === void 0 ? "." : thousands_sep, s5 = n6 < 0 ? "-" : "";
var i5 = parseInt(n6 = Math.abs(+n6 || 0).toFixed(c6), 10) + "";
var j6 = i5.length > 3 ? i5.length % 3 : 0;
return s5 + (j6 ? i5.substr(0, j6) + t7 : "") + i5.substr(j6).replace(/(\d{3})(?=\d)/g, "$1" + t7) + (c6 ? d6 + Math.abs(n6 - i5).toFixed(c6).slice(2) : "");
};
util3.formatSize = function(size) {
if (size >= 1073741824) {
size = util3.formatNumber(size / 1073741824, 2, ".", "") + " GiB";
} else if (size >= 1048576) {
size = util3.formatNumber(size / 1048576, 2, ".", "") + " MiB";
} else if (size >= 1024) {
size = util3.formatNumber(size / 1024, 0) + " KiB";
} else {
size = util3.formatNumber(size, 0) + " bytes";
}
return size;
};
util3.bytesFromIP = function(ip) {
if (ip.indexOf(".") !== -1) {
return util3.bytesFromIPv4(ip);
}
if (ip.indexOf(":") !== -1) {
return util3.bytesFromIPv6(ip);
}
return null;
};
util3.bytesFromIPv4 = function(ip) {
ip = ip.split(".");
if (ip.length !== 4) {
return null;
}
var b6 = util3.createBuffer();
for (var i5 = 0; i5 < ip.length; ++i5) {
var num = parseInt(ip[i5], 10);
if (isNaN(num)) {
return null;
}
b6.putByte(num);
}
return b6.getBytes();
};
util3.bytesFromIPv6 = function(ip) {
var blanks = 0;
ip = ip.split(":").filter(function(e7) {
if (e7.length === 0) ++blanks;
return true;
});
var zeros = (8 - ip.length + blanks) * 2;
var b6 = util3.createBuffer();
for (var i5 = 0; i5 < 8; ++i5) {
if (!ip[i5] || ip[i5].length === 0) {
b6.fillWithByte(0, zeros);
zeros = 0;
continue;
}
var bytes = util3.hexToBytes(ip[i5]);
if (bytes.length < 2) {
b6.putByte(0);
}
b6.putBytes(bytes);
}
return b6.getBytes();
};
util3.bytesToIP = function(bytes) {
if (bytes.length === 4) {
return util3.bytesToIPv4(bytes);
}
if (bytes.length === 16) {
return util3.bytesToIPv6(bytes);
}
return null;
};
util3.bytesToIPv4 = function(bytes) {
if (bytes.length !== 4) {
return null;
}
var ip = [];
for (var i5 = 0; i5 < bytes.length; ++i5) {
ip.push(bytes.charCodeAt(i5));
}
return ip.join(".");
};
util3.bytesToIPv6 = function(bytes) {
if (bytes.length !== 16) {
return null;
}
var ip = [];
var zeroGroups = [];
var zeroMaxGroup = 0;
for (var i5 = 0; i5 < bytes.length; i5 += 2) {
var hex = util3.bytesToHex(bytes[i5] + bytes[i5 + 1]);
while (hex[0] === "0" && hex !== "0") {
hex = hex.substr(1);
}
if (hex === "0") {
var last = zeroGroups[zeroGroups.length - 1];
var idx = ip.length;
if (!last || idx !== last.end + 1) {
zeroGroups.push({ start: idx, end: idx });
} else {
last.end = idx;
if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) {
zeroMaxGroup = zeroGroups.length - 1;
}
}
}
ip.push(hex);
}
if (zeroGroups.length > 0) {
var group = zeroGroups[zeroMaxGroup];
if (group.end - group.start > 0) {
ip.splice(group.start, group.end - group.start + 1, "");
if (group.start === 0) {
ip.unshift("");
}
if (group.end === 7) {
ip.push("");
}
}
}
return ip.join(":");
};
util3.estimateCores = function(options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
}
options = options || {};
if ("cores" in util3 && !options.update) {
return callback(null, util3.cores);
}
if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) {
util3.cores = navigator.hardwareConcurrency;
return callback(null, util3.cores);
}
if (typeof Worker === "undefined") {
util3.cores = 1;
return callback(null, util3.cores);
}
if (typeof Blob === "undefined") {
util3.cores = 2;
return callback(null, util3.cores);
}
var blobUrl = URL.createObjectURL(new Blob([
"(",
function() {
self.addEventListener("message", function(e7) {
var st = Date.now();
var et = st + 4;
while (Date.now() < et) ;
self.postMessage({ st, et });
});
}.toString(),
")()"
], { type: "application/javascript" }));
sample([], 5, 16);
function sample(max, samples, numWorkers) {
if (samples === 0) {
var avg = Math.floor(max.reduce(function(avg2, x6) {
return avg2 + x6;
}, 0) / max.length);
util3.cores = Math.max(1, avg);
URL.revokeObjectURL(blobUrl);
return callback(null, util3.cores);
}
map2(numWorkers, function(err, results) {
max.push(reduce(numWorkers, results));
sample(max, samples - 1, numWorkers);
});
}
__name(sample, "sample");
function map2(numWorkers, callback2) {
var workers = [];
var results = [];
for (var i5 = 0; i5 < numWorkers; ++i5) {
var worker = new Worker(blobUrl);
worker.addEventListener("message", function(e7) {
results.push(e7.data);
if (results.length === numWorkers) {
for (var i6 = 0; i6 < numWorkers; ++i6) {
workers[i6].terminate();
}
callback2(null, results);
}
});
workers.push(worker);
}
for (var i5 = 0; i5 < numWorkers; ++i5) {
workers[i5].postMessage(i5);
}
}
__name(map2, "map");
function reduce(numWorkers, results) {
var overlaps = [];
for (var n6 = 0; n6 < numWorkers; ++n6) {
var r1 = results[n6];
var overlap = overlaps[n6] = [];
for (var i5 = 0; i5 < numWorkers; ++i5) {
if (n6 === i5) {
continue;
}
var r22 = results[i5];
if (r1.st > r22.st && r1.st < r22.et || r22.st > r1.st && r22.st < r1.et) {
overlap.push(i5);
}
}
}
return overlaps.reduce(function(max, overlap2) {
return Math.max(max, overlap2.length);
}, 0);
}
__name(reduce, "reduce");
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/cipher.js
var require_cipher = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/cipher.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
module3.exports = forge.cipher = forge.cipher || {};
forge.cipher.algorithms = forge.cipher.algorithms || {};
forge.cipher.createCipher = function(algorithm, key) {
var api = algorithm;
if (typeof api === "string") {
api = forge.cipher.getAlgorithm(api);
if (api) {
api = api();
}
}
if (!api) {
throw new Error("Unsupported algorithm: " + algorithm);
}
return new forge.cipher.BlockCipher({
algorithm: api,
key,
decrypt: false
});
};
forge.cipher.createDecipher = function(algorithm, key) {
var api = algorithm;
if (typeof api === "string") {
api = forge.cipher.getAlgorithm(api);
if (api) {
api = api();
}
}
if (!api) {
throw new Error("Unsupported algorithm: " + algorithm);
}
return new forge.cipher.BlockCipher({
algorithm: api,
key,
decrypt: true
});
};
forge.cipher.registerAlgorithm = function(name2, algorithm) {
name2 = name2.toUpperCase();
forge.cipher.algorithms[name2] = algorithm;
};
forge.cipher.getAlgorithm = function(name2) {
name2 = name2.toUpperCase();
if (name2 in forge.cipher.algorithms) {
return forge.cipher.algorithms[name2];
}
return null;
};
var BlockCipher = forge.cipher.BlockCipher = function(options) {
this.algorithm = options.algorithm;
this.mode = this.algorithm.mode;
this.blockSize = this.mode.blockSize;
this._finish = false;
this._input = null;
this.output = null;
this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;
this._decrypt = options.decrypt;
this.algorithm.initialize(options);
};
BlockCipher.prototype.start = function(options) {
options = options || {};
var opts = {};
for (var key in options) {
opts[key] = options[key];
}
opts.decrypt = this._decrypt;
this._finish = false;
this._input = forge.util.createBuffer();
this.output = options.output || forge.util.createBuffer();
this.mode.start(opts);
};
BlockCipher.prototype.update = function(input) {
if (input) {
this._input.putBuffer(input);
}
while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) {
}
this._input.compact();
};
BlockCipher.prototype.finish = function(pad2) {
if (pad2 && (this.mode.name === "ECB" || this.mode.name === "CBC")) {
this.mode.pad = function(input) {
return pad2(this.blockSize, input, false);
};
this.mode.unpad = function(output) {
return pad2(this.blockSize, output, true);
};
}
var options = {};
options.decrypt = this._decrypt;
options.overflow = this._input.length() % this.blockSize;
if (!this._decrypt && this.mode.pad) {
if (!this.mode.pad(this._input, options)) {
return false;
}
}
this._finish = true;
this.update();
if (this._decrypt && this.mode.unpad) {
if (!this.mode.unpad(this.output, options)) {
return false;
}
}
if (this.mode.afterFinish) {
if (!this.mode.afterFinish(this.output, options)) {
return false;
}
}
return true;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/cipherModes.js
var require_cipherModes = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/cipherModes.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
forge.cipher = forge.cipher || {};
var modes = module3.exports = forge.cipher.modes = forge.cipher.modes || {};
modes.ecb = function(options) {
options = options || {};
this.name = "ECB";
this.cipher = options.cipher;
this.blockSize = options.blockSize || 16;
this._ints = this.blockSize / 4;
this._inBlock = new Array(this._ints);
this._outBlock = new Array(this._ints);
};
modes.ecb.prototype.start = function(options) {
};
modes.ecb.prototype.encrypt = function(input, output, finish) {
if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
return true;
}
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = input.getInt32();
}
this.cipher.encrypt(this._inBlock, this._outBlock);
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(this._outBlock[i5]);
}
};
modes.ecb.prototype.decrypt = function(input, output, finish) {
if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
return true;
}
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = input.getInt32();
}
this.cipher.decrypt(this._inBlock, this._outBlock);
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(this._outBlock[i5]);
}
};
modes.ecb.prototype.pad = function(input, options) {
var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length();
input.fillWithByte(padding, padding);
return true;
};
modes.ecb.prototype.unpad = function(output, options) {
if (options.overflow > 0) {
return false;
}
var len = output.length();
var count = output.at(len - 1);
if (count > this.blockSize << 2) {
return false;
}
output.truncate(count);
return true;
};
modes.cbc = function(options) {
options = options || {};
this.name = "CBC";
this.cipher = options.cipher;
this.blockSize = options.blockSize || 16;
this._ints = this.blockSize / 4;
this._inBlock = new Array(this._ints);
this._outBlock = new Array(this._ints);
};
modes.cbc.prototype.start = function(options) {
if (options.iv === null) {
if (!this._prev) {
throw new Error("Invalid IV parameter.");
}
this._iv = this._prev.slice(0);
} else if (!("iv" in options)) {
throw new Error("Invalid IV parameter.");
} else {
this._iv = transformIV(options.iv, this.blockSize);
this._prev = this._iv.slice(0);
}
};
modes.cbc.prototype.encrypt = function(input, output, finish) {
if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
return true;
}
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = this._prev[i5] ^ input.getInt32();
}
this.cipher.encrypt(this._inBlock, this._outBlock);
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(this._outBlock[i5]);
}
this._prev = this._outBlock;
};
modes.cbc.prototype.decrypt = function(input, output, finish) {
if (input.length() < this.blockSize && !(finish && input.length() > 0)) {
return true;
}
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = input.getInt32();
}
this.cipher.decrypt(this._inBlock, this._outBlock);
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(this._prev[i5] ^ this._outBlock[i5]);
}
this._prev = this._inBlock.slice(0);
};
modes.cbc.prototype.pad = function(input, options) {
var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length();
input.fillWithByte(padding, padding);
return true;
};
modes.cbc.prototype.unpad = function(output, options) {
if (options.overflow > 0) {
return false;
}
var len = output.length();
var count = output.at(len - 1);
if (count > this.blockSize << 2) {
return false;
}
output.truncate(count);
return true;
};
modes.cfb = function(options) {
options = options || {};
this.name = "CFB";
this.cipher = options.cipher;
this.blockSize = options.blockSize || 16;
this._ints = this.blockSize / 4;
this._inBlock = null;
this._outBlock = new Array(this._ints);
this._partialBlock = new Array(this._ints);
this._partialOutput = forge.util.createBuffer();
this._partialBytes = 0;
};
modes.cfb.prototype.start = function(options) {
if (!("iv" in options)) {
throw new Error("Invalid IV parameter.");
}
this._iv = transformIV(options.iv, this.blockSize);
this._inBlock = this._iv.slice(0);
this._partialBytes = 0;
};
modes.cfb.prototype.encrypt = function(input, output, finish) {
var inputLength = input.length();
if (inputLength === 0) {
return true;
}
this.cipher.encrypt(this._inBlock, this._outBlock);
if (this._partialBytes === 0 && inputLength >= this.blockSize) {
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = input.getInt32() ^ this._outBlock[i5];
output.putInt32(this._inBlock[i5]);
}
return;
}
var partialBytes = (this.blockSize - inputLength) % this.blockSize;
if (partialBytes > 0) {
partialBytes = this.blockSize - partialBytes;
}
this._partialOutput.clear();
for (var i5 = 0; i5 < this._ints; ++i5) {
this._partialBlock[i5] = input.getInt32() ^ this._outBlock[i5];
this._partialOutput.putInt32(this._partialBlock[i5]);
}
if (partialBytes > 0) {
input.read -= this.blockSize;
} else {
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = this._partialBlock[i5];
}
}
if (this._partialBytes > 0) {
this._partialOutput.getBytes(this._partialBytes);
}
if (partialBytes > 0 && !finish) {
output.putBytes(this._partialOutput.getBytes(
partialBytes - this._partialBytes
));
this._partialBytes = partialBytes;
return true;
}
output.putBytes(this._partialOutput.getBytes(
inputLength - this._partialBytes
));
this._partialBytes = 0;
};
modes.cfb.prototype.decrypt = function(input, output, finish) {
var inputLength = input.length();
if (inputLength === 0) {
return true;
}
this.cipher.encrypt(this._inBlock, this._outBlock);
if (this._partialBytes === 0 && inputLength >= this.blockSize) {
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = input.getInt32();
output.putInt32(this._inBlock[i5] ^ this._outBlock[i5]);
}
return;
}
var partialBytes = (this.blockSize - inputLength) % this.blockSize;
if (partialBytes > 0) {
partialBytes = this.blockSize - partialBytes;
}
this._partialOutput.clear();
for (var i5 = 0; i5 < this._ints; ++i5) {
this._partialBlock[i5] = input.getInt32();
this._partialOutput.putInt32(this._partialBlock[i5] ^ this._outBlock[i5]);
}
if (partialBytes > 0) {
input.read -= this.blockSize;
} else {
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = this._partialBlock[i5];
}
}
if (this._partialBytes > 0) {
this._partialOutput.getBytes(this._partialBytes);
}
if (partialBytes > 0 && !finish) {
output.putBytes(this._partialOutput.getBytes(
partialBytes - this._partialBytes
));
this._partialBytes = partialBytes;
return true;
}
output.putBytes(this._partialOutput.getBytes(
inputLength - this._partialBytes
));
this._partialBytes = 0;
};
modes.ofb = function(options) {
options = options || {};
this.name = "OFB";
this.cipher = options.cipher;
this.blockSize = options.blockSize || 16;
this._ints = this.blockSize / 4;
this._inBlock = null;
this._outBlock = new Array(this._ints);
this._partialOutput = forge.util.createBuffer();
this._partialBytes = 0;
};
modes.ofb.prototype.start = function(options) {
if (!("iv" in options)) {
throw new Error("Invalid IV parameter.");
}
this._iv = transformIV(options.iv, this.blockSize);
this._inBlock = this._iv.slice(0);
this._partialBytes = 0;
};
modes.ofb.prototype.encrypt = function(input, output, finish) {
var inputLength = input.length();
if (input.length() === 0) {
return true;
}
this.cipher.encrypt(this._inBlock, this._outBlock);
if (this._partialBytes === 0 && inputLength >= this.blockSize) {
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(input.getInt32() ^ this._outBlock[i5]);
this._inBlock[i5] = this._outBlock[i5];
}
return;
}
var partialBytes = (this.blockSize - inputLength) % this.blockSize;
if (partialBytes > 0) {
partialBytes = this.blockSize - partialBytes;
}
this._partialOutput.clear();
for (var i5 = 0; i5 < this._ints; ++i5) {
this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i5]);
}
if (partialBytes > 0) {
input.read -= this.blockSize;
} else {
for (var i5 = 0; i5 < this._ints; ++i5) {
this._inBlock[i5] = this._outBlock[i5];
}
}
if (this._partialBytes > 0) {
this._partialOutput.getBytes(this._partialBytes);
}
if (partialBytes > 0 && !finish) {
output.putBytes(this._partialOutput.getBytes(
partialBytes - this._partialBytes
));
this._partialBytes = partialBytes;
return true;
}
output.putBytes(this._partialOutput.getBytes(
inputLength - this._partialBytes
));
this._partialBytes = 0;
};
modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;
modes.ctr = function(options) {
options = options || {};
this.name = "CTR";
this.cipher = options.cipher;
this.blockSize = options.blockSize || 16;
this._ints = this.blockSize / 4;
this._inBlock = null;
this._outBlock = new Array(this._ints);
this._partialOutput = forge.util.createBuffer();
this._partialBytes = 0;
};
modes.ctr.prototype.start = function(options) {
if (!("iv" in options)) {
throw new Error("Invalid IV parameter.");
}
this._iv = transformIV(options.iv, this.blockSize);
this._inBlock = this._iv.slice(0);
this._partialBytes = 0;
};
modes.ctr.prototype.encrypt = function(input, output, finish) {
var inputLength = input.length();
if (inputLength === 0) {
return true;
}
this.cipher.encrypt(this._inBlock, this._outBlock);
if (this._partialBytes === 0 && inputLength >= this.blockSize) {
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(input.getInt32() ^ this._outBlock[i5]);
}
} else {
var partialBytes = (this.blockSize - inputLength) % this.blockSize;
if (partialBytes > 0) {
partialBytes = this.blockSize - partialBytes;
}
this._partialOutput.clear();
for (var i5 = 0; i5 < this._ints; ++i5) {
this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i5]);
}
if (partialBytes > 0) {
input.read -= this.blockSize;
}
if (this._partialBytes > 0) {
this._partialOutput.getBytes(this._partialBytes);
}
if (partialBytes > 0 && !finish) {
output.putBytes(this._partialOutput.getBytes(
partialBytes - this._partialBytes
));
this._partialBytes = partialBytes;
return true;
}
output.putBytes(this._partialOutput.getBytes(
inputLength - this._partialBytes
));
this._partialBytes = 0;
}
inc32(this._inBlock);
};
modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;
modes.gcm = function(options) {
options = options || {};
this.name = "GCM";
this.cipher = options.cipher;
this.blockSize = options.blockSize || 16;
this._ints = this.blockSize / 4;
this._inBlock = new Array(this._ints);
this._outBlock = new Array(this._ints);
this._partialOutput = forge.util.createBuffer();
this._partialBytes = 0;
this._R = 3774873600;
};
modes.gcm.prototype.start = function(options) {
if (!("iv" in options)) {
throw new Error("Invalid IV parameter.");
}
var iv = forge.util.createBuffer(options.iv);
this._cipherLength = 0;
var additionalData;
if ("additionalData" in options) {
additionalData = forge.util.createBuffer(options.additionalData);
} else {
additionalData = forge.util.createBuffer();
}
if ("tagLength" in options) {
this._tagLength = options.tagLength;
} else {
this._tagLength = 128;
}
this._tag = null;
if (options.decrypt) {
this._tag = forge.util.createBuffer(options.tag).getBytes();
if (this._tag.length !== this._tagLength / 8) {
throw new Error("Authentication tag does not match tag length.");
}
}
this._hashBlock = new Array(this._ints);
this.tag = null;
this._hashSubkey = new Array(this._ints);
this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);
this.componentBits = 4;
this._m = this.generateHashTable(this._hashSubkey, this.componentBits);
var ivLength = iv.length();
if (ivLength === 12) {
this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];
} else {
this._j0 = [0, 0, 0, 0];
while (iv.length() > 0) {
this._j0 = this.ghash(
this._hashSubkey,
this._j0,
[iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]
);
}
this._j0 = this.ghash(
this._hashSubkey,
this._j0,
[0, 0].concat(from64To32(ivLength * 8))
);
}
this._inBlock = this._j0.slice(0);
inc32(this._inBlock);
this._partialBytes = 0;
additionalData = forge.util.createBuffer(additionalData);
this._aDataLength = from64To32(additionalData.length() * 8);
var overflow = additionalData.length() % this.blockSize;
if (overflow) {
additionalData.fillWithByte(0, this.blockSize - overflow);
}
this._s = [0, 0, 0, 0];
while (additionalData.length() > 0) {
this._s = this.ghash(this._hashSubkey, this._s, [
additionalData.getInt32(),
additionalData.getInt32(),
additionalData.getInt32(),
additionalData.getInt32()
]);
}
};
modes.gcm.prototype.encrypt = function(input, output, finish) {
var inputLength = input.length();
if (inputLength === 0) {
return true;
}
this.cipher.encrypt(this._inBlock, this._outBlock);
if (this._partialBytes === 0 && inputLength >= this.blockSize) {
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(this._outBlock[i5] ^= input.getInt32());
}
this._cipherLength += this.blockSize;
} else {
var partialBytes = (this.blockSize - inputLength) % this.blockSize;
if (partialBytes > 0) {
partialBytes = this.blockSize - partialBytes;
}
this._partialOutput.clear();
for (var i5 = 0; i5 < this._ints; ++i5) {
this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i5]);
}
if (partialBytes <= 0 || finish) {
if (finish) {
var overflow = inputLength % this.blockSize;
this._cipherLength += overflow;
this._partialOutput.truncate(this.blockSize - overflow);
} else {
this._cipherLength += this.blockSize;
}
for (var i5 = 0; i5 < this._ints; ++i5) {
this._outBlock[i5] = this._partialOutput.getInt32();
}
this._partialOutput.read -= this.blockSize;
}
if (this._partialBytes > 0) {
this._partialOutput.getBytes(this._partialBytes);
}
if (partialBytes > 0 && !finish) {
input.read -= this.blockSize;
output.putBytes(this._partialOutput.getBytes(
partialBytes - this._partialBytes
));
this._partialBytes = partialBytes;
return true;
}
output.putBytes(this._partialOutput.getBytes(
inputLength - this._partialBytes
));
this._partialBytes = 0;
}
this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);
inc32(this._inBlock);
};
modes.gcm.prototype.decrypt = function(input, output, finish) {
var inputLength = input.length();
if (inputLength < this.blockSize && !(finish && inputLength > 0)) {
return true;
}
this.cipher.encrypt(this._inBlock, this._outBlock);
inc32(this._inBlock);
this._hashBlock[0] = input.getInt32();
this._hashBlock[1] = input.getInt32();
this._hashBlock[2] = input.getInt32();
this._hashBlock[3] = input.getInt32();
this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);
for (var i5 = 0; i5 < this._ints; ++i5) {
output.putInt32(this._outBlock[i5] ^ this._hashBlock[i5]);
}
if (inputLength < this.blockSize) {
this._cipherLength += inputLength % this.blockSize;
} else {
this._cipherLength += this.blockSize;
}
};
modes.gcm.prototype.afterFinish = function(output, options) {
var rval = true;
if (options.decrypt && options.overflow) {
output.truncate(this.blockSize - options.overflow);
}
this.tag = forge.util.createBuffer();
var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));
this._s = this.ghash(this._hashSubkey, this._s, lengths);
var tag = [];
this.cipher.encrypt(this._j0, tag);
for (var i5 = 0; i5 < this._ints; ++i5) {
this.tag.putInt32(this._s[i5] ^ tag[i5]);
}
this.tag.truncate(this.tag.length() % (this._tagLength / 8));
if (options.decrypt && this.tag.bytes() !== this._tag) {
rval = false;
}
return rval;
};
modes.gcm.prototype.multiply = function(x6, y4) {
var z_i = [0, 0, 0, 0];
var v_i = y4.slice(0);
for (var i5 = 0; i5 < 128; ++i5) {
var x_i = x6[i5 / 32 | 0] & 1 << 31 - i5 % 32;
if (x_i) {
z_i[0] ^= v_i[0];
z_i[1] ^= v_i[1];
z_i[2] ^= v_i[2];
z_i[3] ^= v_i[3];
}
this.pow(v_i, v_i);
}
return z_i;
};
modes.gcm.prototype.pow = function(x6, out) {
var lsb = x6[3] & 1;
for (var i5 = 3; i5 > 0; --i5) {
out[i5] = x6[i5] >>> 1 | (x6[i5 - 1] & 1) << 31;
}
out[0] = x6[0] >>> 1;
if (lsb) {
out[0] ^= this._R;
}
};
modes.gcm.prototype.tableMultiply = function(x6) {
var z5 = [0, 0, 0, 0];
for (var i5 = 0; i5 < 32; ++i5) {
var idx = i5 / 8 | 0;
var x_i = x6[idx] >>> (7 - i5 % 8) * 4 & 15;
var ah2 = this._m[i5][x_i];
z5[0] ^= ah2[0];
z5[1] ^= ah2[1];
z5[2] ^= ah2[2];
z5[3] ^= ah2[3];
}
return z5;
};
modes.gcm.prototype.ghash = function(h6, y4, x6) {
y4[0] ^= x6[0];
y4[1] ^= x6[1];
y4[2] ^= x6[2];
y4[3] ^= x6[3];
return this.tableMultiply(y4);
};
modes.gcm.prototype.generateHashTable = function(h6, bits) {
var multiplier = 8 / bits;
var perInt = 4 * multiplier;
var size = 16 * multiplier;
var m6 = new Array(size);
for (var i5 = 0; i5 < size; ++i5) {
var tmp = [0, 0, 0, 0];
var idx = i5 / perInt | 0;
var shft = (perInt - 1 - i5 % perInt) * bits;
tmp[idx] = 1 << bits - 1 << shft;
m6[i5] = this.generateSubHashTable(this.multiply(tmp, h6), bits);
}
return m6;
};
modes.gcm.prototype.generateSubHashTable = function(mid, bits) {
var size = 1 << bits;
var half = size >>> 1;
var m6 = new Array(size);
m6[half] = mid.slice(0);
var i5 = half >>> 1;
while (i5 > 0) {
this.pow(m6[2 * i5], m6[i5] = []);
i5 >>= 1;
}
i5 = 2;
while (i5 < half) {
for (var j6 = 1; j6 < i5; ++j6) {
var m_i = m6[i5];
var m_j = m6[j6];
m6[i5 + j6] = [
m_i[0] ^ m_j[0],
m_i[1] ^ m_j[1],
m_i[2] ^ m_j[2],
m_i[3] ^ m_j[3]
];
}
i5 *= 2;
}
m6[0] = [0, 0, 0, 0];
for (i5 = half + 1; i5 < size; ++i5) {
var c6 = m6[i5 ^ half];
m6[i5] = [mid[0] ^ c6[0], mid[1] ^ c6[1], mid[2] ^ c6[2], mid[3] ^ c6[3]];
}
return m6;
};
function transformIV(iv, blockSize) {
if (typeof iv === "string") {
iv = forge.util.createBuffer(iv);
}
if (forge.util.isArray(iv) && iv.length > 4) {
var tmp = iv;
iv = forge.util.createBuffer();
for (var i5 = 0; i5 < tmp.length; ++i5) {
iv.putByte(tmp[i5]);
}
}
if (iv.length() < blockSize) {
throw new Error(
"Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes."
);
}
if (!forge.util.isArray(iv)) {
var ints = [];
var blocks = blockSize / 4;
for (var i5 = 0; i5 < blocks; ++i5) {
ints.push(iv.getInt32());
}
iv = ints;
}
return iv;
}
__name(transformIV, "transformIV");
function inc32(block) {
block[block.length - 1] = block[block.length - 1] + 1 & 4294967295;
}
__name(inc32, "inc32");
function from64To32(num) {
return [num / 4294967296 | 0, num & 4294967295];
}
__name(from64To32, "from64To32");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/aes.js
var require_aes = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/aes.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_cipher();
require_cipherModes();
require_util10();
module3.exports = forge.aes = forge.aes || {};
forge.aes.startEncrypting = function(key, iv, output, mode) {
var cipher = _createCipher({
key,
output,
decrypt: false,
mode
});
cipher.start(iv);
return cipher;
};
forge.aes.createEncryptionCipher = function(key, mode) {
return _createCipher({
key,
output: null,
decrypt: false,
mode
});
};
forge.aes.startDecrypting = function(key, iv, output, mode) {
var cipher = _createCipher({
key,
output,
decrypt: true,
mode
});
cipher.start(iv);
return cipher;
};
forge.aes.createDecryptionCipher = function(key, mode) {
return _createCipher({
key,
output: null,
decrypt: true,
mode
});
};
forge.aes.Algorithm = function(name2, mode) {
if (!init3) {
initialize();
}
var self2 = this;
self2.name = name2;
self2.mode = new mode({
blockSize: 16,
cipher: {
encrypt: /* @__PURE__ */ __name(function(inBlock, outBlock) {
return _updateBlock(self2._w, inBlock, outBlock, false);
}, "encrypt"),
decrypt: /* @__PURE__ */ __name(function(inBlock, outBlock) {
return _updateBlock(self2._w, inBlock, outBlock, true);
}, "decrypt")
}
});
self2._init = false;
};
forge.aes.Algorithm.prototype.initialize = function(options) {
if (this._init) {
return;
}
var key = options.key;
var tmp;
if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) {
key = forge.util.createBuffer(key);
} else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) {
tmp = key;
key = forge.util.createBuffer();
for (var i5 = 0; i5 < tmp.length; ++i5) {
key.putByte(tmp[i5]);
}
}
if (!forge.util.isArray(key)) {
tmp = key;
key = [];
var len = tmp.length();
if (len === 16 || len === 24 || len === 32) {
len = len >>> 2;
for (var i5 = 0; i5 < len; ++i5) {
key.push(tmp.getInt32());
}
}
}
if (!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) {
throw new Error("Invalid key parameter.");
}
var mode = this.mode.name;
var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1;
this._w = _expandKey(key, options.decrypt && !encryptOp);
this._init = true;
};
forge.aes._expandKey = function(key, decrypt) {
if (!init3) {
initialize();
}
return _expandKey(key, decrypt);
};
forge.aes._updateBlock = _updateBlock;
registerAlgorithm("AES-ECB", forge.cipher.modes.ecb);
registerAlgorithm("AES-CBC", forge.cipher.modes.cbc);
registerAlgorithm("AES-CFB", forge.cipher.modes.cfb);
registerAlgorithm("AES-OFB", forge.cipher.modes.ofb);
registerAlgorithm("AES-CTR", forge.cipher.modes.ctr);
registerAlgorithm("AES-GCM", forge.cipher.modes.gcm);
function registerAlgorithm(name2, mode) {
var factory = /* @__PURE__ */ __name(function() {
return new forge.aes.Algorithm(name2, mode);
}, "factory");
forge.cipher.registerAlgorithm(name2, factory);
}
__name(registerAlgorithm, "registerAlgorithm");
var init3 = false;
var Nb = 4;
var sbox;
var isbox;
var rcon;
var mix;
var imix;
function initialize() {
init3 = true;
rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
var xtime = new Array(256);
for (var i5 = 0; i5 < 128; ++i5) {
xtime[i5] = i5 << 1;
xtime[i5 + 128] = i5 + 128 << 1 ^ 283;
}
sbox = new Array(256);
isbox = new Array(256);
mix = new Array(4);
imix = new Array(4);
for (var i5 = 0; i5 < 4; ++i5) {
mix[i5] = new Array(256);
imix[i5] = new Array(256);
}
var e7 = 0, ei = 0, e22, e42, e8, sx, sx2, me, ime;
for (var i5 = 0; i5 < 256; ++i5) {
sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4;
sx = sx >> 8 ^ sx & 255 ^ 99;
sbox[e7] = sx;
isbox[sx] = e7;
sx2 = xtime[sx];
e22 = xtime[e7];
e42 = xtime[e22];
e8 = xtime[e42];
me = sx2 << 24 ^ // 2
sx << 16 ^ // 1
sx << 8 ^ // 1
(sx ^ sx2);
ime = (e22 ^ e42 ^ e8) << 24 ^ // E (14)
(e7 ^ e8) << 16 ^ // 9
(e7 ^ e42 ^ e8) << 8 ^ // D (13)
(e7 ^ e22 ^ e8);
for (var n6 = 0; n6 < 4; ++n6) {
mix[n6][e7] = me;
imix[n6][sx] = ime;
me = me << 24 | me >>> 8;
ime = ime << 24 | ime >>> 8;
}
if (e7 === 0) {
e7 = ei = 1;
} else {
e7 = e22 ^ xtime[xtime[xtime[e22 ^ e8]]];
ei ^= xtime[xtime[ei]];
}
}
}
__name(initialize, "initialize");
function _expandKey(key, decrypt) {
var w6 = key.slice(0);
var temp, iNk = 1;
var Nk = w6.length;
var Nr1 = Nk + 6 + 1;
var end = Nb * Nr1;
for (var i5 = Nk; i5 < end; ++i5) {
temp = w6[i5 - 1];
if (i5 % Nk === 0) {
temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24;
iNk++;
} else if (Nk > 6 && i5 % Nk === 4) {
temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255];
}
w6[i5] = w6[i5 - Nk] ^ temp;
}
if (decrypt) {
var tmp;
var m0 = imix[0];
var m1 = imix[1];
var m22 = imix[2];
var m32 = imix[3];
var wnew = w6.slice(0);
end = w6.length;
for (var i5 = 0, wi = end - Nb; i5 < end; i5 += Nb, wi -= Nb) {
if (i5 === 0 || i5 === end - Nb) {
wnew[i5] = w6[wi];
wnew[i5 + 1] = w6[wi + 3];
wnew[i5 + 2] = w6[wi + 2];
wnew[i5 + 3] = w6[wi + 1];
} else {
for (var n6 = 0; n6 < Nb; ++n6) {
tmp = w6[wi + n6];
wnew[i5 + (3 & -n6)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m22[sbox[tmp >>> 8 & 255]] ^ m32[sbox[tmp & 255]];
}
}
}
w6 = wnew;
}
return w6;
}
__name(_expandKey, "_expandKey");
function _updateBlock(w6, input, output, decrypt) {
var Nr = w6.length / 4 - 1;
var m0, m1, m22, m32, sub;
if (decrypt) {
m0 = imix[0];
m1 = imix[1];
m22 = imix[2];
m32 = imix[3];
sub = isbox;
} else {
m0 = mix[0];
m1 = mix[1];
m22 = mix[2];
m32 = mix[3];
sub = sbox;
}
var a5, b6, c6, d6, a22, b22, c22;
a5 = input[0] ^ w6[0];
b6 = input[decrypt ? 3 : 1] ^ w6[1];
c6 = input[2] ^ w6[2];
d6 = input[decrypt ? 1 : 3] ^ w6[3];
var i5 = 3;
for (var round = 1; round < Nr; ++round) {
a22 = m0[a5 >>> 24] ^ m1[b6 >>> 16 & 255] ^ m22[c6 >>> 8 & 255] ^ m32[d6 & 255] ^ w6[++i5];
b22 = m0[b6 >>> 24] ^ m1[c6 >>> 16 & 255] ^ m22[d6 >>> 8 & 255] ^ m32[a5 & 255] ^ w6[++i5];
c22 = m0[c6 >>> 24] ^ m1[d6 >>> 16 & 255] ^ m22[a5 >>> 8 & 255] ^ m32[b6 & 255] ^ w6[++i5];
d6 = m0[d6 >>> 24] ^ m1[a5 >>> 16 & 255] ^ m22[b6 >>> 8 & 255] ^ m32[c6 & 255] ^ w6[++i5];
a5 = a22;
b6 = b22;
c6 = c22;
}
output[0] = sub[a5 >>> 24] << 24 ^ sub[b6 >>> 16 & 255] << 16 ^ sub[c6 >>> 8 & 255] << 8 ^ sub[d6 & 255] ^ w6[++i5];
output[decrypt ? 3 : 1] = sub[b6 >>> 24] << 24 ^ sub[c6 >>> 16 & 255] << 16 ^ sub[d6 >>> 8 & 255] << 8 ^ sub[a5 & 255] ^ w6[++i5];
output[2] = sub[c6 >>> 24] << 24 ^ sub[d6 >>> 16 & 255] << 16 ^ sub[a5 >>> 8 & 255] << 8 ^ sub[b6 & 255] ^ w6[++i5];
output[decrypt ? 1 : 3] = sub[d6 >>> 24] << 24 ^ sub[a5 >>> 16 & 255] << 16 ^ sub[b6 >>> 8 & 255] << 8 ^ sub[c6 & 255] ^ w6[++i5];
}
__name(_updateBlock, "_updateBlock");
function _createCipher(options) {
options = options || {};
var mode = (options.mode || "CBC").toUpperCase();
var algorithm = "AES-" + mode;
var cipher;
if (options.decrypt) {
cipher = forge.cipher.createDecipher(algorithm, options.key);
} else {
cipher = forge.cipher.createCipher(algorithm, options.key);
}
var start = cipher.start;
cipher.start = function(iv, options2) {
var output = null;
if (options2 instanceof forge.util.ByteBuffer) {
output = options2;
options2 = {};
}
options2 = options2 || {};
options2.output = output;
options2.iv = iv;
start.call(cipher, options2);
};
return cipher;
}
__name(_createCipher, "_createCipher");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/oids.js
var require_oids = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/oids.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
forge.pki = forge.pki || {};
var oids = module3.exports = forge.pki.oids = forge.oids = forge.oids || {};
function _IN(id, name2) {
oids[id] = name2;
oids[name2] = id;
}
__name(_IN, "_IN");
function _I_(id, name2) {
oids[id] = name2;
}
__name(_I_, "_I_");
_IN("1.2.840.113549.1.1.1", "rsaEncryption");
_IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption");
_IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption");
_IN("1.2.840.113549.1.1.7", "RSAES-OAEP");
_IN("1.2.840.113549.1.1.8", "mgf1");
_IN("1.2.840.113549.1.1.9", "pSpecified");
_IN("1.2.840.113549.1.1.10", "RSASSA-PSS");
_IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption");
_IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption");
_IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption");
_IN("1.3.101.112", "EdDSA25519");
_IN("1.2.840.10040.4.3", "dsa-with-sha1");
_IN("1.3.14.3.2.7", "desCBC");
_IN("1.3.14.3.2.26", "sha1");
_IN("1.3.14.3.2.29", "sha1WithRSASignature");
_IN("2.16.840.1.101.3.4.2.1", "sha256");
_IN("2.16.840.1.101.3.4.2.2", "sha384");
_IN("2.16.840.1.101.3.4.2.3", "sha512");
_IN("2.16.840.1.101.3.4.2.4", "sha224");
_IN("2.16.840.1.101.3.4.2.5", "sha512-224");
_IN("2.16.840.1.101.3.4.2.6", "sha512-256");
_IN("1.2.840.113549.2.2", "md2");
_IN("1.2.840.113549.2.5", "md5");
_IN("1.2.840.113549.1.7.1", "data");
_IN("1.2.840.113549.1.7.2", "signedData");
_IN("1.2.840.113549.1.7.3", "envelopedData");
_IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData");
_IN("1.2.840.113549.1.7.5", "digestedData");
_IN("1.2.840.113549.1.7.6", "encryptedData");
_IN("1.2.840.113549.1.9.1", "emailAddress");
_IN("1.2.840.113549.1.9.2", "unstructuredName");
_IN("1.2.840.113549.1.9.3", "contentType");
_IN("1.2.840.113549.1.9.4", "messageDigest");
_IN("1.2.840.113549.1.9.5", "signingTime");
_IN("1.2.840.113549.1.9.6", "counterSignature");
_IN("1.2.840.113549.1.9.7", "challengePassword");
_IN("1.2.840.113549.1.9.8", "unstructuredAddress");
_IN("1.2.840.113549.1.9.14", "extensionRequest");
_IN("1.2.840.113549.1.9.20", "friendlyName");
_IN("1.2.840.113549.1.9.21", "localKeyId");
_IN("1.2.840.113549.1.9.22.1", "x509Certificate");
_IN("1.2.840.113549.1.12.10.1.1", "keyBag");
_IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag");
_IN("1.2.840.113549.1.12.10.1.3", "certBag");
_IN("1.2.840.113549.1.12.10.1.4", "crlBag");
_IN("1.2.840.113549.1.12.10.1.5", "secretBag");
_IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag");
_IN("1.2.840.113549.1.5.13", "pkcs5PBES2");
_IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2");
_IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4");
_IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4");
_IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC");
_IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC");
_IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC");
_IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC");
_IN("1.2.840.113549.2.7", "hmacWithSHA1");
_IN("1.2.840.113549.2.8", "hmacWithSHA224");
_IN("1.2.840.113549.2.9", "hmacWithSHA256");
_IN("1.2.840.113549.2.10", "hmacWithSHA384");
_IN("1.2.840.113549.2.11", "hmacWithSHA512");
_IN("1.2.840.113549.3.7", "des-EDE3-CBC");
_IN("2.16.840.1.101.3.4.1.2", "aes128-CBC");
_IN("2.16.840.1.101.3.4.1.22", "aes192-CBC");
_IN("2.16.840.1.101.3.4.1.42", "aes256-CBC");
_IN("2.5.4.3", "commonName");
_IN("2.5.4.4", "surname");
_IN("2.5.4.5", "serialNumber");
_IN("2.5.4.6", "countryName");
_IN("2.5.4.7", "localityName");
_IN("2.5.4.8", "stateOrProvinceName");
_IN("2.5.4.9", "streetAddress");
_IN("2.5.4.10", "organizationName");
_IN("2.5.4.11", "organizationalUnitName");
_IN("2.5.4.12", "title");
_IN("2.5.4.13", "description");
_IN("2.5.4.15", "businessCategory");
_IN("2.5.4.17", "postalCode");
_IN("2.5.4.42", "givenName");
_IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName");
_IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName");
_IN("2.16.840.1.113730.1.1", "nsCertType");
_IN("2.16.840.1.113730.1.13", "nsComment");
_I_("2.5.29.1", "authorityKeyIdentifier");
_I_("2.5.29.2", "keyAttributes");
_I_("2.5.29.3", "certificatePolicies");
_I_("2.5.29.4", "keyUsageRestriction");
_I_("2.5.29.5", "policyMapping");
_I_("2.5.29.6", "subtreesConstraint");
_I_("2.5.29.7", "subjectAltName");
_I_("2.5.29.8", "issuerAltName");
_I_("2.5.29.9", "subjectDirectoryAttributes");
_I_("2.5.29.10", "basicConstraints");
_I_("2.5.29.11", "nameConstraints");
_I_("2.5.29.12", "policyConstraints");
_I_("2.5.29.13", "basicConstraints");
_IN("2.5.29.14", "subjectKeyIdentifier");
_IN("2.5.29.15", "keyUsage");
_I_("2.5.29.16", "privateKeyUsagePeriod");
_IN("2.5.29.17", "subjectAltName");
_IN("2.5.29.18", "issuerAltName");
_IN("2.5.29.19", "basicConstraints");
_I_("2.5.29.20", "cRLNumber");
_I_("2.5.29.21", "cRLReason");
_I_("2.5.29.22", "expirationDate");
_I_("2.5.29.23", "instructionCode");
_I_("2.5.29.24", "invalidityDate");
_I_("2.5.29.25", "cRLDistributionPoints");
_I_("2.5.29.26", "issuingDistributionPoint");
_I_("2.5.29.27", "deltaCRLIndicator");
_I_("2.5.29.28", "issuingDistributionPoint");
_I_("2.5.29.29", "certificateIssuer");
_I_("2.5.29.30", "nameConstraints");
_IN("2.5.29.31", "cRLDistributionPoints");
_IN("2.5.29.32", "certificatePolicies");
_I_("2.5.29.33", "policyMappings");
_I_("2.5.29.34", "policyConstraints");
_IN("2.5.29.35", "authorityKeyIdentifier");
_I_("2.5.29.36", "policyConstraints");
_IN("2.5.29.37", "extKeyUsage");
_I_("2.5.29.46", "freshestCRL");
_I_("2.5.29.54", "inhibitAnyPolicy");
_IN("1.3.6.1.4.1.11129.2.4.2", "timestampList");
_IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess");
_IN("1.3.6.1.5.5.7.3.1", "serverAuth");
_IN("1.3.6.1.5.5.7.3.2", "clientAuth");
_IN("1.3.6.1.5.5.7.3.3", "codeSigning");
_IN("1.3.6.1.5.5.7.3.4", "emailProtection");
_IN("1.3.6.1.5.5.7.3.8", "timeStamping");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/asn1.js
var require_asn1 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/asn1.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
require_oids();
var asn1 = module3.exports = forge.asn1 = forge.asn1 || {};
asn1.Class = {
UNIVERSAL: 0,
APPLICATION: 64,
CONTEXT_SPECIFIC: 128,
PRIVATE: 192
};
asn1.Type = {
NONE: 0,
BOOLEAN: 1,
INTEGER: 2,
BITSTRING: 3,
OCTETSTRING: 4,
NULL: 5,
OID: 6,
ODESC: 7,
EXTERNAL: 8,
REAL: 9,
ENUMERATED: 10,
EMBEDDED: 11,
UTF8: 12,
ROID: 13,
SEQUENCE: 16,
SET: 17,
PRINTABLESTRING: 19,
IA5STRING: 22,
UTCTIME: 23,
GENERALIZEDTIME: 24,
BMPSTRING: 30
};
asn1.create = function(tagClass, type, constructed, value, options) {
if (forge.util.isArray(value)) {
var tmp = [];
for (var i5 = 0; i5 < value.length; ++i5) {
if (value[i5] !== void 0) {
tmp.push(value[i5]);
}
}
value = tmp;
}
var obj = {
tagClass,
type,
constructed,
composed: constructed || forge.util.isArray(value),
value
};
if (options && "bitStringContents" in options) {
obj.bitStringContents = options.bitStringContents;
obj.original = asn1.copy(obj);
}
return obj;
};
asn1.copy = function(obj, options) {
var copy;
if (forge.util.isArray(obj)) {
copy = [];
for (var i5 = 0; i5 < obj.length; ++i5) {
copy.push(asn1.copy(obj[i5], options));
}
return copy;
}
if (typeof obj === "string") {
return obj;
}
copy = {
tagClass: obj.tagClass,
type: obj.type,
constructed: obj.constructed,
composed: obj.composed,
value: asn1.copy(obj.value, options)
};
if (options && !options.excludeBitStringContents) {
copy.bitStringContents = obj.bitStringContents;
}
return copy;
};
asn1.equals = function(obj1, obj2, options) {
if (forge.util.isArray(obj1)) {
if (!forge.util.isArray(obj2)) {
return false;
}
if (obj1.length !== obj2.length) {
return false;
}
for (var i5 = 0; i5 < obj1.length; ++i5) {
if (!asn1.equals(obj1[i5], obj2[i5])) {
return false;
}
}
return true;
}
if (typeof obj1 !== typeof obj2) {
return false;
}
if (typeof obj1 === "string") {
return obj1 === obj2;
}
var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value);
if (options && options.includeBitStringContents) {
equal = equal && obj1.bitStringContents === obj2.bitStringContents;
}
return equal;
};
asn1.getBerValueLength = function(b6) {
var b22 = b6.getByte();
if (b22 === 128) {
return void 0;
}
var length;
var longForm = b22 & 128;
if (!longForm) {
length = b22;
} else {
length = b6.getInt((b22 & 127) << 3);
}
return length;
};
function _checkBufferLength(bytes, remaining, n6) {
if (n6 > remaining) {
var error2 = new Error("Too few bytes to parse DER.");
error2.available = bytes.length();
error2.remaining = remaining;
error2.requested = n6;
throw error2;
}
}
__name(_checkBufferLength, "_checkBufferLength");
var _getValueLength = /* @__PURE__ */ __name(function(bytes, remaining) {
var b22 = bytes.getByte();
remaining--;
if (b22 === 128) {
return void 0;
}
var length;
var longForm = b22 & 128;
if (!longForm) {
length = b22;
} else {
var longFormBytes = b22 & 127;
_checkBufferLength(bytes, remaining, longFormBytes);
length = bytes.getInt(longFormBytes << 3);
}
if (length < 0) {
throw new Error("Negative length: " + length);
}
return length;
}, "_getValueLength");
asn1.fromDer = function(bytes, options) {
if (options === void 0) {
options = {
strict: true,
parseAllBytes: true,
decodeBitStrings: true
};
}
if (typeof options === "boolean") {
options = {
strict: options,
parseAllBytes: true,
decodeBitStrings: true
};
}
if (!("strict" in options)) {
options.strict = true;
}
if (!("parseAllBytes" in options)) {
options.parseAllBytes = true;
}
if (!("decodeBitStrings" in options)) {
options.decodeBitStrings = true;
}
if (typeof bytes === "string") {
bytes = forge.util.createBuffer(bytes);
}
var byteCount = bytes.length();
var value = _fromDer(bytes, bytes.length(), 0, options);
if (options.parseAllBytes && bytes.length() !== 0) {
var error2 = new Error("Unparsed DER bytes remain after ASN.1 parsing.");
error2.byteCount = byteCount;
error2.remaining = bytes.length();
throw error2;
}
return value;
};
function _fromDer(bytes, remaining, depth, options) {
var start;
_checkBufferLength(bytes, remaining, 2);
var b1 = bytes.getByte();
remaining--;
var tagClass = b1 & 192;
var type = b1 & 31;
start = bytes.length();
var length = _getValueLength(bytes, remaining);
remaining -= start - bytes.length();
if (length !== void 0 && length > remaining) {
if (options.strict) {
var error2 = new Error("Too few bytes to read ASN.1 value.");
error2.available = bytes.length();
error2.remaining = remaining;
error2.requested = length;
throw error2;
}
length = remaining;
}
var value;
var bitStringContents;
var constructed = (b1 & 32) === 32;
if (constructed) {
value = [];
if (length === void 0) {
for (; ; ) {
_checkBufferLength(bytes, remaining, 2);
if (bytes.bytes(2) === String.fromCharCode(0, 0)) {
bytes.getBytes(2);
remaining -= 2;
break;
}
start = bytes.length();
value.push(_fromDer(bytes, remaining, depth + 1, options));
remaining -= start - bytes.length();
}
} else {
while (length > 0) {
start = bytes.length();
value.push(_fromDer(bytes, length, depth + 1, options));
remaining -= start - bytes.length();
length -= start - bytes.length();
}
}
}
if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) {
bitStringContents = bytes.bytes(length);
}
if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here
// .. other parts of forge expect to decode OCTET STRINGs manually
type === asn1.Type.BITSTRING && length > 1) {
var savedRead = bytes.read;
var savedRemaining = remaining;
var unused = 0;
if (type === asn1.Type.BITSTRING) {
_checkBufferLength(bytes, remaining, 1);
unused = bytes.getByte();
remaining--;
}
if (unused === 0) {
try {
start = bytes.length();
var subOptions = {
// enforce strict mode to avoid parsing ASN.1 from plain data
strict: true,
decodeBitStrings: true
};
var composed = _fromDer(bytes, remaining, depth + 1, subOptions);
var used = start - bytes.length();
remaining -= used;
if (type == asn1.Type.BITSTRING) {
used++;
}
var tc = composed.tagClass;
if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {
value = [composed];
}
} catch (ex) {
}
}
if (value === void 0) {
bytes.read = savedRead;
remaining = savedRemaining;
}
}
if (value === void 0) {
if (length === void 0) {
if (options.strict) {
throw new Error("Non-constructed ASN.1 object of indefinite length.");
}
length = remaining;
}
if (type === asn1.Type.BMPSTRING) {
value = "";
for (; length > 0; length -= 2) {
_checkBufferLength(bytes, remaining, 2);
value += String.fromCharCode(bytes.getInt16());
remaining -= 2;
}
} else {
value = bytes.getBytes(length);
remaining -= length;
}
}
var asn1Options = bitStringContents === void 0 ? null : {
bitStringContents
};
return asn1.create(tagClass, type, constructed, value, asn1Options);
}
__name(_fromDer, "_fromDer");
asn1.toDer = function(obj) {
var bytes = forge.util.createBuffer();
var b1 = obj.tagClass | obj.type;
var value = forge.util.createBuffer();
var useBitStringContents = false;
if ("bitStringContents" in obj) {
useBitStringContents = true;
if (obj.original) {
useBitStringContents = asn1.equals(obj, obj.original);
}
}
if (useBitStringContents) {
value.putBytes(obj.bitStringContents);
} else if (obj.composed) {
if (obj.constructed) {
b1 |= 32;
} else {
value.putByte(0);
}
for (var i5 = 0; i5 < obj.value.length; ++i5) {
if (obj.value[i5] !== void 0) {
value.putBuffer(asn1.toDer(obj.value[i5]));
}
}
} else {
if (obj.type === asn1.Type.BMPSTRING) {
for (var i5 = 0; i5 < obj.value.length; ++i5) {
value.putInt16(obj.value.charCodeAt(i5));
}
} else {
if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer
(obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer
obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) {
value.putBytes(obj.value.substr(1));
} else {
value.putBytes(obj.value);
}
}
}
bytes.putByte(b1);
if (value.length() <= 127) {
bytes.putByte(value.length() & 127);
} else {
var len = value.length();
var lenBytes = "";
do {
lenBytes += String.fromCharCode(len & 255);
len = len >>> 8;
} while (len > 0);
bytes.putByte(lenBytes.length | 128);
for (var i5 = lenBytes.length - 1; i5 >= 0; --i5) {
bytes.putByte(lenBytes.charCodeAt(i5));
}
}
bytes.putBuffer(value);
return bytes;
};
asn1.oidToDer = function(oid) {
var values = oid.split(".");
var bytes = forge.util.createBuffer();
bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));
var last, valueBytes, value, b6;
for (var i5 = 2; i5 < values.length; ++i5) {
last = true;
valueBytes = [];
value = parseInt(values[i5], 10);
do {
b6 = value & 127;
value = value >>> 7;
if (!last) {
b6 |= 128;
}
valueBytes.push(b6);
last = false;
} while (value > 0);
for (var n6 = valueBytes.length - 1; n6 >= 0; --n6) {
bytes.putByte(valueBytes[n6]);
}
}
return bytes;
};
asn1.derToOid = function(bytes) {
var oid;
if (typeof bytes === "string") {
bytes = forge.util.createBuffer(bytes);
}
var b6 = bytes.getByte();
oid = Math.floor(b6 / 40) + "." + b6 % 40;
var value = 0;
while (bytes.length() > 0) {
b6 = bytes.getByte();
value = value << 7;
if (b6 & 128) {
value += b6 & 127;
} else {
oid += "." + (value + b6);
value = 0;
}
}
return oid;
};
asn1.utcTimeToDate = function(utc) {
var date = /* @__PURE__ */ new Date();
var year = parseInt(utc.substr(0, 2), 10);
year = year >= 50 ? 1900 + year : 2e3 + year;
var MM = parseInt(utc.substr(2, 2), 10) - 1;
var DD2 = parseInt(utc.substr(4, 2), 10);
var hh = parseInt(utc.substr(6, 2), 10);
var mm = parseInt(utc.substr(8, 2), 10);
var ss = 0;
if (utc.length > 11) {
var c6 = utc.charAt(10);
var end = 10;
if (c6 !== "+" && c6 !== "-") {
ss = parseInt(utc.substr(10, 2), 10);
end += 2;
}
}
date.setUTCFullYear(year, MM, DD2);
date.setUTCHours(hh, mm, ss, 0);
if (end) {
c6 = utc.charAt(end);
if (c6 === "+" || c6 === "-") {
var hhoffset = parseInt(utc.substr(end + 1, 2), 10);
var mmoffset = parseInt(utc.substr(end + 4, 2), 10);
var offset = hhoffset * 60 + mmoffset;
offset *= 6e4;
if (c6 === "+") {
date.setTime(+date - offset);
} else {
date.setTime(+date + offset);
}
}
}
return date;
};
asn1.generalizedTimeToDate = function(gentime) {
var date = /* @__PURE__ */ new Date();
var YYYY = parseInt(gentime.substr(0, 4), 10);
var MM = parseInt(gentime.substr(4, 2), 10) - 1;
var DD2 = parseInt(gentime.substr(6, 2), 10);
var hh = parseInt(gentime.substr(8, 2), 10);
var mm = parseInt(gentime.substr(10, 2), 10);
var ss = parseInt(gentime.substr(12, 2), 10);
var fff = 0;
var offset = 0;
var isUTC = false;
if (gentime.charAt(gentime.length - 1) === "Z") {
isUTC = true;
}
var end = gentime.length - 5, c6 = gentime.charAt(end);
if (c6 === "+" || c6 === "-") {
var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);
var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);
offset = hhoffset * 60 + mmoffset;
offset *= 6e4;
if (c6 === "+") {
offset *= -1;
}
isUTC = true;
}
if (gentime.charAt(14) === ".") {
fff = parseFloat(gentime.substr(14), 10) * 1e3;
}
if (isUTC) {
date.setUTCFullYear(YYYY, MM, DD2);
date.setUTCHours(hh, mm, ss, fff);
date.setTime(+date + offset);
} else {
date.setFullYear(YYYY, MM, DD2);
date.setHours(hh, mm, ss, fff);
}
return date;
};
asn1.dateToUtcTime = function(date) {
if (typeof date === "string") {
return date;
}
var rval = "";
var format9 = [];
format9.push(("" + date.getUTCFullYear()).substr(2));
format9.push("" + (date.getUTCMonth() + 1));
format9.push("" + date.getUTCDate());
format9.push("" + date.getUTCHours());
format9.push("" + date.getUTCMinutes());
format9.push("" + date.getUTCSeconds());
for (var i5 = 0; i5 < format9.length; ++i5) {
if (format9[i5].length < 2) {
rval += "0";
}
rval += format9[i5];
}
rval += "Z";
return rval;
};
asn1.dateToGeneralizedTime = function(date) {
if (typeof date === "string") {
return date;
}
var rval = "";
var format9 = [];
format9.push("" + date.getUTCFullYear());
format9.push("" + (date.getUTCMonth() + 1));
format9.push("" + date.getUTCDate());
format9.push("" + date.getUTCHours());
format9.push("" + date.getUTCMinutes());
format9.push("" + date.getUTCSeconds());
for (var i5 = 0; i5 < format9.length; ++i5) {
if (format9[i5].length < 2) {
rval += "0";
}
rval += format9[i5];
}
rval += "Z";
return rval;
};
asn1.integerToDer = function(x6) {
var rval = forge.util.createBuffer();
if (x6 >= -128 && x6 < 128) {
return rval.putSignedInt(x6, 8);
}
if (x6 >= -32768 && x6 < 32768) {
return rval.putSignedInt(x6, 16);
}
if (x6 >= -8388608 && x6 < 8388608) {
return rval.putSignedInt(x6, 24);
}
if (x6 >= -2147483648 && x6 < 2147483648) {
return rval.putSignedInt(x6, 32);
}
var error2 = new Error("Integer too large; max is 32-bits.");
error2.integer = x6;
throw error2;
};
asn1.derToInteger = function(bytes) {
if (typeof bytes === "string") {
bytes = forge.util.createBuffer(bytes);
}
var n6 = bytes.length() * 8;
if (n6 > 32) {
throw new Error("Integer too large; max is 32-bits.");
}
return bytes.getSignedInt(n6);
};
asn1.validate = function(obj, v7, capture, errors) {
var rval = false;
if ((obj.tagClass === v7.tagClass || typeof v7.tagClass === "undefined") && (obj.type === v7.type || typeof v7.type === "undefined")) {
if (obj.constructed === v7.constructed || typeof v7.constructed === "undefined") {
rval = true;
if (v7.value && forge.util.isArray(v7.value)) {
var j6 = 0;
for (var i5 = 0; rval && i5 < v7.value.length; ++i5) {
rval = v7.value[i5].optional || false;
if (obj.value[j6]) {
rval = asn1.validate(obj.value[j6], v7.value[i5], capture, errors);
if (rval) {
++j6;
} else if (v7.value[i5].optional) {
rval = true;
}
}
if (!rval && errors) {
errors.push(
"[" + v7.name + '] Tag class "' + v7.tagClass + '", type "' + v7.type + '" expected value length "' + v7.value.length + '", got "' + obj.value.length + '"'
);
}
}
}
if (rval && capture) {
if (v7.capture) {
capture[v7.capture] = obj.value;
}
if (v7.captureAsn1) {
capture[v7.captureAsn1] = obj;
}
if (v7.captureBitStringContents && "bitStringContents" in obj) {
capture[v7.captureBitStringContents] = obj.bitStringContents;
}
if (v7.captureBitStringValue && "bitStringContents" in obj) {
var value;
if (obj.bitStringContents.length < 2) {
capture[v7.captureBitStringValue] = "";
} else {
var unused = obj.bitStringContents.charCodeAt(0);
if (unused !== 0) {
throw new Error(
"captureBitStringValue only supported for zero unused bits"
);
}
capture[v7.captureBitStringValue] = obj.bitStringContents.slice(1);
}
}
}
} else if (errors) {
errors.push(
"[" + v7.name + '] Expected constructed "' + v7.constructed + '", got "' + obj.constructed + '"'
);
}
} else if (errors) {
if (obj.tagClass !== v7.tagClass) {
errors.push(
"[" + v7.name + '] Expected tag class "' + v7.tagClass + '", got "' + obj.tagClass + '"'
);
}
if (obj.type !== v7.type) {
errors.push(
"[" + v7.name + '] Expected type "' + v7.type + '", got "' + obj.type + '"'
);
}
}
return rval;
};
var _nonLatinRegex = /[^\\u0000-\\u00ff]/;
asn1.prettyPrint = function(obj, level, indentation) {
var rval = "";
level = level || 0;
indentation = indentation || 2;
if (level > 0) {
rval += "\n";
}
var indent = "";
for (var i5 = 0; i5 < level * indentation; ++i5) {
indent += " ";
}
rval += indent + "Tag: ";
switch (obj.tagClass) {
case asn1.Class.UNIVERSAL:
rval += "Universal:";
break;
case asn1.Class.APPLICATION:
rval += "Application:";
break;
case asn1.Class.CONTEXT_SPECIFIC:
rval += "Context-Specific:";
break;
case asn1.Class.PRIVATE:
rval += "Private:";
break;
}
if (obj.tagClass === asn1.Class.UNIVERSAL) {
rval += obj.type;
switch (obj.type) {
case asn1.Type.NONE:
rval += " (None)";
break;
case asn1.Type.BOOLEAN:
rval += " (Boolean)";
break;
case asn1.Type.INTEGER:
rval += " (Integer)";
break;
case asn1.Type.BITSTRING:
rval += " (Bit string)";
break;
case asn1.Type.OCTETSTRING:
rval += " (Octet string)";
break;
case asn1.Type.NULL:
rval += " (Null)";
break;
case asn1.Type.OID:
rval += " (Object Identifier)";
break;
case asn1.Type.ODESC:
rval += " (Object Descriptor)";
break;
case asn1.Type.EXTERNAL:
rval += " (External or Instance of)";
break;
case asn1.Type.REAL:
rval += " (Real)";
break;
case asn1.Type.ENUMERATED:
rval += " (Enumerated)";
break;
case asn1.Type.EMBEDDED:
rval += " (Embedded PDV)";
break;
case asn1.Type.UTF8:
rval += " (UTF8)";
break;
case asn1.Type.ROID:
rval += " (Relative Object Identifier)";
break;
case asn1.Type.SEQUENCE:
rval += " (Sequence)";
break;
case asn1.Type.SET:
rval += " (Set)";
break;
case asn1.Type.PRINTABLESTRING:
rval += " (Printable String)";
break;
case asn1.Type.IA5String:
rval += " (IA5String (ASCII))";
break;
case asn1.Type.UTCTIME:
rval += " (UTC time)";
break;
case asn1.Type.GENERALIZEDTIME:
rval += " (Generalized time)";
break;
case asn1.Type.BMPSTRING:
rval += " (BMP String)";
break;
}
} else {
rval += obj.type;
}
rval += "\n";
rval += indent + "Constructed: " + obj.constructed + "\n";
if (obj.composed) {
var subvalues = 0;
var sub = "";
for (var i5 = 0; i5 < obj.value.length; ++i5) {
if (obj.value[i5] !== void 0) {
subvalues += 1;
sub += asn1.prettyPrint(obj.value[i5], level + 1, indentation);
if (i5 + 1 < obj.value.length) {
sub += ",";
}
}
}
rval += indent + "Sub values: " + subvalues + sub;
} else {
rval += indent + "Value: ";
if (obj.type === asn1.Type.OID) {
var oid = asn1.derToOid(obj.value);
rval += oid;
if (forge.pki && forge.pki.oids) {
if (oid in forge.pki.oids) {
rval += " (" + forge.pki.oids[oid] + ") ";
}
}
}
if (obj.type === asn1.Type.INTEGER) {
try {
rval += asn1.derToInteger(obj.value);
} catch (ex) {
rval += "0x" + forge.util.bytesToHex(obj.value);
}
} else if (obj.type === asn1.Type.BITSTRING) {
if (obj.value.length > 1) {
rval += "0x" + forge.util.bytesToHex(obj.value.slice(1));
} else {
rval += "(none)";
}
if (obj.value.length > 0) {
var unused = obj.value.charCodeAt(0);
if (unused == 1) {
rval += " (1 unused bit shown)";
} else if (unused > 1) {
rval += " (" + unused + " unused bits shown)";
}
}
} else if (obj.type === asn1.Type.OCTETSTRING) {
if (!_nonLatinRegex.test(obj.value)) {
rval += "(" + obj.value + ") ";
}
rval += "0x" + forge.util.bytesToHex(obj.value);
} else if (obj.type === asn1.Type.UTF8) {
try {
rval += forge.util.decodeUtf8(obj.value);
} catch (e7) {
if (e7.message === "URI malformed") {
rval += "0x" + forge.util.bytesToHex(obj.value) + " (malformed UTF8)";
} else {
throw e7;
}
}
} else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) {
rval += obj.value;
} else if (_nonLatinRegex.test(obj.value)) {
rval += "0x" + forge.util.bytesToHex(obj.value);
} else if (obj.value.length === 0) {
rval += "[null]";
} else {
rval += obj.value;
}
}
return rval;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md.js
var require_md = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
module3.exports = forge.md = forge.md || {};
forge.md.algorithms = forge.md.algorithms || {};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/hmac.js
var require_hmac = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/hmac.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_md();
require_util10();
var hmac2 = module3.exports = forge.hmac = forge.hmac || {};
hmac2.create = function() {
var _key = null;
var _md = null;
var _ipadding = null;
var _opadding = null;
var ctx = {};
ctx.start = function(md, key) {
if (md !== null) {
if (typeof md === "string") {
md = md.toLowerCase();
if (md in forge.md.algorithms) {
_md = forge.md.algorithms[md].create();
} else {
throw new Error('Unknown hash algorithm "' + md + '"');
}
} else {
_md = md;
}
}
if (key === null) {
key = _key;
} else {
if (typeof key === "string") {
key = forge.util.createBuffer(key);
} else if (forge.util.isArray(key)) {
var tmp = key;
key = forge.util.createBuffer();
for (var i5 = 0; i5 < tmp.length; ++i5) {
key.putByte(tmp[i5]);
}
}
var keylen = key.length();
if (keylen > _md.blockLength) {
_md.start();
_md.update(key.bytes());
key = _md.digest();
}
_ipadding = forge.util.createBuffer();
_opadding = forge.util.createBuffer();
keylen = key.length();
for (var i5 = 0; i5 < keylen; ++i5) {
var tmp = key.at(i5);
_ipadding.putByte(54 ^ tmp);
_opadding.putByte(92 ^ tmp);
}
if (keylen < _md.blockLength) {
var tmp = _md.blockLength - keylen;
for (var i5 = 0; i5 < tmp; ++i5) {
_ipadding.putByte(54);
_opadding.putByte(92);
}
}
_key = key;
_ipadding = _ipadding.bytes();
_opadding = _opadding.bytes();
}
_md.start();
_md.update(_ipadding);
};
ctx.update = function(bytes) {
_md.update(bytes);
};
ctx.getMac = function() {
var inner = _md.digest().bytes();
_md.start();
_md.update(_opadding);
_md.update(inner);
return _md.digest();
};
ctx.digest = ctx.getMac;
return ctx;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md5.js
var require_md5 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md5.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_md();
require_util10();
var md5 = module3.exports = forge.md5 = forge.md5 || {};
forge.md.md5 = forge.md.algorithms.md5 = md5;
md5.create = function() {
if (!_initialized) {
_init();
}
var _state = null;
var _input = forge.util.createBuffer();
var _w2 = new Array(16);
var md = {
algorithm: "md5",
blockLength: 64,
digestLength: 16,
// 56-bit length of message so far (does not including padding)
messageLength: 0,
// true message length
fullMessageLength: null,
// size of message length in bytes
messageLengthSize: 8
};
md.start = function() {
md.messageLength = 0;
md.fullMessageLength = md.messageLength64 = [];
var int32s = md.messageLengthSize / 4;
for (var i5 = 0; i5 < int32s; ++i5) {
md.fullMessageLength.push(0);
}
_input = forge.util.createBuffer();
_state = {
h0: 1732584193,
h1: 4023233417,
h2: 2562383102,
h3: 271733878
};
return md;
};
md.start();
md.update = function(msg, encoding) {
if (encoding === "utf8") {
msg = forge.util.encodeUtf8(msg);
}
var len = msg.length;
md.messageLength += len;
len = [len / 4294967296 >>> 0, len >>> 0];
for (var i5 = md.fullMessageLength.length - 1; i5 >= 0; --i5) {
md.fullMessageLength[i5] += len[1];
len[1] = len[0] + (md.fullMessageLength[i5] / 4294967296 >>> 0);
md.fullMessageLength[i5] = md.fullMessageLength[i5] >>> 0;
len[0] = len[1] / 4294967296 >>> 0;
}
_input.putBytes(msg);
_update(_state, _w2, _input);
if (_input.read > 2048 || _input.length() === 0) {
_input.compact();
}
return md;
};
md.digest = function() {
var finalBlock = forge.util.createBuffer();
finalBlock.putBytes(_input.bytes());
var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
var overflow = remaining & md.blockLength - 1;
finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
var bits, carry = 0;
for (var i5 = md.fullMessageLength.length - 1; i5 >= 0; --i5) {
bits = md.fullMessageLength[i5] * 8 + carry;
carry = bits / 4294967296 >>> 0;
finalBlock.putInt32Le(bits >>> 0);
}
var s22 = {
h0: _state.h0,
h1: _state.h1,
h2: _state.h2,
h3: _state.h3
};
_update(s22, _w2, finalBlock);
var rval = forge.util.createBuffer();
rval.putInt32Le(s22.h0);
rval.putInt32Le(s22.h1);
rval.putInt32Le(s22.h2);
rval.putInt32Le(s22.h3);
return rval;
};
return md;
};
var _padding = null;
var _g = null;
var _r2 = null;
var _k = null;
var _initialized = false;
function _init() {
_padding = String.fromCharCode(128);
_padding += forge.util.fillString(String.fromCharCode(0), 64);
_g = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
1,
6,
11,
0,
5,
10,
15,
4,
9,
14,
3,
8,
13,
2,
7,
12,
5,
8,
11,
14,
1,
4,
7,
10,
13,
0,
3,
6,
9,
12,
15,
2,
0,
7,
14,
5,
12,
3,
10,
1,
8,
15,
6,
13,
4,
11,
2,
9
];
_r2 = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21
];
_k = new Array(64);
for (var i5 = 0; i5 < 64; ++i5) {
_k[i5] = Math.floor(Math.abs(Math.sin(i5 + 1)) * 4294967296);
}
_initialized = true;
}
__name(_init, "_init");
function _update(s5, w6, bytes) {
var t7, a5, b6, c6, d6, f6, r7, i5;
var len = bytes.length();
while (len >= 64) {
a5 = s5.h0;
b6 = s5.h1;
c6 = s5.h2;
d6 = s5.h3;
for (i5 = 0; i5 < 16; ++i5) {
w6[i5] = bytes.getInt32Le();
f6 = d6 ^ b6 & (c6 ^ d6);
t7 = a5 + f6 + _k[i5] + w6[i5];
r7 = _r2[i5];
a5 = d6;
d6 = c6;
c6 = b6;
b6 += t7 << r7 | t7 >>> 32 - r7;
}
for (; i5 < 32; ++i5) {
f6 = c6 ^ d6 & (b6 ^ c6);
t7 = a5 + f6 + _k[i5] + w6[_g[i5]];
r7 = _r2[i5];
a5 = d6;
d6 = c6;
c6 = b6;
b6 += t7 << r7 | t7 >>> 32 - r7;
}
for (; i5 < 48; ++i5) {
f6 = b6 ^ c6 ^ d6;
t7 = a5 + f6 + _k[i5] + w6[_g[i5]];
r7 = _r2[i5];
a5 = d6;
d6 = c6;
c6 = b6;
b6 += t7 << r7 | t7 >>> 32 - r7;
}
for (; i5 < 64; ++i5) {
f6 = c6 ^ (b6 | ~d6);
t7 = a5 + f6 + _k[i5] + w6[_g[i5]];
r7 = _r2[i5];
a5 = d6;
d6 = c6;
c6 = b6;
b6 += t7 << r7 | t7 >>> 32 - r7;
}
s5.h0 = s5.h0 + a5 | 0;
s5.h1 = s5.h1 + b6 | 0;
s5.h2 = s5.h2 + c6 | 0;
s5.h3 = s5.h3 + d6 | 0;
len -= 64;
}
}
__name(_update, "_update");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pem.js
var require_pem = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pem.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
var pem = module3.exports = forge.pem = forge.pem || {};
pem.encode = function(msg, options) {
options = options || {};
var rval = "-----BEGIN " + msg.type + "-----\r\n";
var header;
if (msg.procType) {
header = {
name: "Proc-Type",
values: [String(msg.procType.version), msg.procType.type]
};
rval += foldHeader(header);
}
if (msg.contentDomain) {
header = { name: "Content-Domain", values: [msg.contentDomain] };
rval += foldHeader(header);
}
if (msg.dekInfo) {
header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] };
if (msg.dekInfo.parameters) {
header.values.push(msg.dekInfo.parameters);
}
rval += foldHeader(header);
}
if (msg.headers) {
for (var i5 = 0; i5 < msg.headers.length; ++i5) {
rval += foldHeader(msg.headers[i5]);
}
}
if (msg.procType) {
rval += "\r\n";
}
rval += forge.util.encode64(msg.body, options.maxline || 64) + "\r\n";
rval += "-----END " + msg.type + "-----\r\n";
return rval;
};
pem.decode = function(str) {
var rval = [];
var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;
var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;
var rCRLF = /\r?\n/;
var match2;
while (true) {
match2 = rMessage.exec(str);
if (!match2) {
break;
}
var type = match2[1];
if (type === "NEW CERTIFICATE REQUEST") {
type = "CERTIFICATE REQUEST";
}
var msg = {
type,
procType: null,
contentDomain: null,
dekInfo: null,
headers: [],
body: forge.util.decode64(match2[3])
};
rval.push(msg);
if (!match2[2]) {
continue;
}
var lines = match2[2].split(rCRLF);
var li = 0;
while (match2 && li < lines.length) {
var line = lines[li].replace(/\s+$/, "");
for (var nl = li + 1; nl < lines.length; ++nl) {
var next = lines[nl];
if (!/\s/.test(next[0])) {
break;
}
line += next;
li = nl;
}
match2 = line.match(rHeader);
if (match2) {
var header = { name: match2[1], values: [] };
var values = match2[2].split(",");
for (var vi = 0; vi < values.length; ++vi) {
header.values.push(ltrim(values[vi]));
}
if (!msg.procType) {
if (header.name !== "Proc-Type") {
throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');
} else if (header.values.length !== 2) {
throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');
}
msg.procType = { version: values[0], type: values[1] };
} else if (!msg.contentDomain && header.name === "Content-Domain") {
msg.contentDomain = values[0] || "";
} else if (!msg.dekInfo && header.name === "DEK-Info") {
if (header.values.length === 0) {
throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');
}
msg.dekInfo = { algorithm: values[0], parameters: values[1] || null };
} else {
msg.headers.push(header);
}
}
++li;
}
if (msg.procType === "ENCRYPTED" && !msg.dekInfo) {
throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".');
}
}
if (rval.length === 0) {
throw new Error("Invalid PEM formatted message.");
}
return rval;
};
function foldHeader(header) {
var rval = header.name + ": ";
var values = [];
var insertSpace = /* @__PURE__ */ __name(function(match2, $1) {
return " " + $1;
}, "insertSpace");
for (var i5 = 0; i5 < header.values.length; ++i5) {
values.push(header.values[i5].replace(/^(\S+\r\n)/, insertSpace));
}
rval += values.join(",") + "\r\n";
var length = 0;
var candidate = -1;
for (var i5 = 0; i5 < rval.length; ++i5, ++length) {
if (length > 65 && candidate !== -1) {
var insert = rval[candidate];
if (insert === ",") {
++candidate;
rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate);
} else {
rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1);
}
length = i5 - candidate - 1;
candidate = -1;
++i5;
} else if (rval[i5] === " " || rval[i5] === " " || rval[i5] === ",") {
candidate = i5;
}
}
return rval;
}
__name(foldHeader, "foldHeader");
function ltrim(str) {
return str.replace(/^\s+/, "");
}
__name(ltrim, "ltrim");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/des.js
var require_des = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/des.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_cipher();
require_cipherModes();
require_util10();
module3.exports = forge.des = forge.des || {};
forge.des.startEncrypting = function(key, iv, output, mode) {
var cipher = _createCipher({
key,
output,
decrypt: false,
mode: mode || (iv === null ? "ECB" : "CBC")
});
cipher.start(iv);
return cipher;
};
forge.des.createEncryptionCipher = function(key, mode) {
return _createCipher({
key,
output: null,
decrypt: false,
mode
});
};
forge.des.startDecrypting = function(key, iv, output, mode) {
var cipher = _createCipher({
key,
output,
decrypt: true,
mode: mode || (iv === null ? "ECB" : "CBC")
});
cipher.start(iv);
return cipher;
};
forge.des.createDecryptionCipher = function(key, mode) {
return _createCipher({
key,
output: null,
decrypt: true,
mode
});
};
forge.des.Algorithm = function(name2, mode) {
var self2 = this;
self2.name = name2;
self2.mode = new mode({
blockSize: 8,
cipher: {
encrypt: /* @__PURE__ */ __name(function(inBlock, outBlock) {
return _updateBlock(self2._keys, inBlock, outBlock, false);
}, "encrypt"),
decrypt: /* @__PURE__ */ __name(function(inBlock, outBlock) {
return _updateBlock(self2._keys, inBlock, outBlock, true);
}, "decrypt")
}
});
self2._init = false;
};
forge.des.Algorithm.prototype.initialize = function(options) {
if (this._init) {
return;
}
var key = forge.util.createBuffer(options.key);
if (this.name.indexOf("3DES") === 0) {
if (key.length() !== 24) {
throw new Error("Invalid Triple-DES key size: " + key.length() * 8);
}
}
this._keys = _createKeys(key);
this._init = true;
};
registerAlgorithm("DES-ECB", forge.cipher.modes.ecb);
registerAlgorithm("DES-CBC", forge.cipher.modes.cbc);
registerAlgorithm("DES-CFB", forge.cipher.modes.cfb);
registerAlgorithm("DES-OFB", forge.cipher.modes.ofb);
registerAlgorithm("DES-CTR", forge.cipher.modes.ctr);
registerAlgorithm("3DES-ECB", forge.cipher.modes.ecb);
registerAlgorithm("3DES-CBC", forge.cipher.modes.cbc);
registerAlgorithm("3DES-CFB", forge.cipher.modes.cfb);
registerAlgorithm("3DES-OFB", forge.cipher.modes.ofb);
registerAlgorithm("3DES-CTR", forge.cipher.modes.ctr);
function registerAlgorithm(name2, mode) {
var factory = /* @__PURE__ */ __name(function() {
return new forge.des.Algorithm(name2, mode);
}, "factory");
forge.cipher.registerAlgorithm(name2, factory);
}
__name(registerAlgorithm, "registerAlgorithm");
var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756];
var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344];
var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584];
var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928];
var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080];
var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312];
var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154];
var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696];
function _createKeys(key) {
var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261];
var iterations = key.length() > 8 ? 3 : 1;
var keys = [];
var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
var n6 = 0, tmp;
for (var j6 = 0; j6 < iterations; j6++) {
var left2 = key.getInt32();
var right2 = key.getInt32();
tmp = (left2 >>> 4 ^ right2) & 252645135;
right2 ^= tmp;
left2 ^= tmp << 4;
tmp = (right2 >>> -16 ^ left2) & 65535;
left2 ^= tmp;
right2 ^= tmp << -16;
tmp = (left2 >>> 2 ^ right2) & 858993459;
right2 ^= tmp;
left2 ^= tmp << 2;
tmp = (right2 >>> -16 ^ left2) & 65535;
left2 ^= tmp;
right2 ^= tmp << -16;
tmp = (left2 >>> 1 ^ right2) & 1431655765;
right2 ^= tmp;
left2 ^= tmp << 1;
tmp = (right2 >>> 8 ^ left2) & 16711935;
left2 ^= tmp;
right2 ^= tmp << 8;
tmp = (left2 >>> 1 ^ right2) & 1431655765;
right2 ^= tmp;
left2 ^= tmp << 1;
tmp = left2 << 8 | right2 >>> 20 & 240;
left2 = right2 << 24 | right2 << 8 & 16711680 | right2 >>> 8 & 65280 | right2 >>> 24 & 240;
right2 = tmp;
for (var i5 = 0; i5 < shifts.length; ++i5) {
if (shifts[i5]) {
left2 = left2 << 2 | left2 >>> 26;
right2 = right2 << 2 | right2 >>> 26;
} else {
left2 = left2 << 1 | left2 >>> 27;
right2 = right2 << 1 | right2 >>> 27;
}
left2 &= -15;
right2 &= -15;
var lefttmp = pc2bytes0[left2 >>> 28] | pc2bytes1[left2 >>> 24 & 15] | pc2bytes2[left2 >>> 20 & 15] | pc2bytes3[left2 >>> 16 & 15] | pc2bytes4[left2 >>> 12 & 15] | pc2bytes5[left2 >>> 8 & 15] | pc2bytes6[left2 >>> 4 & 15];
var righttmp = pc2bytes7[right2 >>> 28] | pc2bytes8[right2 >>> 24 & 15] | pc2bytes9[right2 >>> 20 & 15] | pc2bytes10[right2 >>> 16 & 15] | pc2bytes11[right2 >>> 12 & 15] | pc2bytes12[right2 >>> 8 & 15] | pc2bytes13[right2 >>> 4 & 15];
tmp = (righttmp >>> 16 ^ lefttmp) & 65535;
keys[n6++] = lefttmp ^ tmp;
keys[n6++] = righttmp ^ tmp << 16;
}
}
return keys;
}
__name(_createKeys, "_createKeys");
function _updateBlock(keys, input, output, decrypt) {
var iterations = keys.length === 32 ? 3 : 9;
var looping;
if (iterations === 3) {
looping = decrypt ? [30, -2, -2] : [0, 32, 2];
} else {
looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2];
}
var tmp;
var left2 = input[0];
var right2 = input[1];
tmp = (left2 >>> 4 ^ right2) & 252645135;
right2 ^= tmp;
left2 ^= tmp << 4;
tmp = (left2 >>> 16 ^ right2) & 65535;
right2 ^= tmp;
left2 ^= tmp << 16;
tmp = (right2 >>> 2 ^ left2) & 858993459;
left2 ^= tmp;
right2 ^= tmp << 2;
tmp = (right2 >>> 8 ^ left2) & 16711935;
left2 ^= tmp;
right2 ^= tmp << 8;
tmp = (left2 >>> 1 ^ right2) & 1431655765;
right2 ^= tmp;
left2 ^= tmp << 1;
left2 = left2 << 1 | left2 >>> 31;
right2 = right2 << 1 | right2 >>> 31;
for (var j6 = 0; j6 < iterations; j6 += 3) {
var endloop = looping[j6 + 1];
var loopinc = looping[j6 + 2];
for (var i5 = looping[j6]; i5 != endloop; i5 += loopinc) {
var right1 = right2 ^ keys[i5];
var right22 = (right2 >>> 4 | right2 << 28) ^ keys[i5 + 1];
tmp = left2;
left2 = right2;
right2 = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right22 >>> 24 & 63] | spfunction3[right22 >>> 16 & 63] | spfunction5[right22 >>> 8 & 63] | spfunction7[right22 & 63]);
}
tmp = left2;
left2 = right2;
right2 = tmp;
}
left2 = left2 >>> 1 | left2 << 31;
right2 = right2 >>> 1 | right2 << 31;
tmp = (left2 >>> 1 ^ right2) & 1431655765;
right2 ^= tmp;
left2 ^= tmp << 1;
tmp = (right2 >>> 8 ^ left2) & 16711935;
left2 ^= tmp;
right2 ^= tmp << 8;
tmp = (right2 >>> 2 ^ left2) & 858993459;
left2 ^= tmp;
right2 ^= tmp << 2;
tmp = (left2 >>> 16 ^ right2) & 65535;
right2 ^= tmp;
left2 ^= tmp << 16;
tmp = (left2 >>> 4 ^ right2) & 252645135;
right2 ^= tmp;
left2 ^= tmp << 4;
output[0] = left2;
output[1] = right2;
}
__name(_updateBlock, "_updateBlock");
function _createCipher(options) {
options = options || {};
var mode = (options.mode || "CBC").toUpperCase();
var algorithm = "DES-" + mode;
var cipher;
if (options.decrypt) {
cipher = forge.cipher.createDecipher(algorithm, options.key);
} else {
cipher = forge.cipher.createCipher(algorithm, options.key);
}
var start = cipher.start;
cipher.start = function(iv, options2) {
var output = null;
if (options2 instanceof forge.util.ByteBuffer) {
output = options2;
options2 = {};
}
options2 = options2 || {};
options2.output = output;
options2.iv = iv;
start.call(cipher, options2);
};
return cipher;
}
__name(_createCipher, "_createCipher");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pbkdf2.js
var require_pbkdf2 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pbkdf2.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_hmac();
require_md();
require_util10();
var pkcs5 = forge.pkcs5 = forge.pkcs5 || {};
var crypto8;
if (forge.util.isNodejs && !forge.options.usePureJavaScript) {
crypto8 = require("crypto");
}
module3.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(p6, s5, c6, dkLen, md, callback) {
if (typeof md === "function") {
callback = md;
md = null;
}
if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto8.pbkdf2 && (md === null || typeof md !== "object") && (crypto8.pbkdf2Sync.length > 4 || (!md || md === "sha1"))) {
if (typeof md !== "string") {
md = "sha1";
}
p6 = Buffer.from(p6, "binary");
s5 = Buffer.from(s5, "binary");
if (!callback) {
if (crypto8.pbkdf2Sync.length === 4) {
return crypto8.pbkdf2Sync(p6, s5, c6, dkLen).toString("binary");
}
return crypto8.pbkdf2Sync(p6, s5, c6, dkLen, md).toString("binary");
}
if (crypto8.pbkdf2Sync.length === 4) {
return crypto8.pbkdf2(p6, s5, c6, dkLen, function(err2, key) {
if (err2) {
return callback(err2);
}
callback(null, key.toString("binary"));
});
}
return crypto8.pbkdf2(p6, s5, c6, dkLen, md, function(err2, key) {
if (err2) {
return callback(err2);
}
callback(null, key.toString("binary"));
});
}
if (typeof md === "undefined" || md === null) {
md = "sha1";
}
if (typeof md === "string") {
if (!(md in forge.md.algorithms)) {
throw new Error("Unknown hash algorithm: " + md);
}
md = forge.md[md].create();
}
var hLen = md.digestLength;
if (dkLen > 4294967295 * hLen) {
var err = new Error("Derived key is too long.");
if (callback) {
return callback(err);
}
throw err;
}
var len = Math.ceil(dkLen / hLen);
var r7 = dkLen - (len - 1) * hLen;
var prf = forge.hmac.create();
prf.start(md, p6);
var dk = "";
var xor, u_c, u_c1;
if (!callback) {
for (var i5 = 1; i5 <= len; ++i5) {
prf.start(null, null);
prf.update(s5);
prf.update(forge.util.int32ToBytes(i5));
xor = u_c1 = prf.digest().getBytes();
for (var j6 = 2; j6 <= c6; ++j6) {
prf.start(null, null);
prf.update(u_c1);
u_c = prf.digest().getBytes();
xor = forge.util.xorBytes(xor, u_c, hLen);
u_c1 = u_c;
}
dk += i5 < len ? xor : xor.substr(0, r7);
}
return dk;
}
var i5 = 1, j6;
function outer() {
if (i5 > len) {
return callback(null, dk);
}
prf.start(null, null);
prf.update(s5);
prf.update(forge.util.int32ToBytes(i5));
xor = u_c1 = prf.digest().getBytes();
j6 = 2;
inner();
}
__name(outer, "outer");
function inner() {
if (j6 <= c6) {
prf.start(null, null);
prf.update(u_c1);
u_c = prf.digest().getBytes();
xor = forge.util.xorBytes(xor, u_c, hLen);
u_c1 = u_c;
++j6;
return forge.util.setImmediate(inner);
}
dk += i5 < len ? xor : xor.substr(0, r7);
++i5;
outer();
}
__name(inner, "inner");
outer();
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha256.js
var require_sha256 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha256.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_md();
require_util10();
var sha256 = module3.exports = forge.sha256 = forge.sha256 || {};
forge.md.sha256 = forge.md.algorithms.sha256 = sha256;
sha256.create = function() {
if (!_initialized) {
_init();
}
var _state = null;
var _input = forge.util.createBuffer();
var _w2 = new Array(64);
var md = {
algorithm: "sha256",
blockLength: 64,
digestLength: 32,
// 56-bit length of message so far (does not including padding)
messageLength: 0,
// true message length
fullMessageLength: null,
// size of message length in bytes
messageLengthSize: 8
};
md.start = function() {
md.messageLength = 0;
md.fullMessageLength = md.messageLength64 = [];
var int32s = md.messageLengthSize / 4;
for (var i5 = 0; i5 < int32s; ++i5) {
md.fullMessageLength.push(0);
}
_input = forge.util.createBuffer();
_state = {
h0: 1779033703,
h1: 3144134277,
h2: 1013904242,
h3: 2773480762,
h4: 1359893119,
h5: 2600822924,
h6: 528734635,
h7: 1541459225
};
return md;
};
md.start();
md.update = function(msg, encoding) {
if (encoding === "utf8") {
msg = forge.util.encodeUtf8(msg);
}
var len = msg.length;
md.messageLength += len;
len = [len / 4294967296 >>> 0, len >>> 0];
for (var i5 = md.fullMessageLength.length - 1; i5 >= 0; --i5) {
md.fullMessageLength[i5] += len[1];
len[1] = len[0] + (md.fullMessageLength[i5] / 4294967296 >>> 0);
md.fullMessageLength[i5] = md.fullMessageLength[i5] >>> 0;
len[0] = len[1] / 4294967296 >>> 0;
}
_input.putBytes(msg);
_update(_state, _w2, _input);
if (_input.read > 2048 || _input.length() === 0) {
_input.compact();
}
return md;
};
md.digest = function() {
var finalBlock = forge.util.createBuffer();
finalBlock.putBytes(_input.bytes());
var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
var overflow = remaining & md.blockLength - 1;
finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
var next, carry;
var bits = md.fullMessageLength[0] * 8;
for (var i5 = 0; i5 < md.fullMessageLength.length - 1; ++i5) {
next = md.fullMessageLength[i5 + 1] * 8;
carry = next / 4294967296 >>> 0;
bits += carry;
finalBlock.putInt32(bits >>> 0);
bits = next >>> 0;
}
finalBlock.putInt32(bits);
var s22 = {
h0: _state.h0,
h1: _state.h1,
h2: _state.h2,
h3: _state.h3,
h4: _state.h4,
h5: _state.h5,
h6: _state.h6,
h7: _state.h7
};
_update(s22, _w2, finalBlock);
var rval = forge.util.createBuffer();
rval.putInt32(s22.h0);
rval.putInt32(s22.h1);
rval.putInt32(s22.h2);
rval.putInt32(s22.h3);
rval.putInt32(s22.h4);
rval.putInt32(s22.h5);
rval.putInt32(s22.h6);
rval.putInt32(s22.h7);
return rval;
};
return md;
};
var _padding = null;
var _initialized = false;
var _k = null;
function _init() {
_padding = String.fromCharCode(128);
_padding += forge.util.fillString(String.fromCharCode(0), 64);
_k = [
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
];
_initialized = true;
}
__name(_init, "_init");
function _update(s5, w6, bytes) {
var t1, t22, s0, s1, ch2, maj, i5, a5, b6, c6, d6, e7, f6, g6, h6;
var len = bytes.length();
while (len >= 64) {
for (i5 = 0; i5 < 16; ++i5) {
w6[i5] = bytes.getInt32();
}
for (; i5 < 64; ++i5) {
t1 = w6[i5 - 2];
t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;
t22 = w6[i5 - 15];
t22 = (t22 >>> 7 | t22 << 25) ^ (t22 >>> 18 | t22 << 14) ^ t22 >>> 3;
w6[i5] = t1 + w6[i5 - 7] + t22 + w6[i5 - 16] | 0;
}
a5 = s5.h0;
b6 = s5.h1;
c6 = s5.h2;
d6 = s5.h3;
e7 = s5.h4;
f6 = s5.h5;
g6 = s5.h6;
h6 = s5.h7;
for (i5 = 0; i5 < 64; ++i5) {
s1 = (e7 >>> 6 | e7 << 26) ^ (e7 >>> 11 | e7 << 21) ^ (e7 >>> 25 | e7 << 7);
ch2 = g6 ^ e7 & (f6 ^ g6);
s0 = (a5 >>> 2 | a5 << 30) ^ (a5 >>> 13 | a5 << 19) ^ (a5 >>> 22 | a5 << 10);
maj = a5 & b6 | c6 & (a5 ^ b6);
t1 = h6 + s1 + ch2 + _k[i5] + w6[i5];
t22 = s0 + maj;
h6 = g6;
g6 = f6;
f6 = e7;
e7 = d6 + t1 >>> 0;
d6 = c6;
c6 = b6;
b6 = a5;
a5 = t1 + t22 >>> 0;
}
s5.h0 = s5.h0 + a5 | 0;
s5.h1 = s5.h1 + b6 | 0;
s5.h2 = s5.h2 + c6 | 0;
s5.h3 = s5.h3 + d6 | 0;
s5.h4 = s5.h4 + e7 | 0;
s5.h5 = s5.h5 + f6 | 0;
s5.h6 = s5.h6 + g6 | 0;
s5.h7 = s5.h7 + h6 | 0;
len -= 64;
}
}
__name(_update, "_update");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/prng.js
var require_prng = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/prng.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
var _crypto = null;
if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) {
_crypto = require("crypto");
}
var prng = module3.exports = forge.prng = forge.prng || {};
prng.create = function(plugin) {
var ctx = {
plugin,
key: null,
seed: null,
time: null,
// number of reseeds so far
reseeds: 0,
// amount of data generated so far
generated: 0,
// no initial key bytes
keyBytes: ""
};
var md = plugin.md;
var pools = new Array(32);
for (var i5 = 0; i5 < 32; ++i5) {
pools[i5] = md.create();
}
ctx.pools = pools;
ctx.pool = 0;
ctx.generate = function(count, callback) {
if (!callback) {
return ctx.generateSync(count);
}
var cipher = ctx.plugin.cipher;
var increment2 = ctx.plugin.increment;
var formatKey = ctx.plugin.formatKey;
var formatSeed = ctx.plugin.formatSeed;
var b6 = forge.util.createBuffer();
ctx.key = null;
generate2();
function generate2(err) {
if (err) {
return callback(err);
}
if (b6.length() >= count) {
return callback(null, b6.getBytes(count));
}
if (ctx.generated > 1048575) {
ctx.key = null;
}
if (ctx.key === null) {
return forge.util.nextTick(function() {
_reseed(generate2);
});
}
var bytes = cipher(ctx.key, ctx.seed);
ctx.generated += bytes.length;
b6.putBytes(bytes);
ctx.key = formatKey(cipher(ctx.key, increment2(ctx.seed)));
ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
forge.util.setImmediate(generate2);
}
__name(generate2, "generate");
};
ctx.generateSync = function(count) {
var cipher = ctx.plugin.cipher;
var increment2 = ctx.plugin.increment;
var formatKey = ctx.plugin.formatKey;
var formatSeed = ctx.plugin.formatSeed;
ctx.key = null;
var b6 = forge.util.createBuffer();
while (b6.length() < count) {
if (ctx.generated > 1048575) {
ctx.key = null;
}
if (ctx.key === null) {
_reseedSync();
}
var bytes = cipher(ctx.key, ctx.seed);
ctx.generated += bytes.length;
b6.putBytes(bytes);
ctx.key = formatKey(cipher(ctx.key, increment2(ctx.seed)));
ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
}
return b6.getBytes(count);
};
function _reseed(callback) {
if (ctx.pools[0].messageLength >= 32) {
_seed();
return callback();
}
var needed = 32 - ctx.pools[0].messageLength << 5;
ctx.seedFile(needed, function(err, bytes) {
if (err) {
return callback(err);
}
ctx.collect(bytes);
_seed();
callback();
});
}
__name(_reseed, "_reseed");
function _reseedSync() {
if (ctx.pools[0].messageLength >= 32) {
return _seed();
}
var needed = 32 - ctx.pools[0].messageLength << 5;
ctx.collect(ctx.seedFileSync(needed));
_seed();
}
__name(_reseedSync, "_reseedSync");
function _seed() {
ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1;
var md2 = ctx.plugin.md.create();
md2.update(ctx.keyBytes);
var _2powK = 1;
for (var k6 = 0; k6 < 32; ++k6) {
if (ctx.reseeds % _2powK === 0) {
md2.update(ctx.pools[k6].digest().getBytes());
ctx.pools[k6].start();
}
_2powK = _2powK << 1;
}
ctx.keyBytes = md2.digest().getBytes();
md2.start();
md2.update(ctx.keyBytes);
var seedBytes = md2.digest().getBytes();
ctx.key = ctx.plugin.formatKey(ctx.keyBytes);
ctx.seed = ctx.plugin.formatSeed(seedBytes);
ctx.generated = 0;
}
__name(_seed, "_seed");
function defaultSeedFile(needed) {
var getRandomValues = null;
var globalScope = forge.util.globalScope;
var _crypto2 = globalScope.crypto || globalScope.msCrypto;
if (_crypto2 && _crypto2.getRandomValues) {
getRandomValues = /* @__PURE__ */ __name(function(arr) {
return _crypto2.getRandomValues(arr);
}, "getRandomValues");
}
var b6 = forge.util.createBuffer();
if (getRandomValues) {
while (b6.length() < needed) {
var count = Math.max(1, Math.min(needed - b6.length(), 65536) / 4);
var entropy = new Uint32Array(Math.floor(count));
try {
getRandomValues(entropy);
for (var i6 = 0; i6 < entropy.length; ++i6) {
b6.putInt32(entropy[i6]);
}
} catch (e7) {
if (!(typeof QuotaExceededError !== "undefined" && e7 instanceof QuotaExceededError)) {
throw e7;
}
}
}
}
if (b6.length() < needed) {
var hi, lo, next;
var seed = Math.floor(Math.random() * 65536);
while (b6.length() < needed) {
lo = 16807 * (seed & 65535);
hi = 16807 * (seed >> 16);
lo += (hi & 32767) << 16;
lo += hi >> 15;
lo = (lo & 2147483647) + (lo >> 31);
seed = lo & 4294967295;
for (var i6 = 0; i6 < 3; ++i6) {
next = seed >>> (i6 << 3);
next ^= Math.floor(Math.random() * 256);
b6.putByte(next & 255);
}
}
}
return b6.getBytes(needed);
}
__name(defaultSeedFile, "defaultSeedFile");
if (_crypto) {
ctx.seedFile = function(needed, callback) {
_crypto.randomBytes(needed, function(err, bytes) {
if (err) {
return callback(err);
}
callback(null, bytes.toString());
});
};
ctx.seedFileSync = function(needed) {
return _crypto.randomBytes(needed).toString();
};
} else {
ctx.seedFile = function(needed, callback) {
try {
callback(null, defaultSeedFile(needed));
} catch (e7) {
callback(e7);
}
};
ctx.seedFileSync = defaultSeedFile;
}
ctx.collect = function(bytes) {
var count = bytes.length;
for (var i6 = 0; i6 < count; ++i6) {
ctx.pools[ctx.pool].update(bytes.substr(i6, 1));
ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1;
}
};
ctx.collectInt = function(i6, n6) {
var bytes = "";
for (var x6 = 0; x6 < n6; x6 += 8) {
bytes += String.fromCharCode(i6 >> x6 & 255);
}
ctx.collect(bytes);
};
ctx.registerWorker = function(worker) {
if (worker === self) {
ctx.seedFile = function(needed, callback) {
function listener2(e7) {
var data = e7.data;
if (data.forge && data.forge.prng) {
self.removeEventListener("message", listener2);
callback(data.forge.prng.err, data.forge.prng.bytes);
}
}
__name(listener2, "listener");
self.addEventListener("message", listener2);
self.postMessage({ forge: { prng: { needed } } });
};
} else {
var listener = /* @__PURE__ */ __name(function(e7) {
var data = e7.data;
if (data.forge && data.forge.prng) {
ctx.seedFile(data.forge.prng.needed, function(err, bytes) {
worker.postMessage({ forge: { prng: { err, bytes } } });
});
}
}, "listener");
worker.addEventListener("message", listener);
}
};
return ctx;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/random.js
var require_random2 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/random.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_aes();
require_sha256();
require_prng();
require_util10();
(function() {
if (forge.random && forge.random.getBytes) {
module3.exports = forge.random;
return;
}
(function(jQuery2) {
var prng_aes = {};
var _prng_aes_output = new Array(4);
var _prng_aes_buffer = forge.util.createBuffer();
prng_aes.formatKey = function(key2) {
var tmp = forge.util.createBuffer(key2);
key2 = new Array(4);
key2[0] = tmp.getInt32();
key2[1] = tmp.getInt32();
key2[2] = tmp.getInt32();
key2[3] = tmp.getInt32();
return forge.aes._expandKey(key2, false);
};
prng_aes.formatSeed = function(seed) {
var tmp = forge.util.createBuffer(seed);
seed = new Array(4);
seed[0] = tmp.getInt32();
seed[1] = tmp.getInt32();
seed[2] = tmp.getInt32();
seed[3] = tmp.getInt32();
return seed;
};
prng_aes.cipher = function(key2, seed) {
forge.aes._updateBlock(key2, seed, _prng_aes_output, false);
_prng_aes_buffer.putInt32(_prng_aes_output[0]);
_prng_aes_buffer.putInt32(_prng_aes_output[1]);
_prng_aes_buffer.putInt32(_prng_aes_output[2]);
_prng_aes_buffer.putInt32(_prng_aes_output[3]);
return _prng_aes_buffer.getBytes();
};
prng_aes.increment = function(seed) {
++seed[3];
return seed;
};
prng_aes.md = forge.md.sha256;
function spawnPrng() {
var ctx = forge.prng.create(prng_aes);
ctx.getBytes = function(count, callback) {
return ctx.generate(count, callback);
};
ctx.getBytesSync = function(count) {
return ctx.generate(count);
};
return ctx;
}
__name(spawnPrng, "spawnPrng");
var _ctx = spawnPrng();
var getRandomValues = null;
var globalScope = forge.util.globalScope;
var _crypto = globalScope.crypto || globalScope.msCrypto;
if (_crypto && _crypto.getRandomValues) {
getRandomValues = /* @__PURE__ */ __name(function(arr) {
return _crypto.getRandomValues(arr);
}, "getRandomValues");
}
if (forge.options.usePureJavaScript || !forge.util.isNodejs && !getRandomValues) {
if (typeof window === "undefined" || window.document === void 0) {
}
_ctx.collectInt(+/* @__PURE__ */ new Date(), 32);
if (typeof navigator !== "undefined") {
var _navBytes = "";
for (var key in navigator) {
try {
if (typeof navigator[key] == "string") {
_navBytes += navigator[key];
}
} catch (e7) {
}
}
_ctx.collect(_navBytes);
_navBytes = null;
}
if (jQuery2) {
jQuery2().mousemove(function(e7) {
_ctx.collectInt(e7.clientX, 16);
_ctx.collectInt(e7.clientY, 16);
});
jQuery2().keypress(function(e7) {
_ctx.collectInt(e7.charCode, 8);
});
}
}
if (!forge.random) {
forge.random = _ctx;
} else {
for (var key in _ctx) {
forge.random[key] = _ctx[key];
}
}
forge.random.createInstance = spawnPrng;
module3.exports = forge.random;
})(typeof jQuery !== "undefined" ? jQuery : null);
})();
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/rc2.js
var require_rc2 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/rc2.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
var piTable = [
217,
120,
249,
196,
25,
221,
181,
237,
40,
233,
253,
121,
74,
160,
216,
157,
198,
126,
55,
131,
43,
118,
83,
142,
98,
76,
100,
136,
68,
139,
251,
162,
23,
154,
89,
245,
135,
179,
79,
19,
97,
69,
109,
141,
9,
129,
125,
50,
189,
143,
64,
235,
134,
183,
123,
11,
240,
149,
33,
34,
92,
107,
78,
130,
84,
214,
101,
147,
206,
96,
178,
28,
115,
86,
192,
20,
167,
140,
241,
220,
18,
117,
202,
31,
59,
190,
228,
209,
66,
61,
212,
48,
163,
60,
182,
38,
111,
191,
14,
218,
70,
105,
7,
87,
39,
242,
29,
155,
188,
148,
67,
3,
248,
17,
199,
246,
144,
239,
62,
231,
6,
195,
213,
47,
200,
102,
30,
215,
8,
232,
234,
222,
128,
82,
238,
247,
132,
170,
114,
172,
53,
77,
106,
42,
150,
26,
210,
113,
90,
21,
73,
116,
75,
159,
208,
94,
4,
24,
164,
236,
194,
224,
65,
110,
15,
81,
203,
204,
36,
145,
175,
80,
161,
244,
112,
57,
153,
124,
58,
133,
35,
184,
180,
122,
252,
2,
54,
91,
37,
85,
151,
49,
45,
93,
250,
152,
227,
138,
146,
174,
5,
223,
41,
16,
103,
108,
186,
201,
211,
0,
230,
207,
225,
158,
168,
44,
99,
22,
1,
63,
88,
226,
137,
169,
13,
56,
52,
27,
171,
51,
255,
176,
187,
72,
12,
95,
185,
177,
205,
46,
197,
243,
219,
71,
229,
165,
156,
119,
10,
166,
32,
104,
254,
127,
193,
173
];
var s5 = [1, 2, 3, 5];
var rol = /* @__PURE__ */ __name(function(word, bits) {
return word << bits & 65535 | (word & 65535) >> 16 - bits;
}, "rol");
var ror = /* @__PURE__ */ __name(function(word, bits) {
return (word & 65535) >> bits | word << 16 - bits & 65535;
}, "ror");
module3.exports = forge.rc2 = forge.rc2 || {};
forge.rc2.expandKey = function(key, effKeyBits) {
if (typeof key === "string") {
key = forge.util.createBuffer(key);
}
effKeyBits = effKeyBits || 128;
var L3 = key;
var T3 = key.length();
var T1 = effKeyBits;
var T8 = Math.ceil(T1 / 8);
var TM = 255 >> (T1 & 7);
var i5;
for (i5 = T3; i5 < 128; i5++) {
L3.putByte(piTable[L3.at(i5 - 1) + L3.at(i5 - T3) & 255]);
}
L3.setAt(128 - T8, piTable[L3.at(128 - T8) & TM]);
for (i5 = 127 - T8; i5 >= 0; i5--) {
L3.setAt(i5, piTable[L3.at(i5 + 1) ^ L3.at(i5 + T8)]);
}
return L3;
};
var createCipher = /* @__PURE__ */ __name(function(key, bits, encrypt) {
var _finish = false, _input = null, _output = null, _iv = null;
var mixRound, mashRound;
var i5, j6, K3 = [];
key = forge.rc2.expandKey(key, bits);
for (i5 = 0; i5 < 64; i5++) {
K3.push(key.getInt16Le());
}
if (encrypt) {
mixRound = /* @__PURE__ */ __name(function(R3) {
for (i5 = 0; i5 < 4; i5++) {
R3[i5] += K3[j6] + (R3[(i5 + 3) % 4] & R3[(i5 + 2) % 4]) + (~R3[(i5 + 3) % 4] & R3[(i5 + 1) % 4]);
R3[i5] = rol(R3[i5], s5[i5]);
j6++;
}
}, "mixRound");
mashRound = /* @__PURE__ */ __name(function(R3) {
for (i5 = 0; i5 < 4; i5++) {
R3[i5] += K3[R3[(i5 + 3) % 4] & 63];
}
}, "mashRound");
} else {
mixRound = /* @__PURE__ */ __name(function(R3) {
for (i5 = 3; i5 >= 0; i5--) {
R3[i5] = ror(R3[i5], s5[i5]);
R3[i5] -= K3[j6] + (R3[(i5 + 3) % 4] & R3[(i5 + 2) % 4]) + (~R3[(i5 + 3) % 4] & R3[(i5 + 1) % 4]);
j6--;
}
}, "mixRound");
mashRound = /* @__PURE__ */ __name(function(R3) {
for (i5 = 3; i5 >= 0; i5--) {
R3[i5] -= K3[R3[(i5 + 3) % 4] & 63];
}
}, "mashRound");
}
var runPlan = /* @__PURE__ */ __name(function(plan) {
var R3 = [];
for (i5 = 0; i5 < 4; i5++) {
var val2 = _input.getInt16Le();
if (_iv !== null) {
if (encrypt) {
val2 ^= _iv.getInt16Le();
} else {
_iv.putInt16Le(val2);
}
}
R3.push(val2 & 65535);
}
j6 = encrypt ? 0 : 63;
for (var ptr = 0; ptr < plan.length; ptr++) {
for (var ctr = 0; ctr < plan[ptr][0]; ctr++) {
plan[ptr][1](R3);
}
}
for (i5 = 0; i5 < 4; i5++) {
if (_iv !== null) {
if (encrypt) {
_iv.putInt16Le(R3[i5]);
} else {
R3[i5] ^= _iv.getInt16Le();
}
}
_output.putInt16Le(R3[i5]);
}
}, "runPlan");
var cipher = null;
cipher = {
/**
* Starts or restarts the encryption or decryption process, whichever
* was previously configured.
*
* To use the cipher in CBC mode, iv may be given either as a string
* of bytes, or as a byte buffer. For ECB mode, give null as iv.
*
* @param iv the initialization vector to use, null for ECB mode.
* @param output the output the buffer to write to, null to create one.
*/
start: /* @__PURE__ */ __name(function(iv, output) {
if (iv) {
if (typeof iv === "string") {
iv = forge.util.createBuffer(iv);
}
}
_finish = false;
_input = forge.util.createBuffer();
_output = output || new forge.util.createBuffer();
_iv = iv;
cipher.output = _output;
}, "start"),
/**
* Updates the next block.
*
* @param input the buffer to read from.
*/
update: /* @__PURE__ */ __name(function(input) {
if (!_finish) {
_input.putBuffer(input);
}
while (_input.length() >= 8) {
runPlan([
[5, mixRound],
[1, mashRound],
[6, mixRound],
[1, mashRound],
[5, mixRound]
]);
}
}, "update"),
/**
* Finishes encrypting or decrypting.
*
* @param pad a padding function to use, null for PKCS#7 padding,
* signature(blockSize, buffer, decrypt).
*
* @return true if successful, false on error.
*/
finish: /* @__PURE__ */ __name(function(pad2) {
var rval = true;
if (encrypt) {
if (pad2) {
rval = pad2(8, _input, !encrypt);
} else {
var padding = _input.length() === 8 ? 8 : 8 - _input.length();
_input.fillWithByte(padding, padding);
}
}
if (rval) {
_finish = true;
cipher.update();
}
if (!encrypt) {
rval = _input.length() === 0;
if (rval) {
if (pad2) {
rval = pad2(8, _output, !encrypt);
} else {
var len = _output.length();
var count = _output.at(len - 1);
if (count > len) {
rval = false;
} else {
_output.truncate(count);
}
}
}
}
return rval;
}, "finish")
};
return cipher;
}, "createCipher");
forge.rc2.startEncrypting = function(key, iv, output) {
var cipher = forge.rc2.createEncryptionCipher(key, 128);
cipher.start(iv, output);
return cipher;
};
forge.rc2.createEncryptionCipher = function(key, bits) {
return createCipher(key, bits, true);
};
forge.rc2.startDecrypting = function(key, iv, output) {
var cipher = forge.rc2.createDecryptionCipher(key, 128);
cipher.start(iv, output);
return cipher;
};
forge.rc2.createDecryptionCipher = function(key, bits) {
return createCipher(key, bits, false);
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/jsbn.js
var require_jsbn = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/jsbn.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
module3.exports = forge.jsbn = forge.jsbn || {};
var dbits;
var canary = 244837814094590;
var j_lm = (canary & 16777215) == 15715070;
function BigInteger(a5, b6, c6) {
this.data = [];
if (a5 != null)
if ("number" == typeof a5) this.fromNumber(a5, b6, c6);
else if (b6 == null && "string" != typeof a5) this.fromString(a5, 256);
else this.fromString(a5, b6);
}
__name(BigInteger, "BigInteger");
forge.jsbn.BigInteger = BigInteger;
function nbi() {
return new BigInteger(null);
}
__name(nbi, "nbi");
function am1(i5, x6, w6, j6, c6, n6) {
while (--n6 >= 0) {
var v7 = x6 * this.data[i5++] + w6.data[j6] + c6;
c6 = Math.floor(v7 / 67108864);
w6.data[j6++] = v7 & 67108863;
}
return c6;
}
__name(am1, "am1");
function am2(i5, x6, w6, j6, c6, n6) {
var xl = x6 & 32767, xh = x6 >> 15;
while (--n6 >= 0) {
var l6 = this.data[i5] & 32767;
var h6 = this.data[i5++] >> 15;
var m6 = xh * l6 + h6 * xl;
l6 = xl * l6 + ((m6 & 32767) << 15) + w6.data[j6] + (c6 & 1073741823);
c6 = (l6 >>> 30) + (m6 >>> 15) + xh * h6 + (c6 >>> 30);
w6.data[j6++] = l6 & 1073741823;
}
return c6;
}
__name(am2, "am2");
function am3(i5, x6, w6, j6, c6, n6) {
var xl = x6 & 16383, xh = x6 >> 14;
while (--n6 >= 0) {
var l6 = this.data[i5] & 16383;
var h6 = this.data[i5++] >> 14;
var m6 = xh * l6 + h6 * xl;
l6 = xl * l6 + ((m6 & 16383) << 14) + w6.data[j6] + c6;
c6 = (l6 >> 28) + (m6 >> 14) + xh * h6;
w6.data[j6++] = l6 & 268435455;
}
return c6;
}
__name(am3, "am3");
if (typeof navigator === "undefined") {
BigInteger.prototype.am = am3;
dbits = 28;
} else if (j_lm && navigator.appName == "Microsoft Internet Explorer") {
BigInteger.prototype.am = am2;
dbits = 30;
} else if (j_lm && navigator.appName != "Netscape") {
BigInteger.prototype.am = am1;
dbits = 26;
} else {
BigInteger.prototype.am = am3;
dbits = 28;
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = (1 << dbits) - 1;
BigInteger.prototype.DV = 1 << dbits;
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2, BI_FP);
BigInteger.prototype.F1 = BI_FP - dbits;
BigInteger.prototype.F2 = 2 * dbits - BI_FP;
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr;
var vv;
rr = "0".charCodeAt(0);
for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
rr = "a".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
rr = "A".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
function int2char(n6) {
return BI_RM.charAt(n6);
}
__name(int2char, "int2char");
function intAt(s5, i5) {
var c6 = BI_RC[s5.charCodeAt(i5)];
return c6 == null ? -1 : c6;
}
__name(intAt, "intAt");
function bnpCopyTo(r7) {
for (var i5 = this.t - 1; i5 >= 0; --i5) r7.data[i5] = this.data[i5];
r7.t = this.t;
r7.s = this.s;
}
__name(bnpCopyTo, "bnpCopyTo");
function bnpFromInt(x6) {
this.t = 1;
this.s = x6 < 0 ? -1 : 0;
if (x6 > 0) this.data[0] = x6;
else if (x6 < -1) this.data[0] = x6 + this.DV;
else this.t = 0;
}
__name(bnpFromInt, "bnpFromInt");
function nbv(i5) {
var r7 = nbi();
r7.fromInt(i5);
return r7;
}
__name(nbv, "nbv");
function bnpFromString(s5, b6) {
var k6;
if (b6 == 16) k6 = 4;
else if (b6 == 8) k6 = 3;
else if (b6 == 256) k6 = 8;
else if (b6 == 2) k6 = 1;
else if (b6 == 32) k6 = 5;
else if (b6 == 4) k6 = 2;
else {
this.fromRadix(s5, b6);
return;
}
this.t = 0;
this.s = 0;
var i5 = s5.length, mi = false, sh = 0;
while (--i5 >= 0) {
var x6 = k6 == 8 ? s5[i5] & 255 : intAt(s5, i5);
if (x6 < 0) {
if (s5.charAt(i5) == "-") mi = true;
continue;
}
mi = false;
if (sh == 0)
this.data[this.t++] = x6;
else if (sh + k6 > this.DB) {
this.data[this.t - 1] |= (x6 & (1 << this.DB - sh) - 1) << sh;
this.data[this.t++] = x6 >> this.DB - sh;
} else
this.data[this.t - 1] |= x6 << sh;
sh += k6;
if (sh >= this.DB) sh -= this.DB;
}
if (k6 == 8 && (s5[0] & 128) != 0) {
this.s = -1;
if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
}
this.clamp();
if (mi) BigInteger.ZERO.subTo(this, this);
}
__name(bnpFromString, "bnpFromString");
function bnpClamp() {
var c6 = this.s & this.DM;
while (this.t > 0 && this.data[this.t - 1] == c6) --this.t;
}
__name(bnpClamp, "bnpClamp");
function bnToString(b6) {
if (this.s < 0) return "-" + this.negate().toString(b6);
var k6;
if (b6 == 16) k6 = 4;
else if (b6 == 8) k6 = 3;
else if (b6 == 2) k6 = 1;
else if (b6 == 32) k6 = 5;
else if (b6 == 4) k6 = 2;
else return this.toRadix(b6);
var km = (1 << k6) - 1, d6, m6 = false, r7 = "", i5 = this.t;
var p6 = this.DB - i5 * this.DB % k6;
if (i5-- > 0) {
if (p6 < this.DB && (d6 = this.data[i5] >> p6) > 0) {
m6 = true;
r7 = int2char(d6);
}
while (i5 >= 0) {
if (p6 < k6) {
d6 = (this.data[i5] & (1 << p6) - 1) << k6 - p6;
d6 |= this.data[--i5] >> (p6 += this.DB - k6);
} else {
d6 = this.data[i5] >> (p6 -= k6) & km;
if (p6 <= 0) {
p6 += this.DB;
--i5;
}
}
if (d6 > 0) m6 = true;
if (m6) r7 += int2char(d6);
}
}
return m6 ? r7 : "0";
}
__name(bnToString, "bnToString");
function bnNegate() {
var r7 = nbi();
BigInteger.ZERO.subTo(this, r7);
return r7;
}
__name(bnNegate, "bnNegate");
function bnAbs() {
return this.s < 0 ? this.negate() : this;
}
__name(bnAbs, "bnAbs");
function bnCompareTo(a5) {
var r7 = this.s - a5.s;
if (r7 != 0) return r7;
var i5 = this.t;
r7 = i5 - a5.t;
if (r7 != 0) return this.s < 0 ? -r7 : r7;
while (--i5 >= 0) if ((r7 = this.data[i5] - a5.data[i5]) != 0) return r7;
return 0;
}
__name(bnCompareTo, "bnCompareTo");
function nbits(x6) {
var r7 = 1, t7;
if ((t7 = x6 >>> 16) != 0) {
x6 = t7;
r7 += 16;
}
if ((t7 = x6 >> 8) != 0) {
x6 = t7;
r7 += 8;
}
if ((t7 = x6 >> 4) != 0) {
x6 = t7;
r7 += 4;
}
if ((t7 = x6 >> 2) != 0) {
x6 = t7;
r7 += 2;
}
if ((t7 = x6 >> 1) != 0) {
x6 = t7;
r7 += 1;
}
return r7;
}
__name(nbits, "nbits");
function bnBitLength() {
if (this.t <= 0) return 0;
return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM);
}
__name(bnBitLength, "bnBitLength");
function bnpDLShiftTo(n6, r7) {
var i5;
for (i5 = this.t - 1; i5 >= 0; --i5) r7.data[i5 + n6] = this.data[i5];
for (i5 = n6 - 1; i5 >= 0; --i5) r7.data[i5] = 0;
r7.t = this.t + n6;
r7.s = this.s;
}
__name(bnpDLShiftTo, "bnpDLShiftTo");
function bnpDRShiftTo(n6, r7) {
for (var i5 = n6; i5 < this.t; ++i5) r7.data[i5 - n6] = this.data[i5];
r7.t = Math.max(this.t - n6, 0);
r7.s = this.s;
}
__name(bnpDRShiftTo, "bnpDRShiftTo");
function bnpLShiftTo(n6, r7) {
var bs2 = n6 % this.DB;
var cbs = this.DB - bs2;
var bm2 = (1 << cbs) - 1;
var ds = Math.floor(n6 / this.DB), c6 = this.s << bs2 & this.DM, i5;
for (i5 = this.t - 1; i5 >= 0; --i5) {
r7.data[i5 + ds + 1] = this.data[i5] >> cbs | c6;
c6 = (this.data[i5] & bm2) << bs2;
}
for (i5 = ds - 1; i5 >= 0; --i5) r7.data[i5] = 0;
r7.data[ds] = c6;
r7.t = this.t + ds + 1;
r7.s = this.s;
r7.clamp();
}
__name(bnpLShiftTo, "bnpLShiftTo");
function bnpRShiftTo(n6, r7) {
r7.s = this.s;
var ds = Math.floor(n6 / this.DB);
if (ds >= this.t) {
r7.t = 0;
return;
}
var bs2 = n6 % this.DB;
var cbs = this.DB - bs2;
var bm2 = (1 << bs2) - 1;
r7.data[0] = this.data[ds] >> bs2;
for (var i5 = ds + 1; i5 < this.t; ++i5) {
r7.data[i5 - ds - 1] |= (this.data[i5] & bm2) << cbs;
r7.data[i5 - ds] = this.data[i5] >> bs2;
}
if (bs2 > 0) r7.data[this.t - ds - 1] |= (this.s & bm2) << cbs;
r7.t = this.t - ds;
r7.clamp();
}
__name(bnpRShiftTo, "bnpRShiftTo");
function bnpSubTo(a5, r7) {
var i5 = 0, c6 = 0, m6 = Math.min(a5.t, this.t);
while (i5 < m6) {
c6 += this.data[i5] - a5.data[i5];
r7.data[i5++] = c6 & this.DM;
c6 >>= this.DB;
}
if (a5.t < this.t) {
c6 -= a5.s;
while (i5 < this.t) {
c6 += this.data[i5];
r7.data[i5++] = c6 & this.DM;
c6 >>= this.DB;
}
c6 += this.s;
} else {
c6 += this.s;
while (i5 < a5.t) {
c6 -= a5.data[i5];
r7.data[i5++] = c6 & this.DM;
c6 >>= this.DB;
}
c6 -= a5.s;
}
r7.s = c6 < 0 ? -1 : 0;
if (c6 < -1) r7.data[i5++] = this.DV + c6;
else if (c6 > 0) r7.data[i5++] = c6;
r7.t = i5;
r7.clamp();
}
__name(bnpSubTo, "bnpSubTo");
function bnpMultiplyTo(a5, r7) {
var x6 = this.abs(), y4 = a5.abs();
var i5 = x6.t;
r7.t = i5 + y4.t;
while (--i5 >= 0) r7.data[i5] = 0;
for (i5 = 0; i5 < y4.t; ++i5) r7.data[i5 + x6.t] = x6.am(0, y4.data[i5], r7, i5, 0, x6.t);
r7.s = 0;
r7.clamp();
if (this.s != a5.s) BigInteger.ZERO.subTo(r7, r7);
}
__name(bnpMultiplyTo, "bnpMultiplyTo");
function bnpSquareTo(r7) {
var x6 = this.abs();
var i5 = r7.t = 2 * x6.t;
while (--i5 >= 0) r7.data[i5] = 0;
for (i5 = 0; i5 < x6.t - 1; ++i5) {
var c6 = x6.am(i5, x6.data[i5], r7, 2 * i5, 0, 1);
if ((r7.data[i5 + x6.t] += x6.am(i5 + 1, 2 * x6.data[i5], r7, 2 * i5 + 1, c6, x6.t - i5 - 1)) >= x6.DV) {
r7.data[i5 + x6.t] -= x6.DV;
r7.data[i5 + x6.t + 1] = 1;
}
}
if (r7.t > 0) r7.data[r7.t - 1] += x6.am(i5, x6.data[i5], r7, 2 * i5, 0, 1);
r7.s = 0;
r7.clamp();
}
__name(bnpSquareTo, "bnpSquareTo");
function bnpDivRemTo(m6, q6, r7) {
var pm = m6.abs();
if (pm.t <= 0) return;
var pt = this.abs();
if (pt.t < pm.t) {
if (q6 != null) q6.fromInt(0);
if (r7 != null) this.copyTo(r7);
return;
}
if (r7 == null) r7 = nbi();
var y4 = nbi(), ts = this.s, ms = m6.s;
var nsh = this.DB - nbits(pm.data[pm.t - 1]);
if (nsh > 0) {
pm.lShiftTo(nsh, y4);
pt.lShiftTo(nsh, r7);
} else {
pm.copyTo(y4);
pt.copyTo(r7);
}
var ys = y4.t;
var y0 = y4.data[ys - 1];
if (y0 == 0) return;
var yt = y0 * (1 << this.F1) + (ys > 1 ? y4.data[ys - 2] >> this.F2 : 0);
var d1 = this.FV / yt, d22 = (1 << this.F1) / yt, e7 = 1 << this.F2;
var i5 = r7.t, j6 = i5 - ys, t7 = q6 == null ? nbi() : q6;
y4.dlShiftTo(j6, t7);
if (r7.compareTo(t7) >= 0) {
r7.data[r7.t++] = 1;
r7.subTo(t7, r7);
}
BigInteger.ONE.dlShiftTo(ys, t7);
t7.subTo(y4, y4);
while (y4.t < ys) y4.data[y4.t++] = 0;
while (--j6 >= 0) {
var qd = r7.data[--i5] == y0 ? this.DM : Math.floor(r7.data[i5] * d1 + (r7.data[i5 - 1] + e7) * d22);
if ((r7.data[i5] += y4.am(0, qd, r7, j6, 0, ys)) < qd) {
y4.dlShiftTo(j6, t7);
r7.subTo(t7, r7);
while (r7.data[i5] < --qd) r7.subTo(t7, r7);
}
}
if (q6 != null) {
r7.drShiftTo(ys, q6);
if (ts != ms) BigInteger.ZERO.subTo(q6, q6);
}
r7.t = ys;
r7.clamp();
if (nsh > 0) r7.rShiftTo(nsh, r7);
if (ts < 0) BigInteger.ZERO.subTo(r7, r7);
}
__name(bnpDivRemTo, "bnpDivRemTo");
function bnMod(a5) {
var r7 = nbi();
this.abs().divRemTo(a5, null, r7);
if (this.s < 0 && r7.compareTo(BigInteger.ZERO) > 0) a5.subTo(r7, r7);
return r7;
}
__name(bnMod, "bnMod");
function Classic(m6) {
this.m = m6;
}
__name(Classic, "Classic");
function cConvert(x6) {
if (x6.s < 0 || x6.compareTo(this.m) >= 0) return x6.mod(this.m);
else return x6;
}
__name(cConvert, "cConvert");
function cRevert(x6) {
return x6;
}
__name(cRevert, "cRevert");
function cReduce(x6) {
x6.divRemTo(this.m, null, x6);
}
__name(cReduce, "cReduce");
function cMulTo(x6, y4, r7) {
x6.multiplyTo(y4, r7);
this.reduce(r7);
}
__name(cMulTo, "cMulTo");
function cSqrTo(x6, r7) {
x6.squareTo(r7);
this.reduce(r7);
}
__name(cSqrTo, "cSqrTo");
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
function bnpInvDigit() {
if (this.t < 1) return 0;
var x6 = this.data[0];
if ((x6 & 1) == 0) return 0;
var y4 = x6 & 3;
y4 = y4 * (2 - (x6 & 15) * y4) & 15;
y4 = y4 * (2 - (x6 & 255) * y4) & 255;
y4 = y4 * (2 - ((x6 & 65535) * y4 & 65535)) & 65535;
y4 = y4 * (2 - x6 * y4 % this.DV) % this.DV;
return y4 > 0 ? this.DV - y4 : -y4;
}
__name(bnpInvDigit, "bnpInvDigit");
function Montgomery(m6) {
this.m = m6;
this.mp = m6.invDigit();
this.mpl = this.mp & 32767;
this.mph = this.mp >> 15;
this.um = (1 << m6.DB - 15) - 1;
this.mt2 = 2 * m6.t;
}
__name(Montgomery, "Montgomery");
function montConvert(x6) {
var r7 = nbi();
x6.abs().dlShiftTo(this.m.t, r7);
r7.divRemTo(this.m, null, r7);
if (x6.s < 0 && r7.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r7, r7);
return r7;
}
__name(montConvert, "montConvert");
function montRevert(x6) {
var r7 = nbi();
x6.copyTo(r7);
this.reduce(r7);
return r7;
}
__name(montRevert, "montRevert");
function montReduce(x6) {
while (x6.t <= this.mt2)
x6.data[x6.t++] = 0;
for (var i5 = 0; i5 < this.m.t; ++i5) {
var j6 = x6.data[i5] & 32767;
var u0 = j6 * this.mpl + ((j6 * this.mph + (x6.data[i5] >> 15) * this.mpl & this.um) << 15) & x6.DM;
j6 = i5 + this.m.t;
x6.data[j6] += this.m.am(0, u0, x6, i5, 0, this.m.t);
while (x6.data[j6] >= x6.DV) {
x6.data[j6] -= x6.DV;
x6.data[++j6]++;
}
}
x6.clamp();
x6.drShiftTo(this.m.t, x6);
if (x6.compareTo(this.m) >= 0) x6.subTo(this.m, x6);
}
__name(montReduce, "montReduce");
function montSqrTo(x6, r7) {
x6.squareTo(r7);
this.reduce(r7);
}
__name(montSqrTo, "montSqrTo");
function montMulTo(x6, y4, r7) {
x6.multiplyTo(y4, r7);
this.reduce(r7);
}
__name(montMulTo, "montMulTo");
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
function bnpIsEven() {
return (this.t > 0 ? this.data[0] & 1 : this.s) == 0;
}
__name(bnpIsEven, "bnpIsEven");
function bnpExp(e7, z5) {
if (e7 > 4294967295 || e7 < 1) return BigInteger.ONE;
var r7 = nbi(), r22 = nbi(), g6 = z5.convert(this), i5 = nbits(e7) - 1;
g6.copyTo(r7);
while (--i5 >= 0) {
z5.sqrTo(r7, r22);
if ((e7 & 1 << i5) > 0) z5.mulTo(r22, g6, r7);
else {
var t7 = r7;
r7 = r22;
r22 = t7;
}
}
return z5.revert(r7);
}
__name(bnpExp, "bnpExp");
function bnModPowInt(e7, m6) {
var z5;
if (e7 < 256 || m6.isEven()) z5 = new Classic(m6);
else z5 = new Montgomery(m6);
return this.exp(e7, z5);
}
__name(bnModPowInt, "bnModPowInt");
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
function bnClone() {
var r7 = nbi();
this.copyTo(r7);
return r7;
}
__name(bnClone, "bnClone");
function bnIntValue() {
if (this.s < 0) {
if (this.t == 1) return this.data[0] - this.DV;
else if (this.t == 0) return -1;
} else if (this.t == 1) return this.data[0];
else if (this.t == 0) return 0;
return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0];
}
__name(bnIntValue, "bnIntValue");
function bnByteValue() {
return this.t == 0 ? this.s : this.data[0] << 24 >> 24;
}
__name(bnByteValue, "bnByteValue");
function bnShortValue() {
return this.t == 0 ? this.s : this.data[0] << 16 >> 16;
}
__name(bnShortValue, "bnShortValue");
function bnpChunkSize(r7) {
return Math.floor(Math.LN2 * this.DB / Math.log(r7));
}
__name(bnpChunkSize, "bnpChunkSize");
function bnSigNum() {
if (this.s < 0) return -1;
else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0;
else return 1;
}
__name(bnSigNum, "bnSigNum");
function bnpToRadix(b6) {
if (b6 == null) b6 = 10;
if (this.signum() == 0 || b6 < 2 || b6 > 36) return "0";
var cs2 = this.chunkSize(b6);
var a5 = Math.pow(b6, cs2);
var d6 = nbv(a5), y4 = nbi(), z5 = nbi(), r7 = "";
this.divRemTo(d6, y4, z5);
while (y4.signum() > 0) {
r7 = (a5 + z5.intValue()).toString(b6).substr(1) + r7;
y4.divRemTo(d6, y4, z5);
}
return z5.intValue().toString(b6) + r7;
}
__name(bnpToRadix, "bnpToRadix");
function bnpFromRadix(s5, b6) {
this.fromInt(0);
if (b6 == null) b6 = 10;
var cs2 = this.chunkSize(b6);
var d6 = Math.pow(b6, cs2), mi = false, j6 = 0, w6 = 0;
for (var i5 = 0; i5 < s5.length; ++i5) {
var x6 = intAt(s5, i5);
if (x6 < 0) {
if (s5.charAt(i5) == "-" && this.signum() == 0) mi = true;
continue;
}
w6 = b6 * w6 + x6;
if (++j6 >= cs2) {
this.dMultiply(d6);
this.dAddOffset(w6, 0);
j6 = 0;
w6 = 0;
}
}
if (j6 > 0) {
this.dMultiply(Math.pow(b6, j6));
this.dAddOffset(w6, 0);
}
if (mi) BigInteger.ZERO.subTo(this, this);
}
__name(bnpFromRadix, "bnpFromRadix");
function bnpFromNumber(a5, b6, c6) {
if ("number" == typeof b6) {
if (a5 < 2) this.fromInt(1);
else {
this.fromNumber(a5, c6);
if (!this.testBit(a5 - 1))
this.bitwiseTo(BigInteger.ONE.shiftLeft(a5 - 1), op_or, this);
if (this.isEven()) this.dAddOffset(1, 0);
while (!this.isProbablePrime(b6)) {
this.dAddOffset(2, 0);
if (this.bitLength() > a5) this.subTo(BigInteger.ONE.shiftLeft(a5 - 1), this);
}
}
} else {
var x6 = new Array(), t7 = a5 & 7;
x6.length = (a5 >> 3) + 1;
b6.nextBytes(x6);
if (t7 > 0) x6[0] &= (1 << t7) - 1;
else x6[0] = 0;
this.fromString(x6, 256);
}
}
__name(bnpFromNumber, "bnpFromNumber");
function bnToByteArray() {
var i5 = this.t, r7 = new Array();
r7[0] = this.s;
var p6 = this.DB - i5 * this.DB % 8, d6, k6 = 0;
if (i5-- > 0) {
if (p6 < this.DB && (d6 = this.data[i5] >> p6) != (this.s & this.DM) >> p6)
r7[k6++] = d6 | this.s << this.DB - p6;
while (i5 >= 0) {
if (p6 < 8) {
d6 = (this.data[i5] & (1 << p6) - 1) << 8 - p6;
d6 |= this.data[--i5] >> (p6 += this.DB - 8);
} else {
d6 = this.data[i5] >> (p6 -= 8) & 255;
if (p6 <= 0) {
p6 += this.DB;
--i5;
}
}
if ((d6 & 128) != 0) d6 |= -256;
if (k6 == 0 && (this.s & 128) != (d6 & 128)) ++k6;
if (k6 > 0 || d6 != this.s) r7[k6++] = d6;
}
}
return r7;
}
__name(bnToByteArray, "bnToByteArray");
function bnEquals(a5) {
return this.compareTo(a5) == 0;
}
__name(bnEquals, "bnEquals");
function bnMin(a5) {
return this.compareTo(a5) < 0 ? this : a5;
}
__name(bnMin, "bnMin");
function bnMax(a5) {
return this.compareTo(a5) > 0 ? this : a5;
}
__name(bnMax, "bnMax");
function bnpBitwiseTo(a5, op, r7) {
var i5, f6, m6 = Math.min(a5.t, this.t);
for (i5 = 0; i5 < m6; ++i5) r7.data[i5] = op(this.data[i5], a5.data[i5]);
if (a5.t < this.t) {
f6 = a5.s & this.DM;
for (i5 = m6; i5 < this.t; ++i5) r7.data[i5] = op(this.data[i5], f6);
r7.t = this.t;
} else {
f6 = this.s & this.DM;
for (i5 = m6; i5 < a5.t; ++i5) r7.data[i5] = op(f6, a5.data[i5]);
r7.t = a5.t;
}
r7.s = op(this.s, a5.s);
r7.clamp();
}
__name(bnpBitwiseTo, "bnpBitwiseTo");
function op_and(x6, y4) {
return x6 & y4;
}
__name(op_and, "op_and");
function bnAnd(a5) {
var r7 = nbi();
this.bitwiseTo(a5, op_and, r7);
return r7;
}
__name(bnAnd, "bnAnd");
function op_or(x6, y4) {
return x6 | y4;
}
__name(op_or, "op_or");
function bnOr(a5) {
var r7 = nbi();
this.bitwiseTo(a5, op_or, r7);
return r7;
}
__name(bnOr, "bnOr");
function op_xor(x6, y4) {
return x6 ^ y4;
}
__name(op_xor, "op_xor");
function bnXor(a5) {
var r7 = nbi();
this.bitwiseTo(a5, op_xor, r7);
return r7;
}
__name(bnXor, "bnXor");
function op_andnot(x6, y4) {
return x6 & ~y4;
}
__name(op_andnot, "op_andnot");
function bnAndNot(a5) {
var r7 = nbi();
this.bitwiseTo(a5, op_andnot, r7);
return r7;
}
__name(bnAndNot, "bnAndNot");
function bnNot() {
var r7 = nbi();
for (var i5 = 0; i5 < this.t; ++i5) r7.data[i5] = this.DM & ~this.data[i5];
r7.t = this.t;
r7.s = ~this.s;
return r7;
}
__name(bnNot, "bnNot");
function bnShiftLeft(n6) {
var r7 = nbi();
if (n6 < 0) this.rShiftTo(-n6, r7);
else this.lShiftTo(n6, r7);
return r7;
}
__name(bnShiftLeft, "bnShiftLeft");
function bnShiftRight(n6) {
var r7 = nbi();
if (n6 < 0) this.lShiftTo(-n6, r7);
else this.rShiftTo(n6, r7);
return r7;
}
__name(bnShiftRight, "bnShiftRight");
function lbit(x6) {
if (x6 == 0) return -1;
var r7 = 0;
if ((x6 & 65535) == 0) {
x6 >>= 16;
r7 += 16;
}
if ((x6 & 255) == 0) {
x6 >>= 8;
r7 += 8;
}
if ((x6 & 15) == 0) {
x6 >>= 4;
r7 += 4;
}
if ((x6 & 3) == 0) {
x6 >>= 2;
r7 += 2;
}
if ((x6 & 1) == 0) ++r7;
return r7;
}
__name(lbit, "lbit");
function bnGetLowestSetBit() {
for (var i5 = 0; i5 < this.t; ++i5)
if (this.data[i5] != 0) return i5 * this.DB + lbit(this.data[i5]);
if (this.s < 0) return this.t * this.DB;
return -1;
}
__name(bnGetLowestSetBit, "bnGetLowestSetBit");
function cbit(x6) {
var r7 = 0;
while (x6 != 0) {
x6 &= x6 - 1;
++r7;
}
return r7;
}
__name(cbit, "cbit");
function bnBitCount() {
var r7 = 0, x6 = this.s & this.DM;
for (var i5 = 0; i5 < this.t; ++i5) r7 += cbit(this.data[i5] ^ x6);
return r7;
}
__name(bnBitCount, "bnBitCount");
function bnTestBit(n6) {
var j6 = Math.floor(n6 / this.DB);
if (j6 >= this.t) return this.s != 0;
return (this.data[j6] & 1 << n6 % this.DB) != 0;
}
__name(bnTestBit, "bnTestBit");
function bnpChangeBit(n6, op) {
var r7 = BigInteger.ONE.shiftLeft(n6);
this.bitwiseTo(r7, op, r7);
return r7;
}
__name(bnpChangeBit, "bnpChangeBit");
function bnSetBit(n6) {
return this.changeBit(n6, op_or);
}
__name(bnSetBit, "bnSetBit");
function bnClearBit(n6) {
return this.changeBit(n6, op_andnot);
}
__name(bnClearBit, "bnClearBit");
function bnFlipBit(n6) {
return this.changeBit(n6, op_xor);
}
__name(bnFlipBit, "bnFlipBit");
function bnpAddTo(a5, r7) {
var i5 = 0, c6 = 0, m6 = Math.min(a5.t, this.t);
while (i5 < m6) {
c6 += this.data[i5] + a5.data[i5];
r7.data[i5++] = c6 & this.DM;
c6 >>= this.DB;
}
if (a5.t < this.t) {
c6 += a5.s;
while (i5 < this.t) {
c6 += this.data[i5];
r7.data[i5++] = c6 & this.DM;
c6 >>= this.DB;
}
c6 += this.s;
} else {
c6 += this.s;
while (i5 < a5.t) {
c6 += a5.data[i5];
r7.data[i5++] = c6 & this.DM;
c6 >>= this.DB;
}
c6 += a5.s;
}
r7.s = c6 < 0 ? -1 : 0;
if (c6 > 0) r7.data[i5++] = c6;
else if (c6 < -1) r7.data[i5++] = this.DV + c6;
r7.t = i5;
r7.clamp();
}
__name(bnpAddTo, "bnpAddTo");
function bnAdd(a5) {
var r7 = nbi();
this.addTo(a5, r7);
return r7;
}
__name(bnAdd, "bnAdd");
function bnSubtract(a5) {
var r7 = nbi();
this.subTo(a5, r7);
return r7;
}
__name(bnSubtract, "bnSubtract");
function bnMultiply(a5) {
var r7 = nbi();
this.multiplyTo(a5, r7);
return r7;
}
__name(bnMultiply, "bnMultiply");
function bnDivide(a5) {
var r7 = nbi();
this.divRemTo(a5, r7, null);
return r7;
}
__name(bnDivide, "bnDivide");
function bnRemainder(a5) {
var r7 = nbi();
this.divRemTo(a5, null, r7);
return r7;
}
__name(bnRemainder, "bnRemainder");
function bnDivideAndRemainder(a5) {
var q6 = nbi(), r7 = nbi();
this.divRemTo(a5, q6, r7);
return new Array(q6, r7);
}
__name(bnDivideAndRemainder, "bnDivideAndRemainder");
function bnpDMultiply(n6) {
this.data[this.t] = this.am(0, n6 - 1, this, 0, 0, this.t);
++this.t;
this.clamp();
}
__name(bnpDMultiply, "bnpDMultiply");
function bnpDAddOffset(n6, w6) {
if (n6 == 0) return;
while (this.t <= w6) this.data[this.t++] = 0;
this.data[w6] += n6;
while (this.data[w6] >= this.DV) {
this.data[w6] -= this.DV;
if (++w6 >= this.t) this.data[this.t++] = 0;
++this.data[w6];
}
}
__name(bnpDAddOffset, "bnpDAddOffset");
function NullExp() {
}
__name(NullExp, "NullExp");
function nNop(x6) {
return x6;
}
__name(nNop, "nNop");
function nMulTo(x6, y4, r7) {
x6.multiplyTo(y4, r7);
}
__name(nMulTo, "nMulTo");
function nSqrTo(x6, r7) {
x6.squareTo(r7);
}
__name(nSqrTo, "nSqrTo");
NullExp.prototype.convert = nNop;
NullExp.prototype.revert = nNop;
NullExp.prototype.mulTo = nMulTo;
NullExp.prototype.sqrTo = nSqrTo;
function bnPow(e7) {
return this.exp(e7, new NullExp());
}
__name(bnPow, "bnPow");
function bnpMultiplyLowerTo(a5, n6, r7) {
var i5 = Math.min(this.t + a5.t, n6);
r7.s = 0;
r7.t = i5;
while (i5 > 0) r7.data[--i5] = 0;
var j6;
for (j6 = r7.t - this.t; i5 < j6; ++i5) r7.data[i5 + this.t] = this.am(0, a5.data[i5], r7, i5, 0, this.t);
for (j6 = Math.min(a5.t, n6); i5 < j6; ++i5) this.am(0, a5.data[i5], r7, i5, 0, n6 - i5);
r7.clamp();
}
__name(bnpMultiplyLowerTo, "bnpMultiplyLowerTo");
function bnpMultiplyUpperTo(a5, n6, r7) {
--n6;
var i5 = r7.t = this.t + a5.t - n6;
r7.s = 0;
while (--i5 >= 0) r7.data[i5] = 0;
for (i5 = Math.max(n6 - this.t, 0); i5 < a5.t; ++i5)
r7.data[this.t + i5 - n6] = this.am(n6 - i5, a5.data[i5], r7, 0, 0, this.t + i5 - n6);
r7.clamp();
r7.drShiftTo(1, r7);
}
__name(bnpMultiplyUpperTo, "bnpMultiplyUpperTo");
function Barrett(m6) {
this.r2 = nbi();
this.q3 = nbi();
BigInteger.ONE.dlShiftTo(2 * m6.t, this.r2);
this.mu = this.r2.divide(m6);
this.m = m6;
}
__name(Barrett, "Barrett");
function barrettConvert(x6) {
if (x6.s < 0 || x6.t > 2 * this.m.t) return x6.mod(this.m);
else if (x6.compareTo(this.m) < 0) return x6;
else {
var r7 = nbi();
x6.copyTo(r7);
this.reduce(r7);
return r7;
}
}
__name(barrettConvert, "barrettConvert");
function barrettRevert(x6) {
return x6;
}
__name(barrettRevert, "barrettRevert");
function barrettReduce(x6) {
x6.drShiftTo(this.m.t - 1, this.r2);
if (x6.t > this.m.t + 1) {
x6.t = this.m.t + 1;
x6.clamp();
}
this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
while (x6.compareTo(this.r2) < 0) x6.dAddOffset(1, this.m.t + 1);
x6.subTo(this.r2, x6);
while (x6.compareTo(this.m) >= 0) x6.subTo(this.m, x6);
}
__name(barrettReduce, "barrettReduce");
function barrettSqrTo(x6, r7) {
x6.squareTo(r7);
this.reduce(r7);
}
__name(barrettSqrTo, "barrettSqrTo");
function barrettMulTo(x6, y4, r7) {
x6.multiplyTo(y4, r7);
this.reduce(r7);
}
__name(barrettMulTo, "barrettMulTo");
Barrett.prototype.convert = barrettConvert;
Barrett.prototype.revert = barrettRevert;
Barrett.prototype.reduce = barrettReduce;
Barrett.prototype.mulTo = barrettMulTo;
Barrett.prototype.sqrTo = barrettSqrTo;
function bnModPow(e7, m6) {
var i5 = e7.bitLength(), k6, r7 = nbv(1), z5;
if (i5 <= 0) return r7;
else if (i5 < 18) k6 = 1;
else if (i5 < 48) k6 = 3;
else if (i5 < 144) k6 = 4;
else if (i5 < 768) k6 = 5;
else k6 = 6;
if (i5 < 8)
z5 = new Classic(m6);
else if (m6.isEven())
z5 = new Barrett(m6);
else
z5 = new Montgomery(m6);
var g6 = new Array(), n6 = 3, k1 = k6 - 1, km = (1 << k6) - 1;
g6[1] = z5.convert(this);
if (k6 > 1) {
var g22 = nbi();
z5.sqrTo(g6[1], g22);
while (n6 <= km) {
g6[n6] = nbi();
z5.mulTo(g22, g6[n6 - 2], g6[n6]);
n6 += 2;
}
}
var j6 = e7.t - 1, w6, is1 = true, r22 = nbi(), t7;
i5 = nbits(e7.data[j6]) - 1;
while (j6 >= 0) {
if (i5 >= k1) w6 = e7.data[j6] >> i5 - k1 & km;
else {
w6 = (e7.data[j6] & (1 << i5 + 1) - 1) << k1 - i5;
if (j6 > 0) w6 |= e7.data[j6 - 1] >> this.DB + i5 - k1;
}
n6 = k6;
while ((w6 & 1) == 0) {
w6 >>= 1;
--n6;
}
if ((i5 -= n6) < 0) {
i5 += this.DB;
--j6;
}
if (is1) {
g6[w6].copyTo(r7);
is1 = false;
} else {
while (n6 > 1) {
z5.sqrTo(r7, r22);
z5.sqrTo(r22, r7);
n6 -= 2;
}
if (n6 > 0) z5.sqrTo(r7, r22);
else {
t7 = r7;
r7 = r22;
r22 = t7;
}
z5.mulTo(r22, g6[w6], r7);
}
while (j6 >= 0 && (e7.data[j6] & 1 << i5) == 0) {
z5.sqrTo(r7, r22);
t7 = r7;
r7 = r22;
r22 = t7;
if (--i5 < 0) {
i5 = this.DB - 1;
--j6;
}
}
}
return z5.revert(r7);
}
__name(bnModPow, "bnModPow");
function bnGCD(a5) {
var x6 = this.s < 0 ? this.negate() : this.clone();
var y4 = a5.s < 0 ? a5.negate() : a5.clone();
if (x6.compareTo(y4) < 0) {
var t7 = x6;
x6 = y4;
y4 = t7;
}
var i5 = x6.getLowestSetBit(), g6 = y4.getLowestSetBit();
if (g6 < 0) return x6;
if (i5 < g6) g6 = i5;
if (g6 > 0) {
x6.rShiftTo(g6, x6);
y4.rShiftTo(g6, y4);
}
while (x6.signum() > 0) {
if ((i5 = x6.getLowestSetBit()) > 0) x6.rShiftTo(i5, x6);
if ((i5 = y4.getLowestSetBit()) > 0) y4.rShiftTo(i5, y4);
if (x6.compareTo(y4) >= 0) {
x6.subTo(y4, x6);
x6.rShiftTo(1, x6);
} else {
y4.subTo(x6, y4);
y4.rShiftTo(1, y4);
}
}
if (g6 > 0) y4.lShiftTo(g6, y4);
return y4;
}
__name(bnGCD, "bnGCD");
function bnpModInt(n6) {
if (n6 <= 0) return 0;
var d6 = this.DV % n6, r7 = this.s < 0 ? n6 - 1 : 0;
if (this.t > 0)
if (d6 == 0) r7 = this.data[0] % n6;
else for (var i5 = this.t - 1; i5 >= 0; --i5) r7 = (d6 * r7 + this.data[i5]) % n6;
return r7;
}
__name(bnpModInt, "bnpModInt");
function bnModInverse(m6) {
var ac2 = m6.isEven();
if (this.isEven() && ac2 || m6.signum() == 0) return BigInteger.ZERO;
var u5 = m6.clone(), v7 = this.clone();
var a5 = nbv(1), b6 = nbv(0), c6 = nbv(0), d6 = nbv(1);
while (u5.signum() != 0) {
while (u5.isEven()) {
u5.rShiftTo(1, u5);
if (ac2) {
if (!a5.isEven() || !b6.isEven()) {
a5.addTo(this, a5);
b6.subTo(m6, b6);
}
a5.rShiftTo(1, a5);
} else if (!b6.isEven()) b6.subTo(m6, b6);
b6.rShiftTo(1, b6);
}
while (v7.isEven()) {
v7.rShiftTo(1, v7);
if (ac2) {
if (!c6.isEven() || !d6.isEven()) {
c6.addTo(this, c6);
d6.subTo(m6, d6);
}
c6.rShiftTo(1, c6);
} else if (!d6.isEven()) d6.subTo(m6, d6);
d6.rShiftTo(1, d6);
}
if (u5.compareTo(v7) >= 0) {
u5.subTo(v7, u5);
if (ac2) a5.subTo(c6, a5);
b6.subTo(d6, b6);
} else {
v7.subTo(u5, v7);
if (ac2) c6.subTo(a5, c6);
d6.subTo(b6, d6);
}
}
if (v7.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
if (d6.compareTo(m6) >= 0) return d6.subtract(m6);
if (d6.signum() < 0) d6.addTo(m6, d6);
else return d6;
if (d6.signum() < 0) return d6.add(m6);
else return d6;
}
__name(bnModInverse, "bnModInverse");
var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509];
var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
function bnIsProbablePrime(t7) {
var i5, x6 = this.abs();
if (x6.t == 1 && x6.data[0] <= lowprimes[lowprimes.length - 1]) {
for (i5 = 0; i5 < lowprimes.length; ++i5)
if (x6.data[0] == lowprimes[i5]) return true;
return false;
}
if (x6.isEven()) return false;
i5 = 1;
while (i5 < lowprimes.length) {
var m6 = lowprimes[i5], j6 = i5 + 1;
while (j6 < lowprimes.length && m6 < lplim) m6 *= lowprimes[j6++];
m6 = x6.modInt(m6);
while (i5 < j6) if (m6 % lowprimes[i5++] == 0) return false;
}
return x6.millerRabin(t7);
}
__name(bnIsProbablePrime, "bnIsProbablePrime");
function bnpMillerRabin(t7) {
var n1 = this.subtract(BigInteger.ONE);
var k6 = n1.getLowestSetBit();
if (k6 <= 0) return false;
var r7 = n1.shiftRight(k6);
var prng = bnGetPrng();
var a5;
for (var i5 = 0; i5 < t7; ++i5) {
do {
a5 = new BigInteger(this.bitLength(), prng);
} while (a5.compareTo(BigInteger.ONE) <= 0 || a5.compareTo(n1) >= 0);
var y4 = a5.modPow(r7, this);
if (y4.compareTo(BigInteger.ONE) != 0 && y4.compareTo(n1) != 0) {
var j6 = 1;
while (j6++ < k6 && y4.compareTo(n1) != 0) {
y4 = y4.modPowInt(2, this);
if (y4.compareTo(BigInteger.ONE) == 0) return false;
}
if (y4.compareTo(n1) != 0) return false;
}
}
return true;
}
__name(bnpMillerRabin, "bnpMillerRabin");
function bnGetPrng() {
return {
// x is an array to fill with bytes
nextBytes: /* @__PURE__ */ __name(function(x6) {
for (var i5 = 0; i5 < x6.length; ++i5) {
x6[i5] = Math.floor(Math.random() * 256);
}
}, "nextBytes")
};
}
__name(bnGetPrng, "bnGetPrng");
BigInteger.prototype.chunkSize = bnpChunkSize;
BigInteger.prototype.toRadix = bnpToRadix;
BigInteger.prototype.fromRadix = bnpFromRadix;
BigInteger.prototype.fromNumber = bnpFromNumber;
BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
BigInteger.prototype.changeBit = bnpChangeBit;
BigInteger.prototype.addTo = bnpAddTo;
BigInteger.prototype.dMultiply = bnpDMultiply;
BigInteger.prototype.dAddOffset = bnpDAddOffset;
BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
BigInteger.prototype.modInt = bnpModInt;
BigInteger.prototype.millerRabin = bnpMillerRabin;
BigInteger.prototype.clone = bnClone;
BigInteger.prototype.intValue = bnIntValue;
BigInteger.prototype.byteValue = bnByteValue;
BigInteger.prototype.shortValue = bnShortValue;
BigInteger.prototype.signum = bnSigNum;
BigInteger.prototype.toByteArray = bnToByteArray;
BigInteger.prototype.equals = bnEquals;
BigInteger.prototype.min = bnMin;
BigInteger.prototype.max = bnMax;
BigInteger.prototype.and = bnAnd;
BigInteger.prototype.or = bnOr;
BigInteger.prototype.xor = bnXor;
BigInteger.prototype.andNot = bnAndNot;
BigInteger.prototype.not = bnNot;
BigInteger.prototype.shiftLeft = bnShiftLeft;
BigInteger.prototype.shiftRight = bnShiftRight;
BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
BigInteger.prototype.bitCount = bnBitCount;
BigInteger.prototype.testBit = bnTestBit;
BigInteger.prototype.setBit = bnSetBit;
BigInteger.prototype.clearBit = bnClearBit;
BigInteger.prototype.flipBit = bnFlipBit;
BigInteger.prototype.add = bnAdd;
BigInteger.prototype.subtract = bnSubtract;
BigInteger.prototype.multiply = bnMultiply;
BigInteger.prototype.divide = bnDivide;
BigInteger.prototype.remainder = bnRemainder;
BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
BigInteger.prototype.modPow = bnModPow;
BigInteger.prototype.modInverse = bnModInverse;
BigInteger.prototype.pow = bnPow;
BigInteger.prototype.gcd = bnGCD;
BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha1.js
var require_sha1 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha1.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_md();
require_util10();
var sha1 = module3.exports = forge.sha1 = forge.sha1 || {};
forge.md.sha1 = forge.md.algorithms.sha1 = sha1;
sha1.create = function() {
if (!_initialized) {
_init();
}
var _state = null;
var _input = forge.util.createBuffer();
var _w2 = new Array(80);
var md = {
algorithm: "sha1",
blockLength: 64,
digestLength: 20,
// 56-bit length of message so far (does not including padding)
messageLength: 0,
// true message length
fullMessageLength: null,
// size of message length in bytes
messageLengthSize: 8
};
md.start = function() {
md.messageLength = 0;
md.fullMessageLength = md.messageLength64 = [];
var int32s = md.messageLengthSize / 4;
for (var i5 = 0; i5 < int32s; ++i5) {
md.fullMessageLength.push(0);
}
_input = forge.util.createBuffer();
_state = {
h0: 1732584193,
h1: 4023233417,
h2: 2562383102,
h3: 271733878,
h4: 3285377520
};
return md;
};
md.start();
md.update = function(msg, encoding) {
if (encoding === "utf8") {
msg = forge.util.encodeUtf8(msg);
}
var len = msg.length;
md.messageLength += len;
len = [len / 4294967296 >>> 0, len >>> 0];
for (var i5 = md.fullMessageLength.length - 1; i5 >= 0; --i5) {
md.fullMessageLength[i5] += len[1];
len[1] = len[0] + (md.fullMessageLength[i5] / 4294967296 >>> 0);
md.fullMessageLength[i5] = md.fullMessageLength[i5] >>> 0;
len[0] = len[1] / 4294967296 >>> 0;
}
_input.putBytes(msg);
_update(_state, _w2, _input);
if (_input.read > 2048 || _input.length() === 0) {
_input.compact();
}
return md;
};
md.digest = function() {
var finalBlock = forge.util.createBuffer();
finalBlock.putBytes(_input.bytes());
var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
var overflow = remaining & md.blockLength - 1;
finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
var next, carry;
var bits = md.fullMessageLength[0] * 8;
for (var i5 = 0; i5 < md.fullMessageLength.length - 1; ++i5) {
next = md.fullMessageLength[i5 + 1] * 8;
carry = next / 4294967296 >>> 0;
bits += carry;
finalBlock.putInt32(bits >>> 0);
bits = next >>> 0;
}
finalBlock.putInt32(bits);
var s22 = {
h0: _state.h0,
h1: _state.h1,
h2: _state.h2,
h3: _state.h3,
h4: _state.h4
};
_update(s22, _w2, finalBlock);
var rval = forge.util.createBuffer();
rval.putInt32(s22.h0);
rval.putInt32(s22.h1);
rval.putInt32(s22.h2);
rval.putInt32(s22.h3);
rval.putInt32(s22.h4);
return rval;
};
return md;
};
var _padding = null;
var _initialized = false;
function _init() {
_padding = String.fromCharCode(128);
_padding += forge.util.fillString(String.fromCharCode(0), 64);
_initialized = true;
}
__name(_init, "_init");
function _update(s5, w6, bytes) {
var t7, a5, b6, c6, d6, e7, f6, i5;
var len = bytes.length();
while (len >= 64) {
a5 = s5.h0;
b6 = s5.h1;
c6 = s5.h2;
d6 = s5.h3;
e7 = s5.h4;
for (i5 = 0; i5 < 16; ++i5) {
t7 = bytes.getInt32();
w6[i5] = t7;
f6 = d6 ^ b6 & (c6 ^ d6);
t7 = (a5 << 5 | a5 >>> 27) + f6 + e7 + 1518500249 + t7;
e7 = d6;
d6 = c6;
c6 = (b6 << 30 | b6 >>> 2) >>> 0;
b6 = a5;
a5 = t7;
}
for (; i5 < 20; ++i5) {
t7 = w6[i5 - 3] ^ w6[i5 - 8] ^ w6[i5 - 14] ^ w6[i5 - 16];
t7 = t7 << 1 | t7 >>> 31;
w6[i5] = t7;
f6 = d6 ^ b6 & (c6 ^ d6);
t7 = (a5 << 5 | a5 >>> 27) + f6 + e7 + 1518500249 + t7;
e7 = d6;
d6 = c6;
c6 = (b6 << 30 | b6 >>> 2) >>> 0;
b6 = a5;
a5 = t7;
}
for (; i5 < 32; ++i5) {
t7 = w6[i5 - 3] ^ w6[i5 - 8] ^ w6[i5 - 14] ^ w6[i5 - 16];
t7 = t7 << 1 | t7 >>> 31;
w6[i5] = t7;
f6 = b6 ^ c6 ^ d6;
t7 = (a5 << 5 | a5 >>> 27) + f6 + e7 + 1859775393 + t7;
e7 = d6;
d6 = c6;
c6 = (b6 << 30 | b6 >>> 2) >>> 0;
b6 = a5;
a5 = t7;
}
for (; i5 < 40; ++i5) {
t7 = w6[i5 - 6] ^ w6[i5 - 16] ^ w6[i5 - 28] ^ w6[i5 - 32];
t7 = t7 << 2 | t7 >>> 30;
w6[i5] = t7;
f6 = b6 ^ c6 ^ d6;
t7 = (a5 << 5 | a5 >>> 27) + f6 + e7 + 1859775393 + t7;
e7 = d6;
d6 = c6;
c6 = (b6 << 30 | b6 >>> 2) >>> 0;
b6 = a5;
a5 = t7;
}
for (; i5 < 60; ++i5) {
t7 = w6[i5 - 6] ^ w6[i5 - 16] ^ w6[i5 - 28] ^ w6[i5 - 32];
t7 = t7 << 2 | t7 >>> 30;
w6[i5] = t7;
f6 = b6 & c6 | d6 & (b6 ^ c6);
t7 = (a5 << 5 | a5 >>> 27) + f6 + e7 + 2400959708 + t7;
e7 = d6;
d6 = c6;
c6 = (b6 << 30 | b6 >>> 2) >>> 0;
b6 = a5;
a5 = t7;
}
for (; i5 < 80; ++i5) {
t7 = w6[i5 - 6] ^ w6[i5 - 16] ^ w6[i5 - 28] ^ w6[i5 - 32];
t7 = t7 << 2 | t7 >>> 30;
w6[i5] = t7;
f6 = b6 ^ c6 ^ d6;
t7 = (a5 << 5 | a5 >>> 27) + f6 + e7 + 3395469782 + t7;
e7 = d6;
d6 = c6;
c6 = (b6 << 30 | b6 >>> 2) >>> 0;
b6 = a5;
a5 = t7;
}
s5.h0 = s5.h0 + a5 | 0;
s5.h1 = s5.h1 + b6 | 0;
s5.h2 = s5.h2 + c6 | 0;
s5.h3 = s5.h3 + d6 | 0;
s5.h4 = s5.h4 + e7 | 0;
len -= 64;
}
}
__name(_update, "_update");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs1.js
var require_pkcs1 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs1.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
require_random2();
require_sha1();
var pkcs1 = module3.exports = forge.pkcs1 = forge.pkcs1 || {};
pkcs1.encode_rsa_oaep = function(key, message, options) {
var label;
var seed;
var md;
var mgf1Md;
if (typeof options === "string") {
label = options;
seed = arguments[3] || void 0;
md = arguments[4] || void 0;
} else if (options) {
label = options.label || void 0;
seed = options.seed || void 0;
md = options.md || void 0;
if (options.mgf1 && options.mgf1.md) {
mgf1Md = options.mgf1.md;
}
}
if (!md) {
md = forge.md.sha1.create();
} else {
md.start();
}
if (!mgf1Md) {
mgf1Md = md;
}
var keyLength = Math.ceil(key.n.bitLength() / 8);
var maxLength = keyLength - 2 * md.digestLength - 2;
if (message.length > maxLength) {
var error2 = new Error("RSAES-OAEP input message length is too long.");
error2.length = message.length;
error2.maxLength = maxLength;
throw error2;
}
if (!label) {
label = "";
}
md.update(label, "raw");
var lHash = md.digest();
var PS = "";
var PS_length = maxLength - message.length;
for (var i5 = 0; i5 < PS_length; i5++) {
PS += "\0";
}
var DB = lHash.getBytes() + PS + "" + message;
if (!seed) {
seed = forge.random.getBytes(md.digestLength);
} else if (seed.length !== md.digestLength) {
var error2 = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");
error2.seedLength = seed.length;
error2.digestLength = md.digestLength;
throw error2;
}
var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);
var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);
return "\0" + maskedSeed + maskedDB;
};
pkcs1.decode_rsa_oaep = function(key, em, options) {
var label;
var md;
var mgf1Md;
if (typeof options === "string") {
label = options;
md = arguments[3] || void 0;
} else if (options) {
label = options.label || void 0;
md = options.md || void 0;
if (options.mgf1 && options.mgf1.md) {
mgf1Md = options.mgf1.md;
}
}
var keyLength = Math.ceil(key.n.bitLength() / 8);
if (em.length !== keyLength) {
var error2 = new Error("RSAES-OAEP encoded message length is invalid.");
error2.length = em.length;
error2.expectedLength = keyLength;
throw error2;
}
if (md === void 0) {
md = forge.md.sha1.create();
} else {
md.start();
}
if (!mgf1Md) {
mgf1Md = md;
}
if (keyLength < 2 * md.digestLength + 2) {
throw new Error("RSAES-OAEP key is too short for the hash function.");
}
if (!label) {
label = "";
}
md.update(label, "raw");
var lHash = md.digest().getBytes();
var y4 = em.charAt(0);
var maskedSeed = em.substring(1, md.digestLength + 1);
var maskedDB = em.substring(1 + md.digestLength);
var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);
var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);
var lHashPrime = db.substring(0, md.digestLength);
var error2 = y4 !== "\0";
for (var i5 = 0; i5 < md.digestLength; ++i5) {
error2 |= lHash.charAt(i5) !== lHashPrime.charAt(i5);
}
var in_ps = 1;
var index = md.digestLength;
for (var j6 = md.digestLength; j6 < db.length; j6++) {
var code = db.charCodeAt(j6);
var is_0 = code & 1 ^ 1;
var error_mask = in_ps ? 65534 : 0;
error2 |= code & error_mask;
in_ps = in_ps & is_0;
index += in_ps;
}
if (error2 || db.charCodeAt(index) !== 1) {
throw new Error("Invalid RSAES-OAEP padding.");
}
return db.substring(index + 1);
};
function rsa_mgf1(seed, maskLength, hash) {
if (!hash) {
hash = forge.md.sha1.create();
}
var t7 = "";
var count = Math.ceil(maskLength / hash.digestLength);
for (var i5 = 0; i5 < count; ++i5) {
var c6 = String.fromCharCode(
i5 >> 24 & 255,
i5 >> 16 & 255,
i5 >> 8 & 255,
i5 & 255
);
hash.start();
hash.update(seed + c6);
t7 += hash.digest().getBytes();
}
return t7.substring(0, maskLength);
}
__name(rsa_mgf1, "rsa_mgf1");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/prime.js
var require_prime = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/prime.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
require_jsbn();
require_random2();
(function() {
if (forge.prime) {
module3.exports = forge.prime;
return;
}
var prime = module3.exports = forge.prime = forge.prime || {};
var BigInteger = forge.jsbn.BigInteger;
var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
var THIRTY = new BigInteger(null);
THIRTY.fromInt(30);
var op_or = /* @__PURE__ */ __name(function(x6, y4) {
return x6 | y4;
}, "op_or");
prime.generateProbablePrime = function(bits, options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
}
options = options || {};
var algorithm = options.algorithm || "PRIMEINC";
if (typeof algorithm === "string") {
algorithm = { name: algorithm };
}
algorithm.options = algorithm.options || {};
var prng = options.prng || forge.random;
var rng2 = {
// x is an array to fill with bytes
nextBytes: /* @__PURE__ */ __name(function(x6) {
var b6 = prng.getBytesSync(x6.length);
for (var i5 = 0; i5 < x6.length; ++i5) {
x6[i5] = b6.charCodeAt(i5);
}
}, "nextBytes")
};
if (algorithm.name === "PRIMEINC") {
return primeincFindPrime(bits, rng2, algorithm.options, callback);
}
throw new Error("Invalid prime generation algorithm: " + algorithm.name);
};
function primeincFindPrime(bits, rng2, options, callback) {
if ("workers" in options) {
return primeincFindPrimeWithWorkers(bits, rng2, options, callback);
}
return primeincFindPrimeWithoutWorkers(bits, rng2, options, callback);
}
__name(primeincFindPrime, "primeincFindPrime");
function primeincFindPrimeWithoutWorkers(bits, rng2, options, callback) {
var num = generateRandom(bits, rng2);
var deltaIdx = 0;
var mrTests = getMillerRabinTests(num.bitLength());
if ("millerRabinTests" in options) {
mrTests = options.millerRabinTests;
}
var maxBlockTime = 10;
if ("maxBlockTime" in options) {
maxBlockTime = options.maxBlockTime;
}
_primeinc(num, bits, rng2, deltaIdx, mrTests, maxBlockTime, callback);
}
__name(primeincFindPrimeWithoutWorkers, "primeincFindPrimeWithoutWorkers");
function _primeinc(num, bits, rng2, deltaIdx, mrTests, maxBlockTime, callback) {
var start = +/* @__PURE__ */ new Date();
do {
if (num.bitLength() > bits) {
num = generateRandom(bits, rng2);
}
if (num.isProbablePrime(mrTests)) {
return callback(null, num);
}
num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
} while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime);
forge.util.setImmediate(function() {
_primeinc(num, bits, rng2, deltaIdx, mrTests, maxBlockTime, callback);
});
}
__name(_primeinc, "_primeinc");
function primeincFindPrimeWithWorkers(bits, rng2, options, callback) {
if (typeof Worker === "undefined") {
return primeincFindPrimeWithoutWorkers(bits, rng2, options, callback);
}
var num = generateRandom(bits, rng2);
var numWorkers = options.workers;
var workLoad = options.workLoad || 100;
var range = workLoad * 30 / 8;
var workerScript = options.workerScript || "forge/prime.worker.js";
if (numWorkers === -1) {
return forge.util.estimateCores(function(err, cores) {
if (err) {
cores = 2;
}
numWorkers = cores - 1;
generate2();
});
}
generate2();
function generate2() {
numWorkers = Math.max(1, numWorkers);
var workers = [];
for (var i5 = 0; i5 < numWorkers; ++i5) {
workers[i5] = new Worker(workerScript);
}
var running = numWorkers;
for (var i5 = 0; i5 < numWorkers; ++i5) {
workers[i5].addEventListener("message", workerMessage);
}
var found = false;
function workerMessage(e7) {
if (found) {
return;
}
--running;
var data = e7.data;
if (data.found) {
for (var i6 = 0; i6 < workers.length; ++i6) {
workers[i6].terminate();
}
found = true;
return callback(null, new BigInteger(data.prime, 16));
}
if (num.bitLength() > bits) {
num = generateRandom(bits, rng2);
}
var hex = num.toString(16);
e7.target.postMessage({
hex,
workLoad
});
num.dAddOffset(range, 0);
}
__name(workerMessage, "workerMessage");
}
__name(generate2, "generate");
}
__name(primeincFindPrimeWithWorkers, "primeincFindPrimeWithWorkers");
function generateRandom(bits, rng2) {
var num = new BigInteger(bits, rng2);
var bits1 = bits - 1;
if (!num.testBit(bits1)) {
num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
}
num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
return num;
}
__name(generateRandom, "generateRandom");
function getMillerRabinTests(bits) {
if (bits <= 100) return 27;
if (bits <= 150) return 18;
if (bits <= 200) return 15;
if (bits <= 250) return 12;
if (bits <= 300) return 9;
if (bits <= 350) return 8;
if (bits <= 400) return 7;
if (bits <= 500) return 6;
if (bits <= 600) return 5;
if (bits <= 800) return 4;
if (bits <= 1250) return 3;
return 2;
}
__name(getMillerRabinTests, "getMillerRabinTests");
})();
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/rsa.js
var require_rsa = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/rsa.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_asn1();
require_jsbn();
require_oids();
require_pkcs1();
require_prime();
require_random2();
require_util10();
if (typeof BigInteger === "undefined") {
BigInteger = forge.jsbn.BigInteger;
}
var BigInteger;
var _crypto = forge.util.isNodejs ? require("crypto") : null;
var asn1 = forge.asn1;
var util3 = forge.util;
forge.pki = forge.pki || {};
module3.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};
var pki = forge.pki;
var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
var privateKeyValidator = {
// PrivateKeyInfo
name: "PrivateKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// Version (INTEGER)
name: "PrivateKeyInfo.version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyVersion"
}, {
// privateKeyAlgorithm
name: "PrivateKeyInfo.privateKeyAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "privateKeyOid"
}]
}, {
// PrivateKey
name: "PrivateKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "privateKey"
}]
};
var rsaPrivateKeyValidator = {
// RSAPrivateKey
name: "RSAPrivateKey",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// Version (INTEGER)
name: "RSAPrivateKey.version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyVersion"
}, {
// modulus (n)
name: "RSAPrivateKey.modulus",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyModulus"
}, {
// publicExponent (e)
name: "RSAPrivateKey.publicExponent",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyPublicExponent"
}, {
// privateExponent (d)
name: "RSAPrivateKey.privateExponent",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyPrivateExponent"
}, {
// prime1 (p)
name: "RSAPrivateKey.prime1",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyPrime1"
}, {
// prime2 (q)
name: "RSAPrivateKey.prime2",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyPrime2"
}, {
// exponent1 (d mod (p-1))
name: "RSAPrivateKey.exponent1",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyExponent1"
}, {
// exponent2 (d mod (q-1))
name: "RSAPrivateKey.exponent2",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyExponent2"
}, {
// coefficient ((inverse of q) mod p)
name: "RSAPrivateKey.coefficient",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyCoefficient"
}]
};
var rsaPublicKeyValidator = {
// RSAPublicKey
name: "RSAPublicKey",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// modulus (n)
name: "RSAPublicKey.modulus",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "publicKeyModulus"
}, {
// publicExponent (e)
name: "RSAPublicKey.exponent",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "publicKeyExponent"
}]
};
var publicKeyValidator = forge.pki.rsa.publicKeyValidator = {
name: "SubjectPublicKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "subjectPublicKeyInfo",
value: [{
name: "SubjectPublicKeyInfo.AlgorithmIdentifier",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "publicKeyOid"
}]
}, {
// subjectPublicKey
name: "SubjectPublicKeyInfo.subjectPublicKey",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
value: [{
// RSAPublicKey
name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
optional: true,
captureAsn1: "rsaPublicKey"
}]
}]
};
var digestInfoValidator = {
name: "DigestInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "DigestInfo.DigestAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "DigestInfo.DigestAlgorithm.algorithmIdentifier",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "algorithmIdentifier"
}, {
// NULL paramters
name: "DigestInfo.DigestAlgorithm.parameters",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.NULL,
// captured only to check existence for md2 and md5
capture: "parameters",
optional: true,
constructed: false
}]
}, {
// digest
name: "DigestInfo.digest",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "digest"
}]
};
var emsaPkcs1v15encode = /* @__PURE__ */ __name(function(md) {
var oid;
if (md.algorithm in pki.oids) {
oid = pki.oids[md.algorithm];
} else {
var error2 = new Error("Unknown message digest algorithm.");
error2.algorithm = md.algorithm;
throw error2;
}
var oidBytes = asn1.oidToDer(oid).getBytes();
var digestInfo = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[]
);
var digestAlgorithm = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[]
);
digestAlgorithm.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
oidBytes
));
digestAlgorithm.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.NULL,
false,
""
));
var digest = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
md.digest().getBytes()
);
digestInfo.value.push(digestAlgorithm);
digestInfo.value.push(digest);
return asn1.toDer(digestInfo).getBytes();
}, "emsaPkcs1v15encode");
var _modPow = /* @__PURE__ */ __name(function(x6, key, pub) {
if (pub) {
return x6.modPow(key.e, key.n);
}
if (!key.p || !key.q) {
return x6.modPow(key.d, key.n);
}
if (!key.dP) {
key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));
}
if (!key.dQ) {
key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));
}
if (!key.qInv) {
key.qInv = key.q.modInverse(key.p);
}
var r7;
do {
r7 = new BigInteger(
forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),
16
);
} while (r7.compareTo(key.n) >= 0 || !r7.gcd(key.n).equals(BigInteger.ONE));
x6 = x6.multiply(r7.modPow(key.e, key.n)).mod(key.n);
var xp = x6.mod(key.p).modPow(key.dP, key.p);
var xq = x6.mod(key.q).modPow(key.dQ, key.q);
while (xp.compareTo(xq) < 0) {
xp = xp.add(key.p);
}
var y4 = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq);
y4 = y4.multiply(r7.modInverse(key.n)).mod(key.n);
return y4;
}, "_modPow");
pki.rsa.encrypt = function(m6, key, bt2) {
var pub = bt2;
var eb;
var k6 = Math.ceil(key.n.bitLength() / 8);
if (bt2 !== false && bt2 !== true) {
pub = bt2 === 2;
eb = _encodePkcs1_v1_5(m6, key, bt2);
} else {
eb = forge.util.createBuffer();
eb.putBytes(m6);
}
var x6 = new BigInteger(eb.toHex(), 16);
var y4 = _modPow(x6, key, pub);
var yhex = y4.toString(16);
var ed = forge.util.createBuffer();
var zeros = k6 - Math.ceil(yhex.length / 2);
while (zeros > 0) {
ed.putByte(0);
--zeros;
}
ed.putBytes(forge.util.hexToBytes(yhex));
return ed.getBytes();
};
pki.rsa.decrypt = function(ed, key, pub, ml) {
var k6 = Math.ceil(key.n.bitLength() / 8);
if (ed.length !== k6) {
var error2 = new Error("Encrypted message length is invalid.");
error2.length = ed.length;
error2.expected = k6;
throw error2;
}
var y4 = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);
if (y4.compareTo(key.n) >= 0) {
throw new Error("Encrypted message is invalid.");
}
var x6 = _modPow(y4, key, pub);
var xhex = x6.toString(16);
var eb = forge.util.createBuffer();
var zeros = k6 - Math.ceil(xhex.length / 2);
while (zeros > 0) {
eb.putByte(0);
--zeros;
}
eb.putBytes(forge.util.hexToBytes(xhex));
if (ml !== false) {
return _decodePkcs1_v1_5(eb.getBytes(), key, pub);
}
return eb.getBytes();
};
pki.rsa.createKeyPairGenerationState = function(bits, e7, options) {
if (typeof bits === "string") {
bits = parseInt(bits, 10);
}
bits = bits || 2048;
options = options || {};
var prng = options.prng || forge.random;
var rng2 = {
// x is an array to fill with bytes
nextBytes: /* @__PURE__ */ __name(function(x6) {
var b6 = prng.getBytesSync(x6.length);
for (var i5 = 0; i5 < x6.length; ++i5) {
x6[i5] = b6.charCodeAt(i5);
}
}, "nextBytes")
};
var algorithm = options.algorithm || "PRIMEINC";
var rval;
if (algorithm === "PRIMEINC") {
rval = {
algorithm,
state: 0,
bits,
rng: rng2,
eInt: e7 || 65537,
e: new BigInteger(null),
p: null,
q: null,
qBits: bits >> 1,
pBits: bits - (bits >> 1),
pqState: 0,
num: null,
keys: null
};
rval.e.fromInt(rval.eInt);
} else {
throw new Error("Invalid key generation algorithm: " + algorithm);
}
return rval;
};
pki.rsa.stepKeyPairGenerationState = function(state2, n6) {
if (!("algorithm" in state2)) {
state2.algorithm = "PRIMEINC";
}
var THIRTY = new BigInteger(null);
THIRTY.fromInt(30);
var deltaIdx = 0;
var op_or = /* @__PURE__ */ __name(function(x6, y4) {
return x6 | y4;
}, "op_or");
var t1 = +/* @__PURE__ */ new Date();
var t22;
var total = 0;
while (state2.keys === null && (n6 <= 0 || total < n6)) {
if (state2.state === 0) {
var bits = state2.p === null ? state2.pBits : state2.qBits;
var bits1 = bits - 1;
if (state2.pqState === 0) {
state2.num = new BigInteger(bits, state2.rng);
if (!state2.num.testBit(bits1)) {
state2.num.bitwiseTo(
BigInteger.ONE.shiftLeft(bits1),
op_or,
state2.num
);
}
state2.num.dAddOffset(31 - state2.num.mod(THIRTY).byteValue(), 0);
deltaIdx = 0;
++state2.pqState;
} else if (state2.pqState === 1) {
if (state2.num.bitLength() > bits) {
state2.pqState = 0;
} else if (state2.num.isProbablePrime(
_getMillerRabinTests(state2.num.bitLength())
)) {
++state2.pqState;
} else {
state2.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
}
} else if (state2.pqState === 2) {
state2.pqState = state2.num.subtract(BigInteger.ONE).gcd(state2.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0;
} else if (state2.pqState === 3) {
state2.pqState = 0;
if (state2.p === null) {
state2.p = state2.num;
} else {
state2.q = state2.num;
}
if (state2.p !== null && state2.q !== null) {
++state2.state;
}
state2.num = null;
}
} else if (state2.state === 1) {
if (state2.p.compareTo(state2.q) < 0) {
state2.num = state2.p;
state2.p = state2.q;
state2.q = state2.num;
}
++state2.state;
} else if (state2.state === 2) {
state2.p1 = state2.p.subtract(BigInteger.ONE);
state2.q1 = state2.q.subtract(BigInteger.ONE);
state2.phi = state2.p1.multiply(state2.q1);
++state2.state;
} else if (state2.state === 3) {
if (state2.phi.gcd(state2.e).compareTo(BigInteger.ONE) === 0) {
++state2.state;
} else {
state2.p = null;
state2.q = null;
state2.state = 0;
}
} else if (state2.state === 4) {
state2.n = state2.p.multiply(state2.q);
if (state2.n.bitLength() === state2.bits) {
++state2.state;
} else {
state2.q = null;
state2.state = 0;
}
} else if (state2.state === 5) {
var d6 = state2.e.modInverse(state2.phi);
state2.keys = {
privateKey: pki.rsa.setPrivateKey(
state2.n,
state2.e,
d6,
state2.p,
state2.q,
d6.mod(state2.p1),
d6.mod(state2.q1),
state2.q.modInverse(state2.p)
),
publicKey: pki.rsa.setPublicKey(state2.n, state2.e)
};
}
t22 = +/* @__PURE__ */ new Date();
total += t22 - t1;
t1 = t22;
}
return state2.keys !== null;
};
pki.rsa.generateKeyPair = function(bits, e7, options, callback) {
if (arguments.length === 1) {
if (typeof bits === "object") {
options = bits;
bits = void 0;
} else if (typeof bits === "function") {
callback = bits;
bits = void 0;
}
} else if (arguments.length === 2) {
if (typeof bits === "number") {
if (typeof e7 === "function") {
callback = e7;
e7 = void 0;
} else if (typeof e7 !== "number") {
options = e7;
e7 = void 0;
}
} else {
options = bits;
callback = e7;
bits = void 0;
e7 = void 0;
}
} else if (arguments.length === 3) {
if (typeof e7 === "number") {
if (typeof options === "function") {
callback = options;
options = void 0;
}
} else {
callback = options;
options = e7;
e7 = void 0;
}
}
options = options || {};
if (bits === void 0) {
bits = options.bits || 2048;
}
if (e7 === void 0) {
e7 = options.e || 65537;
}
if (!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e7 === 65537 || e7 === 3)) {
if (callback) {
if (_detectNodeCrypto("generateKeyPair")) {
return _crypto.generateKeyPair("rsa", {
modulusLength: bits,
publicExponent: e7,
publicKeyEncoding: {
type: "spki",
format: "pem"
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem"
}
}, function(err, pub, priv) {
if (err) {
return callback(err);
}
callback(null, {
privateKey: pki.privateKeyFromPem(priv),
publicKey: pki.publicKeyFromPem(pub)
});
});
}
if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) {
return util3.globalScope.crypto.subtle.generateKey({
name: "RSASSA-PKCS1-v1_5",
modulusLength: bits,
publicExponent: _intToUint8Array(e7),
hash: { name: "SHA-256" }
}, true, ["sign", "verify"]).then(function(pair) {
return util3.globalScope.crypto.subtle.exportKey(
"pkcs8",
pair.privateKey
);
}).then(void 0, function(err) {
callback(err);
}).then(function(pkcs8) {
if (pkcs8) {
var privateKey = pki.privateKeyFromAsn1(
asn1.fromDer(forge.util.createBuffer(pkcs8))
);
callback(null, {
privateKey,
publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
});
}
});
}
if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) {
var genOp = util3.globalScope.msCrypto.subtle.generateKey({
name: "RSASSA-PKCS1-v1_5",
modulusLength: bits,
publicExponent: _intToUint8Array(e7),
hash: { name: "SHA-256" }
}, true, ["sign", "verify"]);
genOp.oncomplete = function(e8) {
var pair = e8.target.result;
var exportOp = util3.globalScope.msCrypto.subtle.exportKey(
"pkcs8",
pair.privateKey
);
exportOp.oncomplete = function(e9) {
var pkcs8 = e9.target.result;
var privateKey = pki.privateKeyFromAsn1(
asn1.fromDer(forge.util.createBuffer(pkcs8))
);
callback(null, {
privateKey,
publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
});
};
exportOp.onerror = function(err) {
callback(err);
};
};
genOp.onerror = function(err) {
callback(err);
};
return;
}
} else {
if (_detectNodeCrypto("generateKeyPairSync")) {
var keypair = _crypto.generateKeyPairSync("rsa", {
modulusLength: bits,
publicExponent: e7,
publicKeyEncoding: {
type: "spki",
format: "pem"
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem"
}
});
return {
privateKey: pki.privateKeyFromPem(keypair.privateKey),
publicKey: pki.publicKeyFromPem(keypair.publicKey)
};
}
}
}
var state2 = pki.rsa.createKeyPairGenerationState(bits, e7, options);
if (!callback) {
pki.rsa.stepKeyPairGenerationState(state2, 0);
return state2.keys;
}
_generateKeyPair(state2, options, callback);
};
pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n6, e7) {
var key = {
n: n6,
e: e7
};
key.encrypt = function(data, scheme, schemeOptions) {
if (typeof scheme === "string") {
scheme = scheme.toUpperCase();
} else if (scheme === void 0) {
scheme = "RSAES-PKCS1-V1_5";
}
if (scheme === "RSAES-PKCS1-V1_5") {
scheme = {
encode: /* @__PURE__ */ __name(function(m6, key2, pub) {
return _encodePkcs1_v1_5(m6, key2, 2).getBytes();
}, "encode")
};
} else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") {
scheme = {
encode: /* @__PURE__ */ __name(function(m6, key2) {
return forge.pkcs1.encode_rsa_oaep(key2, m6, schemeOptions);
}, "encode")
};
} else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) {
scheme = { encode: /* @__PURE__ */ __name(function(e9) {
return e9;
}, "encode") };
} else if (typeof scheme === "string") {
throw new Error('Unsupported encryption scheme: "' + scheme + '".');
}
var e8 = scheme.encode(data, key, true);
return pki.rsa.encrypt(e8, key, true);
};
key.verify = function(digest, signature, scheme, options) {
if (typeof scheme === "string") {
scheme = scheme.toUpperCase();
} else if (scheme === void 0) {
scheme = "RSASSA-PKCS1-V1_5";
}
if (options === void 0) {
options = {
_parseAllDigestBytes: true
};
}
if (!("_parseAllDigestBytes" in options)) {
options._parseAllDigestBytes = true;
}
if (scheme === "RSASSA-PKCS1-V1_5") {
scheme = {
verify: /* @__PURE__ */ __name(function(digest2, d7) {
d7 = _decodePkcs1_v1_5(d7, key, true);
var obj = asn1.fromDer(d7, {
parseAllBytes: options._parseAllDigestBytes
});
var capture = {};
var errors = [];
if (!asn1.validate(obj, digestInfoValidator, capture, errors)) {
var error2 = new Error(
"ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value."
);
error2.errors = errors;
throw error2;
}
var oid = asn1.derToOid(capture.algorithmIdentifier);
if (!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids["sha512-224"] || oid === forge.oids["sha512-256"])) {
var error2 = new Error(
"Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier."
);
error2.oid = oid;
throw error2;
}
if (oid === forge.oids.md2 || oid === forge.oids.md5) {
if (!("parameters" in capture)) {
throw new Error(
"ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters."
);
}
}
return digest2 === capture.digest;
}, "verify")
};
} else if (scheme === "NONE" || scheme === "NULL" || scheme === null) {
scheme = {
verify: /* @__PURE__ */ __name(function(digest2, d7) {
d7 = _decodePkcs1_v1_5(d7, key, true);
return digest2 === d7;
}, "verify")
};
}
var d6 = pki.rsa.decrypt(signature, key, true, false);
return scheme.verify(digest, d6, key.n.bitLength());
};
return key;
};
pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(n6, e7, d6, p6, q6, dP, dQ, qInv) {
var key = {
n: n6,
e: e7,
d: d6,
p: p6,
q: q6,
dP,
dQ,
qInv
};
key.decrypt = function(data, scheme, schemeOptions) {
if (typeof scheme === "string") {
scheme = scheme.toUpperCase();
} else if (scheme === void 0) {
scheme = "RSAES-PKCS1-V1_5";
}
var d7 = pki.rsa.decrypt(data, key, false, false);
if (scheme === "RSAES-PKCS1-V1_5") {
scheme = { decode: _decodePkcs1_v1_5 };
} else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") {
scheme = {
decode: /* @__PURE__ */ __name(function(d8, key2) {
return forge.pkcs1.decode_rsa_oaep(key2, d8, schemeOptions);
}, "decode")
};
} else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) {
scheme = { decode: /* @__PURE__ */ __name(function(d8) {
return d8;
}, "decode") };
} else {
throw new Error('Unsupported encryption scheme: "' + scheme + '".');
}
return scheme.decode(d7, key, false);
};
key.sign = function(md, scheme) {
var bt2 = false;
if (typeof scheme === "string") {
scheme = scheme.toUpperCase();
}
if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") {
scheme = { encode: emsaPkcs1v15encode };
bt2 = 1;
} else if (scheme === "NONE" || scheme === "NULL" || scheme === null) {
scheme = { encode: /* @__PURE__ */ __name(function() {
return md;
}, "encode") };
bt2 = 1;
}
var d7 = scheme.encode(md, key.n.bitLength());
return pki.rsa.encrypt(d7, key, bt2);
};
return key;
};
pki.wrapRsaPrivateKey = function(rsaKey) {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version (0)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(0).getBytes()
),
// privateKeyAlgorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.rsaEncryption).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
]),
// PrivateKey
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
asn1.toDer(rsaKey).getBytes()
)
]);
};
pki.privateKeyFromAsn1 = function(obj) {
var capture = {};
var errors = [];
if (asn1.validate(obj, privateKeyValidator, capture, errors)) {
obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));
}
capture = {};
errors = [];
if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {
var error2 = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");
error2.errors = errors;
throw error2;
}
var n6, e7, d6, p6, q6, dP, dQ, qInv;
n6 = forge.util.createBuffer(capture.privateKeyModulus).toHex();
e7 = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();
d6 = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
p6 = forge.util.createBuffer(capture.privateKeyPrime1).toHex();
q6 = forge.util.createBuffer(capture.privateKeyPrime2).toHex();
dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();
dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();
qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();
return pki.setRsaPrivateKey(
new BigInteger(n6, 16),
new BigInteger(e7, 16),
new BigInteger(d6, 16),
new BigInteger(p6, 16),
new BigInteger(q6, 16),
new BigInteger(dP, 16),
new BigInteger(dQ, 16),
new BigInteger(qInv, 16)
);
};
pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version (0 = only 2 primes, 1 multiple primes)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(0).getBytes()
),
// modulus (n)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.n)
),
// publicExponent (e)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.e)
),
// privateExponent (d)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.d)
),
// privateKeyPrime1 (p)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.p)
),
// privateKeyPrime2 (q)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.q)
),
// privateKeyExponent1 (dP)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.dP)
),
// privateKeyExponent2 (dQ)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.dQ)
),
// coefficient (qInv)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.qInv)
)
]);
};
pki.publicKeyFromAsn1 = function(obj) {
var capture = {};
var errors = [];
if (asn1.validate(obj, publicKeyValidator, capture, errors)) {
var oid = asn1.derToOid(capture.publicKeyOid);
if (oid !== pki.oids.rsaEncryption) {
var error2 = new Error("Cannot read public key. Unknown OID.");
error2.oid = oid;
throw error2;
}
obj = capture.rsaPublicKey;
}
errors = [];
if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {
var error2 = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");
error2.errors = errors;
throw error2;
}
var n6 = forge.util.createBuffer(capture.publicKeyModulus).toHex();
var e7 = forge.util.createBuffer(capture.publicKeyExponent).toHex();
return pki.setRsaPublicKey(
new BigInteger(n6, 16),
new BigInteger(e7, 16)
);
};
pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// AlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.rsaEncryption).getBytes()
),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
]),
// subjectPublicKey
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [
pki.publicKeyToRSAPublicKey(key)
])
]);
};
pki.publicKeyToRSAPublicKey = function(key) {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// modulus (n)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.n)
),
// publicExponent (e)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
_bnToBytes(key.e)
)
]);
};
function _encodePkcs1_v1_5(m6, key, bt2) {
var eb = forge.util.createBuffer();
var k6 = Math.ceil(key.n.bitLength() / 8);
if (m6.length > k6 - 11) {
var error2 = new Error("Message is too long for PKCS#1 v1.5 padding.");
error2.length = m6.length;
error2.max = k6 - 11;
throw error2;
}
eb.putByte(0);
eb.putByte(bt2);
var padNum = k6 - 3 - m6.length;
var padByte;
if (bt2 === 0 || bt2 === 1) {
padByte = bt2 === 0 ? 0 : 255;
for (var i5 = 0; i5 < padNum; ++i5) {
eb.putByte(padByte);
}
} else {
while (padNum > 0) {
var numZeros = 0;
var padBytes = forge.random.getBytes(padNum);
for (var i5 = 0; i5 < padNum; ++i5) {
padByte = padBytes.charCodeAt(i5);
if (padByte === 0) {
++numZeros;
} else {
eb.putByte(padByte);
}
}
padNum = numZeros;
}
}
eb.putByte(0);
eb.putBytes(m6);
return eb;
}
__name(_encodePkcs1_v1_5, "_encodePkcs1_v1_5");
function _decodePkcs1_v1_5(em, key, pub, ml) {
var k6 = Math.ceil(key.n.bitLength() / 8);
var eb = forge.util.createBuffer(em);
var first = eb.getByte();
var bt2 = eb.getByte();
if (first !== 0 || pub && bt2 !== 0 && bt2 !== 1 || !pub && bt2 != 2 || pub && bt2 === 0 && typeof ml === "undefined") {
throw new Error("Encryption block is invalid.");
}
var padNum = 0;
if (bt2 === 0) {
padNum = k6 - 3 - ml;
for (var i5 = 0; i5 < padNum; ++i5) {
if (eb.getByte() !== 0) {
throw new Error("Encryption block is invalid.");
}
}
} else if (bt2 === 1) {
padNum = 0;
while (eb.length() > 1) {
if (eb.getByte() !== 255) {
--eb.read;
break;
}
++padNum;
}
} else if (bt2 === 2) {
padNum = 0;
while (eb.length() > 1) {
if (eb.getByte() === 0) {
--eb.read;
break;
}
++padNum;
}
}
var zero = eb.getByte();
if (zero !== 0 || padNum !== k6 - 3 - eb.length()) {
throw new Error("Encryption block is invalid.");
}
return eb.getBytes();
}
__name(_decodePkcs1_v1_5, "_decodePkcs1_v1_5");
function _generateKeyPair(state2, options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
}
options = options || {};
var opts = {
algorithm: {
name: options.algorithm || "PRIMEINC",
options: {
workers: options.workers || 2,
workLoad: options.workLoad || 100,
workerScript: options.workerScript
}
}
};
if ("prng" in options) {
opts.prng = options.prng;
}
generate2();
function generate2() {
getPrime(state2.pBits, function(err, num) {
if (err) {
return callback(err);
}
state2.p = num;
if (state2.q !== null) {
return finish(err, state2.q);
}
getPrime(state2.qBits, finish);
});
}
__name(generate2, "generate");
function getPrime(bits, callback2) {
forge.prime.generateProbablePrime(bits, opts, callback2);
}
__name(getPrime, "getPrime");
function finish(err, num) {
if (err) {
return callback(err);
}
state2.q = num;
if (state2.p.compareTo(state2.q) < 0) {
var tmp = state2.p;
state2.p = state2.q;
state2.q = tmp;
}
if (state2.p.subtract(BigInteger.ONE).gcd(state2.e).compareTo(BigInteger.ONE) !== 0) {
state2.p = null;
generate2();
return;
}
if (state2.q.subtract(BigInteger.ONE).gcd(state2.e).compareTo(BigInteger.ONE) !== 0) {
state2.q = null;
getPrime(state2.qBits, finish);
return;
}
state2.p1 = state2.p.subtract(BigInteger.ONE);
state2.q1 = state2.q.subtract(BigInteger.ONE);
state2.phi = state2.p1.multiply(state2.q1);
if (state2.phi.gcd(state2.e).compareTo(BigInteger.ONE) !== 0) {
state2.p = state2.q = null;
generate2();
return;
}
state2.n = state2.p.multiply(state2.q);
if (state2.n.bitLength() !== state2.bits) {
state2.q = null;
getPrime(state2.qBits, finish);
return;
}
var d6 = state2.e.modInverse(state2.phi);
state2.keys = {
privateKey: pki.rsa.setPrivateKey(
state2.n,
state2.e,
d6,
state2.p,
state2.q,
d6.mod(state2.p1),
d6.mod(state2.q1),
state2.q.modInverse(state2.p)
),
publicKey: pki.rsa.setPublicKey(state2.n, state2.e)
};
callback(null, state2.keys);
}
__name(finish, "finish");
}
__name(_generateKeyPair, "_generateKeyPair");
function _bnToBytes(b6) {
var hex = b6.toString(16);
if (hex[0] >= "8") {
hex = "00" + hex;
}
var bytes = forge.util.hexToBytes(hex);
if (bytes.length > 1 && // leading 0x00 for positive integer
(bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer
bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) {
return bytes.substr(1);
}
return bytes;
}
__name(_bnToBytes, "_bnToBytes");
function _getMillerRabinTests(bits) {
if (bits <= 100) return 27;
if (bits <= 150) return 18;
if (bits <= 200) return 15;
if (bits <= 250) return 12;
if (bits <= 300) return 9;
if (bits <= 350) return 8;
if (bits <= 400) return 7;
if (bits <= 500) return 6;
if (bits <= 600) return 5;
if (bits <= 800) return 4;
if (bits <= 1250) return 3;
return 2;
}
__name(_getMillerRabinTests, "_getMillerRabinTests");
function _detectNodeCrypto(fn2) {
return forge.util.isNodejs && typeof _crypto[fn2] === "function";
}
__name(_detectNodeCrypto, "_detectNodeCrypto");
function _detectSubtleCrypto(fn2) {
return typeof util3.globalScope !== "undefined" && typeof util3.globalScope.crypto === "object" && typeof util3.globalScope.crypto.subtle === "object" && typeof util3.globalScope.crypto.subtle[fn2] === "function";
}
__name(_detectSubtleCrypto, "_detectSubtleCrypto");
function _detectSubtleMsCrypto(fn2) {
return typeof util3.globalScope !== "undefined" && typeof util3.globalScope.msCrypto === "object" && typeof util3.globalScope.msCrypto.subtle === "object" && typeof util3.globalScope.msCrypto.subtle[fn2] === "function";
}
__name(_detectSubtleMsCrypto, "_detectSubtleMsCrypto");
function _intToUint8Array(x6) {
var bytes = forge.util.hexToBytes(x6.toString(16));
var buffer = new Uint8Array(bytes.length);
for (var i5 = 0; i5 < bytes.length; ++i5) {
buffer[i5] = bytes.charCodeAt(i5);
}
return buffer;
}
__name(_intToUint8Array, "_intToUint8Array");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pbe.js
var require_pbe = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pbe.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_aes();
require_asn1();
require_des();
require_md();
require_oids();
require_pbkdf2();
require_pem();
require_random2();
require_rc2();
require_rsa();
require_util10();
if (typeof BigInteger === "undefined") {
BigInteger = forge.jsbn.BigInteger;
}
var BigInteger;
var asn1 = forge.asn1;
var pki = forge.pki = forge.pki || {};
module3.exports = pki.pbe = forge.pbe = forge.pbe || {};
var oids = pki.oids;
var encryptedPrivateKeyValidator = {
name: "EncryptedPrivateKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "EncryptedPrivateKeyInfo.encryptionAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "encryptionOid"
}, {
name: "AlgorithmIdentifier.parameters",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "encryptionParams"
}]
}, {
// encryptedData
name: "EncryptedPrivateKeyInfo.encryptedData",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "encryptedData"
}]
};
var PBES2AlgorithmsValidator = {
name: "PBES2Algorithms",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "PBES2Algorithms.keyDerivationFunc",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "PBES2Algorithms.keyDerivationFunc.oid",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "kdfOid"
}, {
name: "PBES2Algorithms.params",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "PBES2Algorithms.params.salt",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "kdfSalt"
}, {
name: "PBES2Algorithms.params.iterationCount",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "kdfIterationCount"
}, {
name: "PBES2Algorithms.params.keyLength",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
optional: true,
capture: "keyLength"
}, {
// prf
name: "PBES2Algorithms.params.prf",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
optional: true,
value: [{
name: "PBES2Algorithms.params.prf.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "prfOid"
}]
}]
}]
}, {
name: "PBES2Algorithms.encryptionScheme",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "PBES2Algorithms.encryptionScheme.oid",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "encOid"
}, {
name: "PBES2Algorithms.encryptionScheme.iv",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "encIv"
}]
}]
};
var pkcs12PbeParamsValidator = {
name: "pkcs-12PbeParams",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "pkcs-12PbeParams.salt",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "salt"
}, {
name: "pkcs-12PbeParams.iterations",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "iterations"
}]
};
pki.encryptPrivateKeyInfo = function(obj, password, options) {
options = options || {};
options.saltSize = options.saltSize || 8;
options.count = options.count || 2048;
options.algorithm = options.algorithm || "aes128";
options.prfAlgorithm = options.prfAlgorithm || "sha1";
var salt = forge.random.getBytesSync(options.saltSize);
var count = options.count;
var countBytes = asn1.integerToDer(count);
var dkLen;
var encryptionAlgorithm;
var encryptedData;
if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") {
var ivLen, encOid, cipherFn;
switch (options.algorithm) {
case "aes128":
dkLen = 16;
ivLen = 16;
encOid = oids["aes128-CBC"];
cipherFn = forge.aes.createEncryptionCipher;
break;
case "aes192":
dkLen = 24;
ivLen = 16;
encOid = oids["aes192-CBC"];
cipherFn = forge.aes.createEncryptionCipher;
break;
case "aes256":
dkLen = 32;
ivLen = 16;
encOid = oids["aes256-CBC"];
cipherFn = forge.aes.createEncryptionCipher;
break;
case "des":
dkLen = 8;
ivLen = 8;
encOid = oids["desCBC"];
cipherFn = forge.des.createEncryptionCipher;
break;
default:
var error2 = new Error("Cannot encrypt private key. Unknown encryption algorithm.");
error2.algorithm = options.algorithm;
throw error2;
}
var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase();
var md = prfAlgorithmToMessageDigest(prfAlgorithm);
var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);
var iv = forge.random.getBytesSync(ivLen);
var cipher = cipherFn(dk);
cipher.start(iv);
cipher.update(asn1.toDer(obj));
cipher.finish();
encryptedData = cipher.output.getBytes();
var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);
encryptionAlgorithm = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(oids["pkcs5PBES2"]).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// keyDerivationFunc
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes()
),
// PBKDF2-params
params
]),
// encryptionScheme
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(encOid).getBytes()
),
// iv
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
iv
)
])
])
]
);
} else if (options.algorithm === "3des") {
dkLen = 24;
var saltBytes = new forge.util.ByteBuffer(salt);
var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);
var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);
var cipher = forge.des.createEncryptionCipher(dk);
cipher.start(iv);
cipher.update(asn1.toDer(obj));
cipher.finish();
encryptedData = cipher.output.getBytes();
encryptionAlgorithm = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()
),
// pkcs-12PbeParams
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// salt
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),
// iteration count
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
countBytes.getBytes()
)
])
]
);
} else {
var error2 = new Error("Cannot encrypt private key. Unknown encryption algorithm.");
error2.algorithm = options.algorithm;
throw error2;
}
var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// encryptionAlgorithm
encryptionAlgorithm,
// encryptedData
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
encryptedData
)
]);
return rval;
};
pki.decryptPrivateKeyInfo = function(obj, password) {
var rval = null;
var capture = {};
var errors = [];
if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {
var error2 = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
error2.errors = errors;
throw error2;
}
var oid = asn1.derToOid(capture.encryptionOid);
var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);
var encrypted = forge.util.createBuffer(capture.encryptedData);
cipher.update(encrypted);
if (cipher.finish()) {
rval = asn1.fromDer(cipher.output);
}
return rval;
};
pki.encryptedPrivateKeyToPem = function(epki, maxline) {
var msg = {
type: "ENCRYPTED PRIVATE KEY",
body: asn1.toDer(epki).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
pki.encryptedPrivateKeyFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "ENCRYPTED PRIVATE KEY") {
var error2 = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");
}
return asn1.fromDer(msg.body);
};
pki.encryptRsaPrivateKey = function(rsaKey, password, options) {
options = options || {};
if (!options.legacy) {
var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));
rval = pki.encryptPrivateKeyInfo(rval, password, options);
return pki.encryptedPrivateKeyToPem(rval);
}
var algorithm;
var iv;
var dkLen;
var cipherFn;
switch (options.algorithm) {
case "aes128":
algorithm = "AES-128-CBC";
dkLen = 16;
iv = forge.random.getBytesSync(16);
cipherFn = forge.aes.createEncryptionCipher;
break;
case "aes192":
algorithm = "AES-192-CBC";
dkLen = 24;
iv = forge.random.getBytesSync(16);
cipherFn = forge.aes.createEncryptionCipher;
break;
case "aes256":
algorithm = "AES-256-CBC";
dkLen = 32;
iv = forge.random.getBytesSync(16);
cipherFn = forge.aes.createEncryptionCipher;
break;
case "3des":
algorithm = "DES-EDE3-CBC";
dkLen = 24;
iv = forge.random.getBytesSync(8);
cipherFn = forge.des.createEncryptionCipher;
break;
case "des":
algorithm = "DES-CBC";
dkLen = 8;
iv = forge.random.getBytesSync(8);
cipherFn = forge.des.createEncryptionCipher;
break;
default:
var error2 = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".');
error2.algorithm = options.algorithm;
throw error2;
}
var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
var cipher = cipherFn(dk);
cipher.start(iv);
cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));
cipher.finish();
var msg = {
type: "RSA PRIVATE KEY",
procType: {
version: "4",
type: "ENCRYPTED"
},
dekInfo: {
algorithm,
parameters: forge.util.bytesToHex(iv).toUpperCase()
},
body: cipher.output.getBytes()
};
return forge.pem.encode(msg);
};
pki.decryptRsaPrivateKey = function(pem, password) {
var rval = null;
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") {
var error2 = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');
error2.headerType = error2;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
var dkLen;
var cipherFn;
switch (msg.dekInfo.algorithm) {
case "DES-CBC":
dkLen = 8;
cipherFn = forge.des.createDecryptionCipher;
break;
case "DES-EDE3-CBC":
dkLen = 24;
cipherFn = forge.des.createDecryptionCipher;
break;
case "AES-128-CBC":
dkLen = 16;
cipherFn = forge.aes.createDecryptionCipher;
break;
case "AES-192-CBC":
dkLen = 24;
cipherFn = forge.aes.createDecryptionCipher;
break;
case "AES-256-CBC":
dkLen = 32;
cipherFn = forge.aes.createDecryptionCipher;
break;
case "RC2-40-CBC":
dkLen = 5;
cipherFn = /* @__PURE__ */ __name(function(key) {
return forge.rc2.createDecryptionCipher(key, 40);
}, "cipherFn");
break;
case "RC2-64-CBC":
dkLen = 8;
cipherFn = /* @__PURE__ */ __name(function(key) {
return forge.rc2.createDecryptionCipher(key, 64);
}, "cipherFn");
break;
case "RC2-128-CBC":
dkLen = 16;
cipherFn = /* @__PURE__ */ __name(function(key) {
return forge.rc2.createDecryptionCipher(key, 128);
}, "cipherFn");
break;
default:
var error2 = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".');
error2.algorithm = msg.dekInfo.algorithm;
throw error2;
}
var iv = forge.util.hexToBytes(msg.dekInfo.parameters);
var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
var cipher = cipherFn(dk);
cipher.start(iv);
cipher.update(forge.util.createBuffer(msg.body));
if (cipher.finish()) {
rval = cipher.output.getBytes();
} else {
return rval;
}
} else {
rval = msg.body;
}
if (msg.type === "ENCRYPTED PRIVATE KEY") {
rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);
} else {
rval = asn1.fromDer(rval);
}
if (rval !== null) {
rval = pki.privateKeyFromAsn1(rval);
}
return rval;
};
pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n6, md) {
var j6, l6;
if (typeof md === "undefined" || md === null) {
if (!("sha1" in forge.md)) {
throw new Error('"sha1" hash algorithm unavailable.');
}
md = forge.md.sha1.create();
}
var u5 = md.digestLength;
var v7 = md.blockLength;
var result = new forge.util.ByteBuffer();
var passBuf = new forge.util.ByteBuffer();
if (password !== null && password !== void 0) {
for (l6 = 0; l6 < password.length; l6++) {
passBuf.putInt16(password.charCodeAt(l6));
}
passBuf.putInt16(0);
}
var p6 = passBuf.length();
var s5 = salt.length();
var D3 = new forge.util.ByteBuffer();
D3.fillWithByte(id, v7);
var Slen = v7 * Math.ceil(s5 / v7);
var S4 = new forge.util.ByteBuffer();
for (l6 = 0; l6 < Slen; l6++) {
S4.putByte(salt.at(l6 % s5));
}
var Plen = v7 * Math.ceil(p6 / v7);
var P3 = new forge.util.ByteBuffer();
for (l6 = 0; l6 < Plen; l6++) {
P3.putByte(passBuf.at(l6 % p6));
}
var I4 = S4;
I4.putBuffer(P3);
var c6 = Math.ceil(n6 / u5);
for (var i5 = 1; i5 <= c6; i5++) {
var buf = new forge.util.ByteBuffer();
buf.putBytes(D3.bytes());
buf.putBytes(I4.bytes());
for (var round = 0; round < iter; round++) {
md.start();
md.update(buf.getBytes());
buf = md.digest();
}
var B3 = new forge.util.ByteBuffer();
for (l6 = 0; l6 < v7; l6++) {
B3.putByte(buf.at(l6 % u5));
}
var k6 = Math.ceil(s5 / v7) + Math.ceil(p6 / v7);
var Inew = new forge.util.ByteBuffer();
for (j6 = 0; j6 < k6; j6++) {
var chunk = new forge.util.ByteBuffer(I4.getBytes(v7));
var x6 = 511;
for (l6 = B3.length() - 1; l6 >= 0; l6--) {
x6 = x6 >> 8;
x6 += B3.at(l6) + chunk.at(l6);
chunk.setAt(l6, x6 & 255);
}
Inew.putBuffer(chunk);
}
I4 = Inew;
result.putBuffer(buf);
}
result.truncate(result.length() - n6);
return result;
};
pki.pbe.getCipher = function(oid, params, password) {
switch (oid) {
case pki.oids["pkcs5PBES2"]:
return pki.pbe.getCipherForPBES2(oid, params, password);
case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:
case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:
return pki.pbe.getCipherForPKCS12PBE(oid, params, password);
default:
var error2 = new Error("Cannot read encrypted PBE data block. Unsupported OID.");
error2.oid = oid;
error2.supportedOids = [
"pkcs5PBES2",
"pbeWithSHAAnd3-KeyTripleDES-CBC",
"pbewithSHAAnd40BitRC2-CBC"
];
throw error2;
}
};
pki.pbe.getCipherForPBES2 = function(oid, params, password) {
var capture = {};
var errors = [];
if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {
var error2 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
error2.errors = errors;
throw error2;
}
oid = asn1.derToOid(capture.kdfOid);
if (oid !== pki.oids["pkcs5PBKDF2"]) {
var error2 = new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");
error2.oid = oid;
error2.supportedOids = ["pkcs5PBKDF2"];
throw error2;
}
oid = asn1.derToOid(capture.encOid);
if (oid !== pki.oids["aes128-CBC"] && oid !== pki.oids["aes192-CBC"] && oid !== pki.oids["aes256-CBC"] && oid !== pki.oids["des-EDE3-CBC"] && oid !== pki.oids["desCBC"]) {
var error2 = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");
error2.oid = oid;
error2.supportedOids = [
"aes128-CBC",
"aes192-CBC",
"aes256-CBC",
"des-EDE3-CBC",
"desCBC"
];
throw error2;
}
var salt = capture.kdfSalt;
var count = forge.util.createBuffer(capture.kdfIterationCount);
count = count.getInt(count.length() << 3);
var dkLen;
var cipherFn;
switch (pki.oids[oid]) {
case "aes128-CBC":
dkLen = 16;
cipherFn = forge.aes.createDecryptionCipher;
break;
case "aes192-CBC":
dkLen = 24;
cipherFn = forge.aes.createDecryptionCipher;
break;
case "aes256-CBC":
dkLen = 32;
cipherFn = forge.aes.createDecryptionCipher;
break;
case "des-EDE3-CBC":
dkLen = 24;
cipherFn = forge.des.createDecryptionCipher;
break;
case "desCBC":
dkLen = 8;
cipherFn = forge.des.createDecryptionCipher;
break;
}
var md = prfOidToMessageDigest(capture.prfOid);
var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);
var iv = capture.encIv;
var cipher = cipherFn(dk);
cipher.start(iv);
return cipher;
};
pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {
var capture = {};
var errors = [];
if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {
var error2 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
error2.errors = errors;
throw error2;
}
var salt = forge.util.createBuffer(capture.salt);
var count = forge.util.createBuffer(capture.iterations);
count = count.getInt(count.length() << 3);
var dkLen, dIvLen, cipherFn;
switch (oid) {
case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:
dkLen = 24;
dIvLen = 8;
cipherFn = forge.des.startDecrypting;
break;
case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:
dkLen = 5;
dIvLen = 8;
cipherFn = /* @__PURE__ */ __name(function(key2, iv2) {
var cipher = forge.rc2.createDecryptionCipher(key2, 40);
cipher.start(iv2, null);
return cipher;
}, "cipherFn");
break;
default:
var error2 = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");
error2.oid = oid;
throw error2;
}
var md = prfOidToMessageDigest(capture.prfOid);
var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);
md.start();
var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);
return cipherFn(key, iv);
};
pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {
if (typeof md === "undefined" || md === null) {
if (!("md5" in forge.md)) {
throw new Error('"md5" hash algorithm unavailable.');
}
md = forge.md.md5.create();
}
if (salt === null) {
salt = "";
}
var digests = [hash(md, password + salt)];
for (var length = 16, i5 = 1; length < dkLen; ++i5, length += 16) {
digests.push(hash(md, digests[i5 - 1] + password + salt));
}
return digests.join("").substr(0, dkLen);
};
function hash(md, bytes) {
return md.start().update(bytes).digest().getBytes();
}
__name(hash, "hash");
function prfOidToMessageDigest(prfOid) {
var prfAlgorithm;
if (!prfOid) {
prfAlgorithm = "hmacWithSHA1";
} else {
prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];
if (!prfAlgorithm) {
var error2 = new Error("Unsupported PRF OID.");
error2.oid = prfOid;
error2.supported = [
"hmacWithSHA1",
"hmacWithSHA224",
"hmacWithSHA256",
"hmacWithSHA384",
"hmacWithSHA512"
];
throw error2;
}
}
return prfAlgorithmToMessageDigest(prfAlgorithm);
}
__name(prfOidToMessageDigest, "prfOidToMessageDigest");
function prfAlgorithmToMessageDigest(prfAlgorithm) {
var factory = forge.md;
switch (prfAlgorithm) {
case "hmacWithSHA224":
factory = forge.md.sha512;
case "hmacWithSHA1":
case "hmacWithSHA256":
case "hmacWithSHA384":
case "hmacWithSHA512":
prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();
break;
default:
var error2 = new Error("Unsupported PRF algorithm.");
error2.algorithm = prfAlgorithm;
error2.supported = [
"hmacWithSHA1",
"hmacWithSHA224",
"hmacWithSHA256",
"hmacWithSHA384",
"hmacWithSHA512"
];
throw error2;
}
if (!factory || !(prfAlgorithm in factory)) {
throw new Error("Unknown hash algorithm: " + prfAlgorithm);
}
return factory[prfAlgorithm].create();
}
__name(prfAlgorithmToMessageDigest, "prfAlgorithmToMessageDigest");
function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {
var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// salt
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
salt
),
// iteration count
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
countBytes.getBytes()
)
]);
if (prfAlgorithm !== "hmacWithSHA1") {
params.value.push(
// key length
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
forge.util.hexToBytes(dkLen.toString(16))
),
// AlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()
),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
])
);
}
return params;
}
__name(createPbkdf2Params, "createPbkdf2Params");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs7asn1.js
var require_pkcs7asn1 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs7asn1.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_asn1();
require_util10();
var asn1 = forge.asn1;
var p7v = module3.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};
forge.pkcs7 = forge.pkcs7 || {};
forge.pkcs7.asn1 = p7v;
var contentInfoValidator = {
name: "ContentInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "ContentInfo.ContentType",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "contentType"
}, {
name: "ContentInfo.content",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
optional: true,
captureAsn1: "content"
}]
};
p7v.contentInfoValidator = contentInfoValidator;
var encryptedContentInfoValidator = {
name: "EncryptedContentInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "EncryptedContentInfo.contentType",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "contentType"
}, {
name: "EncryptedContentInfo.contentEncryptionAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "encAlgorithm"
}, {
name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter",
tagClass: asn1.Class.UNIVERSAL,
captureAsn1: "encParameter"
}]
}, {
name: "EncryptedContentInfo.encryptedContent",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
/* The PKCS#7 structure output by OpenSSL somewhat differs from what
* other implementations do generate.
*
* OpenSSL generates a structure like this:
* SEQUENCE {
* ...
* [0]
* 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38
* C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45
* ...
* }
*
* Whereas other implementations (and this PKCS#7 module) generate:
* SEQUENCE {
* ...
* [0] {
* OCTET STRING
* 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38
* C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45
* ...
* }
* }
*
* In order to support both, we just capture the context specific
* field here. The OCTET STRING bit is removed below.
*/
capture: "encryptedContent",
captureAsn1: "encryptedContentAsn1"
}]
};
p7v.envelopedDataValidator = {
name: "EnvelopedData",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "EnvelopedData.Version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "version"
}, {
name: "EnvelopedData.RecipientInfos",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
constructed: true,
captureAsn1: "recipientInfos"
}].concat(encryptedContentInfoValidator)
};
p7v.encryptedDataValidator = {
name: "EncryptedData",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "EncryptedData.Version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "version"
}].concat(encryptedContentInfoValidator)
};
var signerValidator = {
name: "SignerInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "SignerInfo.version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false
}, {
name: "SignerInfo.issuerAndSerialNumber",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "SignerInfo.issuerAndSerialNumber.issuer",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "issuer"
}, {
name: "SignerInfo.issuerAndSerialNumber.serialNumber",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "serial"
}]
}, {
name: "SignerInfo.digestAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "SignerInfo.digestAlgorithm.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "digestAlgorithm"
}, {
name: "SignerInfo.digestAlgorithm.parameter",
tagClass: asn1.Class.UNIVERSAL,
constructed: false,
captureAsn1: "digestParameter",
optional: true
}]
}, {
name: "SignerInfo.authenticatedAttributes",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
optional: true,
capture: "authenticatedAttributes"
}, {
name: "SignerInfo.digestEncryptionAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
capture: "signatureAlgorithm"
}, {
name: "SignerInfo.encryptedDigest",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "signature"
}, {
name: "SignerInfo.unauthenticatedAttributes",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 1,
constructed: true,
optional: true,
capture: "unauthenticatedAttributes"
}]
};
p7v.signedDataValidator = {
name: "SignedData",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [
{
name: "SignedData.Version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "version"
},
{
name: "SignedData.DigestAlgorithms",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
constructed: true,
captureAsn1: "digestAlgorithms"
},
contentInfoValidator,
{
name: "SignedData.Certificates",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
optional: true,
captureAsn1: "certificates"
},
{
name: "SignedData.CertificateRevocationLists",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 1,
optional: true,
captureAsn1: "crls"
},
{
name: "SignedData.SignerInfos",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
capture: "signerInfos",
optional: true,
value: [signerValidator]
}
]
};
p7v.recipientInfoValidator = {
name: "RecipientInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "RecipientInfo.version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "version"
}, {
name: "RecipientInfo.issuerAndSerial",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "RecipientInfo.issuerAndSerial.issuer",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "issuer"
}, {
name: "RecipientInfo.issuerAndSerial.serialNumber",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "serial"
}]
}, {
name: "RecipientInfo.keyEncryptionAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "RecipientInfo.keyEncryptionAlgorithm.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "encAlgorithm"
}, {
name: "RecipientInfo.keyEncryptionAlgorithm.parameter",
tagClass: asn1.Class.UNIVERSAL,
constructed: false,
captureAsn1: "encParameter",
optional: true
}]
}, {
name: "RecipientInfo.encryptedKey",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "encKey"
}]
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/mgf1.js
var require_mgf1 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/mgf1.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
forge.mgf = forge.mgf || {};
var mgf1 = module3.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};
mgf1.create = function(md) {
var mgf = {
/**
* Generate mask of specified length.
*
* @param {String} seed The seed for mask generation.
* @param maskLen Number of bytes to generate.
* @return {String} The generated mask.
*/
generate: /* @__PURE__ */ __name(function(seed, maskLen) {
var t7 = new forge.util.ByteBuffer();
var len = Math.ceil(maskLen / md.digestLength);
for (var i5 = 0; i5 < len; i5++) {
var c6 = new forge.util.ByteBuffer();
c6.putInt32(i5);
md.start();
md.update(seed + c6.getBytes());
t7.putBuffer(md.digest());
}
t7.truncate(t7.length() - maskLen);
return t7.getBytes();
}, "generate")
};
return mgf;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/mgf.js
var require_mgf = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/mgf.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_mgf1();
module3.exports = forge.mgf = forge.mgf || {};
forge.mgf.mgf1 = forge.mgf1;
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pss.js
var require_pss = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pss.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_random2();
require_util10();
var pss = module3.exports = forge.pss = forge.pss || {};
pss.create = function(options) {
if (arguments.length === 3) {
options = {
md: arguments[0],
mgf: arguments[1],
saltLength: arguments[2]
};
}
var hash = options.md;
var mgf = options.mgf;
var hLen = hash.digestLength;
var salt_ = options.salt || null;
if (typeof salt_ === "string") {
salt_ = forge.util.createBuffer(salt_);
}
var sLen;
if ("saltLength" in options) {
sLen = options.saltLength;
} else if (salt_ !== null) {
sLen = salt_.length();
} else {
throw new Error("Salt length not specified or specific salt not given.");
}
if (salt_ !== null && salt_.length() !== sLen) {
throw new Error("Given salt length does not match length of given salt.");
}
var prng = options.prng || forge.random;
var pssobj = {};
pssobj.encode = function(md, modBits) {
var i5;
var emBits = modBits - 1;
var emLen = Math.ceil(emBits / 8);
var mHash = md.digest().getBytes();
if (emLen < hLen + sLen + 2) {
throw new Error("Message is too long to encrypt.");
}
var salt;
if (salt_ === null) {
salt = prng.getBytesSync(sLen);
} else {
salt = salt_.bytes();
}
var m_ = new forge.util.ByteBuffer();
m_.fillWithByte(0, 8);
m_.putBytes(mHash);
m_.putBytes(salt);
hash.start();
hash.update(m_.getBytes());
var h6 = hash.digest().getBytes();
var ps = new forge.util.ByteBuffer();
ps.fillWithByte(0, emLen - sLen - hLen - 2);
ps.putByte(1);
ps.putBytes(salt);
var db = ps.getBytes();
var maskLen = emLen - hLen - 1;
var dbMask = mgf.generate(h6, maskLen);
var maskedDB = "";
for (i5 = 0; i5 < maskLen; i5++) {
maskedDB += String.fromCharCode(db.charCodeAt(i5) ^ dbMask.charCodeAt(i5));
}
var mask = 65280 >> 8 * emLen - emBits & 255;
maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1);
return maskedDB + h6 + String.fromCharCode(188);
};
pssobj.verify = function(mHash, em, modBits) {
var i5;
var emBits = modBits - 1;
var emLen = Math.ceil(emBits / 8);
em = em.substr(-emLen);
if (emLen < hLen + sLen + 2) {
throw new Error("Inconsistent parameters to PSS signature verification.");
}
if (em.charCodeAt(emLen - 1) !== 188) {
throw new Error("Encoded message does not end in 0xBC.");
}
var maskLen = emLen - hLen - 1;
var maskedDB = em.substr(0, maskLen);
var h6 = em.substr(maskLen, hLen);
var mask = 65280 >> 8 * emLen - emBits & 255;
if ((maskedDB.charCodeAt(0) & mask) !== 0) {
throw new Error("Bits beyond keysize not zero as expected.");
}
var dbMask = mgf.generate(h6, maskLen);
var db = "";
for (i5 = 0; i5 < maskLen; i5++) {
db += String.fromCharCode(maskedDB.charCodeAt(i5) ^ dbMask.charCodeAt(i5));
}
db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);
var checkLen = emLen - hLen - sLen - 2;
for (i5 = 0; i5 < checkLen; i5++) {
if (db.charCodeAt(i5) !== 0) {
throw new Error("Leftmost octets not zero as expected");
}
}
if (db.charCodeAt(checkLen) !== 1) {
throw new Error("Inconsistent PSS signature, 0x01 marker not found");
}
var salt = db.substr(-sLen);
var m_ = new forge.util.ByteBuffer();
m_.fillWithByte(0, 8);
m_.putBytes(mHash);
m_.putBytes(salt);
hash.start();
hash.update(m_.getBytes());
var h_ = hash.digest().getBytes();
return h6 === h_;
};
return pssobj;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/x509.js
var require_x509 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/x509.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_aes();
require_asn1();
require_des();
require_md();
require_mgf();
require_oids();
require_pem();
require_pss();
require_rsa();
require_util10();
var asn1 = forge.asn1;
var pki = module3.exports = forge.pki = forge.pki || {};
var oids = pki.oids;
var _shortNames = {};
_shortNames["CN"] = oids["commonName"];
_shortNames["commonName"] = "CN";
_shortNames["C"] = oids["countryName"];
_shortNames["countryName"] = "C";
_shortNames["L"] = oids["localityName"];
_shortNames["localityName"] = "L";
_shortNames["ST"] = oids["stateOrProvinceName"];
_shortNames["stateOrProvinceName"] = "ST";
_shortNames["O"] = oids["organizationName"];
_shortNames["organizationName"] = "O";
_shortNames["OU"] = oids["organizationalUnitName"];
_shortNames["organizationalUnitName"] = "OU";
_shortNames["E"] = oids["emailAddress"];
_shortNames["emailAddress"] = "E";
var publicKeyValidator = forge.pki.rsa.publicKeyValidator;
var x509CertificateValidator = {
name: "Certificate",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "Certificate.TBSCertificate",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "tbsCertificate",
value: [
{
name: "Certificate.TBSCertificate.version",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
optional: true,
value: [{
name: "Certificate.TBSCertificate.version.integer",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "certVersion"
}]
},
{
name: "Certificate.TBSCertificate.serialNumber",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "certSerialNumber"
},
{
name: "Certificate.TBSCertificate.signature",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "Certificate.TBSCertificate.signature.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "certinfoSignatureOid"
}, {
name: "Certificate.TBSCertificate.signature.parameters",
tagClass: asn1.Class.UNIVERSAL,
optional: true,
captureAsn1: "certinfoSignatureParams"
}]
},
{
name: "Certificate.TBSCertificate.issuer",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "certIssuer"
},
{
name: "Certificate.TBSCertificate.validity",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
// Note: UTC and generalized times may both appear so the capture
// names are based on their detected order, the names used below
// are only for the common case, which validity time really means
// "notBefore" and which means "notAfter" will be determined by order
value: [{
// notBefore (Time) (UTC time case)
name: "Certificate.TBSCertificate.validity.notBefore (utc)",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.UTCTIME,
constructed: false,
optional: true,
capture: "certValidity1UTCTime"
}, {
// notBefore (Time) (generalized time case)
name: "Certificate.TBSCertificate.validity.notBefore (generalized)",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.GENERALIZEDTIME,
constructed: false,
optional: true,
capture: "certValidity2GeneralizedTime"
}, {
// notAfter (Time) (only UTC time is supported)
name: "Certificate.TBSCertificate.validity.notAfter (utc)",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.UTCTIME,
constructed: false,
optional: true,
capture: "certValidity3UTCTime"
}, {
// notAfter (Time) (only UTC time is supported)
name: "Certificate.TBSCertificate.validity.notAfter (generalized)",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.GENERALIZEDTIME,
constructed: false,
optional: true,
capture: "certValidity4GeneralizedTime"
}]
},
{
// Name (subject) (RDNSequence)
name: "Certificate.TBSCertificate.subject",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "certSubject"
},
// SubjectPublicKeyInfo
publicKeyValidator,
{
// issuerUniqueID (optional)
name: "Certificate.TBSCertificate.issuerUniqueID",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 1,
constructed: true,
optional: true,
value: [{
name: "Certificate.TBSCertificate.issuerUniqueID.id",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
// TODO: support arbitrary bit length ids
captureBitStringValue: "certIssuerUniqueId"
}]
},
{
// subjectUniqueID (optional)
name: "Certificate.TBSCertificate.subjectUniqueID",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 2,
constructed: true,
optional: true,
value: [{
name: "Certificate.TBSCertificate.subjectUniqueID.id",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
// TODO: support arbitrary bit length ids
captureBitStringValue: "certSubjectUniqueId"
}]
},
{
// Extensions (optional)
name: "Certificate.TBSCertificate.extensions",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 3,
constructed: true,
captureAsn1: "certExtensions",
optional: true
}
]
}, {
// AlgorithmIdentifier (signature algorithm)
name: "Certificate.signatureAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// algorithm
name: "Certificate.signatureAlgorithm.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "certSignatureOid"
}, {
name: "Certificate.TBSCertificate.signature.parameters",
tagClass: asn1.Class.UNIVERSAL,
optional: true,
captureAsn1: "certSignatureParams"
}]
}, {
// SignatureValue
name: "Certificate.signatureValue",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
captureBitStringValue: "certSignature"
}]
};
var rsassaPssParameterValidator = {
name: "rsapss",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "rsapss.hashAlgorithm",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
value: [{
name: "rsapss.hashAlgorithm.AlgorithmIdentifier",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.SEQUENCE,
constructed: true,
optional: true,
value: [{
name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "hashOid"
/* parameter block omitted, for SHA1 NULL anyhow. */
}]
}]
}, {
name: "rsapss.maskGenAlgorithm",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 1,
constructed: true,
value: [{
name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.SEQUENCE,
constructed: true,
optional: true,
value: [{
name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "maskGenOid"
}, {
name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "maskGenHashOid"
/* parameter block omitted, for SHA1 NULL anyhow. */
}]
}]
}]
}, {
name: "rsapss.saltLength",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 2,
optional: true,
value: [{
name: "rsapss.saltLength.saltLength",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.INTEGER,
constructed: false,
capture: "saltLength"
}]
}, {
name: "rsapss.trailerField",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 3,
optional: true,
value: [{
name: "rsapss.trailer.trailer",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.INTEGER,
constructed: false,
capture: "trailer"
}]
}]
};
var certificationRequestInfoValidator = {
name: "CertificationRequestInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "certificationRequestInfo",
value: [
{
name: "CertificationRequestInfo.integer",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "certificationRequestInfoVersion"
},
{
// Name (subject) (RDNSequence)
name: "CertificationRequestInfo.subject",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "certificationRequestInfoSubject"
},
// SubjectPublicKeyInfo
publicKeyValidator,
{
name: "CertificationRequestInfo.attributes",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
optional: true,
capture: "certificationRequestInfoAttributes",
value: [{
name: "CertificationRequestInfo.attributes",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "CertificationRequestInfo.attributes.type",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false
}, {
name: "CertificationRequestInfo.attributes.value",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
constructed: true
}]
}]
}
]
};
var certificationRequestValidator = {
name: "CertificationRequest",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "csr",
value: [
certificationRequestInfoValidator,
{
// AlgorithmIdentifier (signature algorithm)
name: "CertificationRequest.signatureAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// algorithm
name: "CertificationRequest.signatureAlgorithm.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "csrSignatureOid"
}, {
name: "CertificationRequest.signatureAlgorithm.parameters",
tagClass: asn1.Class.UNIVERSAL,
optional: true,
captureAsn1: "csrSignatureParams"
}]
},
{
// signature
name: "CertificationRequest.signature",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
captureBitStringValue: "csrSignature"
}
]
};
pki.RDNAttributesAsArray = function(rdn, md) {
var rval = [];
var set, attr, obj;
for (var si = 0; si < rdn.value.length; ++si) {
set = rdn.value[si];
for (var i5 = 0; i5 < set.value.length; ++i5) {
obj = {};
attr = set.value[i5];
obj.type = asn1.derToOid(attr.value[0].value);
obj.value = attr.value[1].value;
obj.valueTagClass = attr.value[1].type;
if (obj.type in oids) {
obj.name = oids[obj.type];
if (obj.name in _shortNames) {
obj.shortName = _shortNames[obj.name];
}
}
if (md) {
md.update(obj.type);
md.update(obj.value);
}
rval.push(obj);
}
}
return rval;
};
pki.CRIAttributesAsArray = function(attributes) {
var rval = [];
for (var si = 0; si < attributes.length; ++si) {
var seq = attributes[si];
var type = asn1.derToOid(seq.value[0].value);
var values = seq.value[1].value;
for (var vi = 0; vi < values.length; ++vi) {
var obj = {};
obj.type = type;
obj.value = values[vi].value;
obj.valueTagClass = values[vi].type;
if (obj.type in oids) {
obj.name = oids[obj.type];
if (obj.name in _shortNames) {
obj.shortName = _shortNames[obj.name];
}
}
if (obj.type === oids.extensionRequest) {
obj.extensions = [];
for (var ei = 0; ei < obj.value.length; ++ei) {
obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));
}
}
rval.push(obj);
}
}
return rval;
};
function _getAttribute(obj, options) {
if (typeof options === "string") {
options = { shortName: options };
}
var rval = null;
var attr;
for (var i5 = 0; rval === null && i5 < obj.attributes.length; ++i5) {
attr = obj.attributes[i5];
if (options.type && options.type === attr.type) {
rval = attr;
} else if (options.name && options.name === attr.name) {
rval = attr;
} else if (options.shortName && options.shortName === attr.shortName) {
rval = attr;
}
}
return rval;
}
__name(_getAttribute, "_getAttribute");
var _readSignatureParameters = /* @__PURE__ */ __name(function(oid, obj, fillDefaults) {
var params = {};
if (oid !== oids["RSASSA-PSS"]) {
return params;
}
if (fillDefaults) {
params = {
hash: {
algorithmOid: oids["sha1"]
},
mgf: {
algorithmOid: oids["mgf1"],
hash: {
algorithmOid: oids["sha1"]
}
},
saltLength: 20
};
}
var capture = {};
var errors = [];
if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {
var error2 = new Error("Cannot read RSASSA-PSS parameter block.");
error2.errors = errors;
throw error2;
}
if (capture.hashOid !== void 0) {
params.hash = params.hash || {};
params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
}
if (capture.maskGenOid !== void 0) {
params.mgf = params.mgf || {};
params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
params.mgf.hash = params.mgf.hash || {};
params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
}
if (capture.saltLength !== void 0) {
params.saltLength = capture.saltLength.charCodeAt(0);
}
return params;
}, "_readSignatureParameters");
var _createSignatureDigest = /* @__PURE__ */ __name(function(options) {
switch (oids[options.signatureOid]) {
case "sha1WithRSAEncryption":
// deprecated alias
case "sha1WithRSASignature":
return forge.md.sha1.create();
case "md5WithRSAEncryption":
return forge.md.md5.create();
case "sha256WithRSAEncryption":
return forge.md.sha256.create();
case "sha384WithRSAEncryption":
return forge.md.sha384.create();
case "sha512WithRSAEncryption":
return forge.md.sha512.create();
case "RSASSA-PSS":
return forge.md.sha256.create();
default:
var error2 = new Error(
"Could not compute " + options.type + " digest. Unknown signature OID."
);
error2.signatureOid = options.signatureOid;
throw error2;
}
}, "_createSignatureDigest");
var _verifySignature = /* @__PURE__ */ __name(function(options) {
var cert = options.certificate;
var scheme;
switch (cert.signatureOid) {
case oids.sha1WithRSAEncryption:
// deprecated alias
case oids.sha1WithRSASignature:
break;
case oids["RSASSA-PSS"]:
var hash, mgf;
hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];
if (hash === void 0 || forge.md[hash] === void 0) {
var error2 = new Error("Unsupported MGF hash function.");
error2.oid = cert.signatureParameters.mgf.hash.algorithmOid;
error2.name = hash;
throw error2;
}
mgf = oids[cert.signatureParameters.mgf.algorithmOid];
if (mgf === void 0 || forge.mgf[mgf] === void 0) {
var error2 = new Error("Unsupported MGF function.");
error2.oid = cert.signatureParameters.mgf.algorithmOid;
error2.name = mgf;
throw error2;
}
mgf = forge.mgf[mgf].create(forge.md[hash].create());
hash = oids[cert.signatureParameters.hash.algorithmOid];
if (hash === void 0 || forge.md[hash] === void 0) {
var error2 = new Error("Unsupported RSASSA-PSS hash function.");
error2.oid = cert.signatureParameters.hash.algorithmOid;
error2.name = hash;
throw error2;
}
scheme = forge.pss.create(
forge.md[hash].create(),
mgf,
cert.signatureParameters.saltLength
);
break;
}
return cert.publicKey.verify(
options.md.digest().getBytes(),
options.signature,
scheme
);
}, "_verifySignature");
pki.certificateFromPem = function(pem, computeHash, strict) {
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") {
var error2 = new Error(
'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'
);
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error(
"Could not convert certificate from PEM; PEM is encrypted."
);
}
var obj = asn1.fromDer(msg.body, strict);
return pki.certificateFromAsn1(obj, computeHash);
};
pki.certificateToPem = function(cert, maxline) {
var msg = {
type: "CERTIFICATE",
body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
pki.publicKeyFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") {
var error2 = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert public key from PEM; PEM is encrypted.");
}
var obj = asn1.fromDer(msg.body);
return pki.publicKeyFromAsn1(obj);
};
pki.publicKeyToPem = function(key, maxline) {
var msg = {
type: "PUBLIC KEY",
body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
pki.publicKeyToRSAPublicKeyPem = function(key, maxline) {
var msg = {
type: "RSA PUBLIC KEY",
body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
pki.getPublicKeyFingerprint = function(key, options) {
options = options || {};
var md = options.md || forge.md.sha1.create();
var type = options.type || "RSAPublicKey";
var bytes;
switch (type) {
case "RSAPublicKey":
bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();
break;
case "SubjectPublicKeyInfo":
bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();
break;
default:
throw new Error('Unknown fingerprint type "' + options.type + '".');
}
md.start();
md.update(bytes);
var digest = md.digest();
if (options.encoding === "hex") {
var hex = digest.toHex();
if (options.delimiter) {
return hex.match(/.{2}/g).join(options.delimiter);
}
return hex;
} else if (options.encoding === "binary") {
return digest.getBytes();
} else if (options.encoding) {
throw new Error('Unknown encoding "' + options.encoding + '".');
}
return digest;
};
pki.certificationRequestFromPem = function(pem, computeHash, strict) {
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "CERTIFICATE REQUEST") {
var error2 = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert certification request from PEM; PEM is encrypted.");
}
var obj = asn1.fromDer(msg.body, strict);
return pki.certificationRequestFromAsn1(obj, computeHash);
};
pki.certificationRequestToPem = function(csr, maxline) {
var msg = {
type: "CERTIFICATE REQUEST",
body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
pki.createCertificate = function() {
var cert = {};
cert.version = 2;
cert.serialNumber = "00";
cert.signatureOid = null;
cert.signature = null;
cert.siginfo = {};
cert.siginfo.algorithmOid = null;
cert.validity = {};
cert.validity.notBefore = /* @__PURE__ */ new Date();
cert.validity.notAfter = /* @__PURE__ */ new Date();
cert.issuer = {};
cert.issuer.getField = function(sn) {
return _getAttribute(cert.issuer, sn);
};
cert.issuer.addField = function(attr) {
_fillMissingFields([attr]);
cert.issuer.attributes.push(attr);
};
cert.issuer.attributes = [];
cert.issuer.hash = null;
cert.subject = {};
cert.subject.getField = function(sn) {
return _getAttribute(cert.subject, sn);
};
cert.subject.addField = function(attr) {
_fillMissingFields([attr]);
cert.subject.attributes.push(attr);
};
cert.subject.attributes = [];
cert.subject.hash = null;
cert.extensions = [];
cert.publicKey = null;
cert.md = null;
cert.setSubject = function(attrs, uniqueId) {
_fillMissingFields(attrs);
cert.subject.attributes = attrs;
delete cert.subject.uniqueId;
if (uniqueId) {
cert.subject.uniqueId = uniqueId;
}
cert.subject.hash = null;
};
cert.setIssuer = function(attrs, uniqueId) {
_fillMissingFields(attrs);
cert.issuer.attributes = attrs;
delete cert.issuer.uniqueId;
if (uniqueId) {
cert.issuer.uniqueId = uniqueId;
}
cert.issuer.hash = null;
};
cert.setExtensions = function(exts) {
for (var i5 = 0; i5 < exts.length; ++i5) {
_fillMissingExtensionFields(exts[i5], { cert });
}
cert.extensions = exts;
};
cert.getExtension = function(options) {
if (typeof options === "string") {
options = { name: options };
}
var rval = null;
var ext;
for (var i5 = 0; rval === null && i5 < cert.extensions.length; ++i5) {
ext = cert.extensions[i5];
if (options.id && ext.id === options.id) {
rval = ext;
} else if (options.name && ext.name === options.name) {
rval = ext;
}
}
return rval;
};
cert.sign = function(key, md) {
cert.md = md || forge.md.sha1.create();
var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"];
if (!algorithmOid) {
var error2 = new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");
error2.algorithm = cert.md.algorithm;
throw error2;
}
cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
cert.tbsCertificate = pki.getTBSCertificate(cert);
var bytes = asn1.toDer(cert.tbsCertificate);
cert.md.update(bytes.getBytes());
cert.signature = key.sign(cert.md);
};
cert.verify = function(child) {
var rval = false;
if (!cert.issued(child)) {
var issuer = child.issuer;
var subject = cert.subject;
var error2 = new Error(
"The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject."
);
error2.expectedIssuer = subject.attributes;
error2.actualIssuer = issuer.attributes;
throw error2;
}
var md = child.md;
if (md === null) {
md = _createSignatureDigest({
signatureOid: child.signatureOid,
type: "certificate"
});
var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);
var bytes = asn1.toDer(tbsCertificate);
md.update(bytes.getBytes());
}
if (md !== null) {
rval = _verifySignature({
certificate: cert,
md,
signature: child.signature
});
}
return rval;
};
cert.isIssuer = function(parent) {
var rval = false;
var i5 = cert.issuer;
var s5 = parent.subject;
if (i5.hash && s5.hash) {
rval = i5.hash === s5.hash;
} else if (i5.attributes.length === s5.attributes.length) {
rval = true;
var iattr, sattr;
for (var n6 = 0; rval && n6 < i5.attributes.length; ++n6) {
iattr = i5.attributes[n6];
sattr = s5.attributes[n6];
if (iattr.type !== sattr.type || iattr.value !== sattr.value) {
rval = false;
}
}
}
return rval;
};
cert.issued = function(child) {
return child.isIssuer(cert);
};
cert.generateSubjectKeyIdentifier = function() {
return pki.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" });
};
cert.verifySubjectKeyIdentifier = function() {
var oid = oids["subjectKeyIdentifier"];
for (var i5 = 0; i5 < cert.extensions.length; ++i5) {
var ext = cert.extensions[i5];
if (ext.id === oid) {
var ski = cert.generateSubjectKeyIdentifier().getBytes();
return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski;
}
}
return false;
};
return cert;
};
pki.certificateFromAsn1 = function(obj, computeHash) {
var capture = {};
var errors = [];
if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) {
var error2 = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");
error2.errors = errors;
throw error2;
}
var oid = asn1.derToOid(capture.publicKeyOid);
if (oid !== pki.oids.rsaEncryption) {
throw new Error("Cannot read public key. OID is not RSA.");
}
var cert = pki.createCertificate();
cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0;
var serial = forge.util.createBuffer(capture.certSerialNumber);
cert.serialNumber = serial.toHex();
cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);
cert.signatureParameters = _readSignatureParameters(
cert.signatureOid,
capture.certSignatureParams,
true
);
cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);
cert.siginfo.parameters = _readSignatureParameters(
cert.siginfo.algorithmOid,
capture.certinfoSignatureParams,
false
);
cert.signature = capture.certSignature;
var validity = [];
if (capture.certValidity1UTCTime !== void 0) {
validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));
}
if (capture.certValidity2GeneralizedTime !== void 0) {
validity.push(asn1.generalizedTimeToDate(
capture.certValidity2GeneralizedTime
));
}
if (capture.certValidity3UTCTime !== void 0) {
validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));
}
if (capture.certValidity4GeneralizedTime !== void 0) {
validity.push(asn1.generalizedTimeToDate(
capture.certValidity4GeneralizedTime
));
}
if (validity.length > 2) {
throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");
}
if (validity.length < 2) {
throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");
}
cert.validity.notBefore = validity[0];
cert.validity.notAfter = validity[1];
cert.tbsCertificate = capture.tbsCertificate;
if (computeHash) {
cert.md = _createSignatureDigest({
signatureOid: cert.signatureOid,
type: "certificate"
});
var bytes = asn1.toDer(cert.tbsCertificate);
cert.md.update(bytes.getBytes());
}
var imd = forge.md.sha1.create();
var ibytes = asn1.toDer(capture.certIssuer);
imd.update(ibytes.getBytes());
cert.issuer.getField = function(sn) {
return _getAttribute(cert.issuer, sn);
};
cert.issuer.addField = function(attr) {
_fillMissingFields([attr]);
cert.issuer.attributes.push(attr);
};
cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);
if (capture.certIssuerUniqueId) {
cert.issuer.uniqueId = capture.certIssuerUniqueId;
}
cert.issuer.hash = imd.digest().toHex();
var smd = forge.md.sha1.create();
var sbytes = asn1.toDer(capture.certSubject);
smd.update(sbytes.getBytes());
cert.subject.getField = function(sn) {
return _getAttribute(cert.subject, sn);
};
cert.subject.addField = function(attr) {
_fillMissingFields([attr]);
cert.subject.attributes.push(attr);
};
cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);
if (capture.certSubjectUniqueId) {
cert.subject.uniqueId = capture.certSubjectUniqueId;
}
cert.subject.hash = smd.digest().toHex();
if (capture.certExtensions) {
cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);
} else {
cert.extensions = [];
}
cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
return cert;
};
pki.certificateExtensionsFromAsn1 = function(exts) {
var rval = [];
for (var i5 = 0; i5 < exts.value.length; ++i5) {
var extseq = exts.value[i5];
for (var ei = 0; ei < extseq.value.length; ++ei) {
rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));
}
}
return rval;
};
pki.certificateExtensionFromAsn1 = function(ext) {
var e7 = {};
e7.id = asn1.derToOid(ext.value[0].value);
e7.critical = false;
if (ext.value[1].type === asn1.Type.BOOLEAN) {
e7.critical = ext.value[1].value.charCodeAt(0) !== 0;
e7.value = ext.value[2].value;
} else {
e7.value = ext.value[1].value;
}
if (e7.id in oids) {
e7.name = oids[e7.id];
if (e7.name === "keyUsage") {
var ev = asn1.fromDer(e7.value);
var b22 = 0;
var b32 = 0;
if (ev.value.length > 1) {
b22 = ev.value.charCodeAt(1);
b32 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
}
e7.digitalSignature = (b22 & 128) === 128;
e7.nonRepudiation = (b22 & 64) === 64;
e7.keyEncipherment = (b22 & 32) === 32;
e7.dataEncipherment = (b22 & 16) === 16;
e7.keyAgreement = (b22 & 8) === 8;
e7.keyCertSign = (b22 & 4) === 4;
e7.cRLSign = (b22 & 2) === 2;
e7.encipherOnly = (b22 & 1) === 1;
e7.decipherOnly = (b32 & 128) === 128;
} else if (e7.name === "basicConstraints") {
var ev = asn1.fromDer(e7.value);
if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {
e7.cA = ev.value[0].value.charCodeAt(0) !== 0;
} else {
e7.cA = false;
}
var value = null;
if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {
value = ev.value[0].value;
} else if (ev.value.length > 1) {
value = ev.value[1].value;
}
if (value !== null) {
e7.pathLenConstraint = asn1.derToInteger(value);
}
} else if (e7.name === "extKeyUsage") {
var ev = asn1.fromDer(e7.value);
for (var vi = 0; vi < ev.value.length; ++vi) {
var oid = asn1.derToOid(ev.value[vi].value);
if (oid in oids) {
e7[oids[oid]] = true;
} else {
e7[oid] = true;
}
}
} else if (e7.name === "nsCertType") {
var ev = asn1.fromDer(e7.value);
var b22 = 0;
if (ev.value.length > 1) {
b22 = ev.value.charCodeAt(1);
}
e7.client = (b22 & 128) === 128;
e7.server = (b22 & 64) === 64;
e7.email = (b22 & 32) === 32;
e7.objsign = (b22 & 16) === 16;
e7.reserved = (b22 & 8) === 8;
e7.sslCA = (b22 & 4) === 4;
e7.emailCA = (b22 & 2) === 2;
e7.objCA = (b22 & 1) === 1;
} else if (e7.name === "subjectAltName" || e7.name === "issuerAltName") {
e7.altNames = [];
var gn;
var ev = asn1.fromDer(e7.value);
for (var n6 = 0; n6 < ev.value.length; ++n6) {
gn = ev.value[n6];
var altName = {
type: gn.type,
value: gn.value
};
e7.altNames.push(altName);
switch (gn.type) {
// rfc822Name
case 1:
// dNSName
case 2:
// uniformResourceIdentifier (URI)
case 6:
break;
// IPAddress
case 7:
altName.ip = forge.util.bytesToIP(gn.value);
break;
// registeredID
case 8:
altName.oid = asn1.derToOid(gn.value);
break;
default:
}
}
} else if (e7.name === "subjectKeyIdentifier") {
var ev = asn1.fromDer(e7.value);
e7.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);
}
}
return e7;
};
pki.certificationRequestFromAsn1 = function(obj, computeHash) {
var capture = {};
var errors = [];
if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");
error2.errors = errors;
throw error2;
}
var oid = asn1.derToOid(capture.publicKeyOid);
if (oid !== pki.oids.rsaEncryption) {
throw new Error("Cannot read public key. OID is not RSA.");
}
var csr = pki.createCertificationRequest();
csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);
csr.signatureParameters = _readSignatureParameters(
csr.signatureOid,
capture.csrSignatureParams,
true
);
csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);
csr.siginfo.parameters = _readSignatureParameters(
csr.siginfo.algorithmOid,
capture.csrSignatureParams,
false
);
csr.signature = capture.csrSignature;
csr.certificationRequestInfo = capture.certificationRequestInfo;
if (computeHash) {
csr.md = _createSignatureDigest({
signatureOid: csr.signatureOid,
type: "certification request"
});
var bytes = asn1.toDer(csr.certificationRequestInfo);
csr.md.update(bytes.getBytes());
}
var smd = forge.md.sha1.create();
csr.subject.getField = function(sn) {
return _getAttribute(csr.subject, sn);
};
csr.subject.addField = function(attr) {
_fillMissingFields([attr]);
csr.subject.attributes.push(attr);
};
csr.subject.attributes = pki.RDNAttributesAsArray(
capture.certificationRequestInfoSubject,
smd
);
csr.subject.hash = smd.digest().toHex();
csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
csr.getAttribute = function(sn) {
return _getAttribute(csr, sn);
};
csr.addAttribute = function(attr) {
_fillMissingFields([attr]);
csr.attributes.push(attr);
};
csr.attributes = pki.CRIAttributesAsArray(
capture.certificationRequestInfoAttributes || []
);
return csr;
};
pki.createCertificationRequest = function() {
var csr = {};
csr.version = 0;
csr.signatureOid = null;
csr.signature = null;
csr.siginfo = {};
csr.siginfo.algorithmOid = null;
csr.subject = {};
csr.subject.getField = function(sn) {
return _getAttribute(csr.subject, sn);
};
csr.subject.addField = function(attr) {
_fillMissingFields([attr]);
csr.subject.attributes.push(attr);
};
csr.subject.attributes = [];
csr.subject.hash = null;
csr.publicKey = null;
csr.attributes = [];
csr.getAttribute = function(sn) {
return _getAttribute(csr, sn);
};
csr.addAttribute = function(attr) {
_fillMissingFields([attr]);
csr.attributes.push(attr);
};
csr.md = null;
csr.setSubject = function(attrs) {
_fillMissingFields(attrs);
csr.subject.attributes = attrs;
csr.subject.hash = null;
};
csr.setAttributes = function(attrs) {
_fillMissingFields(attrs);
csr.attributes = attrs;
};
csr.sign = function(key, md) {
csr.md = md || forge.md.sha1.create();
var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"];
if (!algorithmOid) {
var error2 = new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");
error2.algorithm = csr.md.algorithm;
throw error2;
}
csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);
var bytes = asn1.toDer(csr.certificationRequestInfo);
csr.md.update(bytes.getBytes());
csr.signature = key.sign(csr.md);
};
csr.verify = function() {
var rval = false;
var md = csr.md;
if (md === null) {
md = _createSignatureDigest({
signatureOid: csr.signatureOid,
type: "certification request"
});
var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr);
var bytes = asn1.toDer(cri);
md.update(bytes.getBytes());
}
if (md !== null) {
rval = _verifySignature({
certificate: csr,
md,
signature: csr.signature
});
}
return rval;
};
return csr;
};
function _dnToAsn1(obj) {
var rval = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[]
);
var attr, set;
var attrs = obj.attributes;
for (var i5 = 0; i5 < attrs.length; ++i5) {
attr = attrs[i5];
var value = attr.value;
var valueTagClass = asn1.Type.PRINTABLESTRING;
if ("valueTagClass" in attr) {
valueTagClass = attr.valueTagClass;
if (valueTagClass === asn1.Type.UTF8) {
value = forge.util.encodeUtf8(value);
}
}
set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// AttributeType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(attr.type).getBytes()
),
// AttributeValue
asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)
])
]);
rval.value.push(set);
}
return rval;
}
__name(_dnToAsn1, "_dnToAsn1");
function _fillMissingFields(attrs) {
var attr;
for (var i5 = 0; i5 < attrs.length; ++i5) {
attr = attrs[i5];
if (typeof attr.name === "undefined") {
if (attr.type && attr.type in pki.oids) {
attr.name = pki.oids[attr.type];
} else if (attr.shortName && attr.shortName in _shortNames) {
attr.name = pki.oids[_shortNames[attr.shortName]];
}
}
if (typeof attr.type === "undefined") {
if (attr.name && attr.name in pki.oids) {
attr.type = pki.oids[attr.name];
} else {
var error2 = new Error("Attribute type not specified.");
error2.attribute = attr;
throw error2;
}
}
if (typeof attr.shortName === "undefined") {
if (attr.name && attr.name in _shortNames) {
attr.shortName = _shortNames[attr.name];
}
}
if (attr.type === oids.extensionRequest) {
attr.valueConstructed = true;
attr.valueTagClass = asn1.Type.SEQUENCE;
if (!attr.value && attr.extensions) {
attr.value = [];
for (var ei = 0; ei < attr.extensions.length; ++ei) {
attr.value.push(pki.certificateExtensionToAsn1(
_fillMissingExtensionFields(attr.extensions[ei])
));
}
}
}
if (typeof attr.value === "undefined") {
var error2 = new Error("Attribute value not specified.");
error2.attribute = attr;
throw error2;
}
}
}
__name(_fillMissingFields, "_fillMissingFields");
function _fillMissingExtensionFields(e7, options) {
options = options || {};
if (typeof e7.name === "undefined") {
if (e7.id && e7.id in pki.oids) {
e7.name = pki.oids[e7.id];
}
}
if (typeof e7.id === "undefined") {
if (e7.name && e7.name in pki.oids) {
e7.id = pki.oids[e7.name];
} else {
var error2 = new Error("Extension ID not specified.");
error2.extension = e7;
throw error2;
}
}
if (typeof e7.value !== "undefined") {
return e7;
}
if (e7.name === "keyUsage") {
var unused = 0;
var b22 = 0;
var b32 = 0;
if (e7.digitalSignature) {
b22 |= 128;
unused = 7;
}
if (e7.nonRepudiation) {
b22 |= 64;
unused = 6;
}
if (e7.keyEncipherment) {
b22 |= 32;
unused = 5;
}
if (e7.dataEncipherment) {
b22 |= 16;
unused = 4;
}
if (e7.keyAgreement) {
b22 |= 8;
unused = 3;
}
if (e7.keyCertSign) {
b22 |= 4;
unused = 2;
}
if (e7.cRLSign) {
b22 |= 2;
unused = 1;
}
if (e7.encipherOnly) {
b22 |= 1;
unused = 0;
}
if (e7.decipherOnly) {
b32 |= 128;
unused = 7;
}
var value = String.fromCharCode(unused);
if (b32 !== 0) {
value += String.fromCharCode(b22) + String.fromCharCode(b32);
} else if (b22 !== 0) {
value += String.fromCharCode(b22);
}
e7.value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BITSTRING,
false,
value
);
} else if (e7.name === "basicConstraints") {
e7.value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[]
);
if (e7.cA) {
e7.value.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BOOLEAN,
false,
String.fromCharCode(255)
));
}
if ("pathLenConstraint" in e7) {
e7.value.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(e7.pathLenConstraint).getBytes()
));
}
} else if (e7.name === "extKeyUsage") {
e7.value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[]
);
var seq = e7.value.value;
for (var key in e7) {
if (e7[key] !== true) {
continue;
}
if (key in oids) {
seq.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(oids[key]).getBytes()
));
} else if (key.indexOf(".") !== -1) {
seq.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(key).getBytes()
));
}
}
} else if (e7.name === "nsCertType") {
var unused = 0;
var b22 = 0;
if (e7.client) {
b22 |= 128;
unused = 7;
}
if (e7.server) {
b22 |= 64;
unused = 6;
}
if (e7.email) {
b22 |= 32;
unused = 5;
}
if (e7.objsign) {
b22 |= 16;
unused = 4;
}
if (e7.reserved) {
b22 |= 8;
unused = 3;
}
if (e7.sslCA) {
b22 |= 4;
unused = 2;
}
if (e7.emailCA) {
b22 |= 2;
unused = 1;
}
if (e7.objCA) {
b22 |= 1;
unused = 0;
}
var value = String.fromCharCode(unused);
if (b22 !== 0) {
value += String.fromCharCode(b22);
}
e7.value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BITSTRING,
false,
value
);
} else if (e7.name === "subjectAltName" || e7.name === "issuerAltName") {
e7.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
var altName;
for (var n6 = 0; n6 < e7.altNames.length; ++n6) {
altName = e7.altNames[n6];
var value = altName.value;
if (altName.type === 7 && altName.ip) {
value = forge.util.bytesFromIP(altName.ip);
if (value === null) {
var error2 = new Error(
'Extension "ip" value is not a valid IPv4 or IPv6 address.'
);
error2.extension = e7;
throw error2;
}
} else if (altName.type === 8) {
if (altName.oid) {
value = asn1.oidToDer(asn1.oidToDer(altName.oid));
} else {
value = asn1.oidToDer(value);
}
}
e7.value.value.push(asn1.create(
asn1.Class.CONTEXT_SPECIFIC,
altName.type,
false,
value
));
}
} else if (e7.name === "nsComment" && options.cert) {
if (!/^[\x00-\x7F]*$/.test(e7.comment) || e7.comment.length < 1 || e7.comment.length > 128) {
throw new Error('Invalid "nsComment" content.');
}
e7.value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.IA5STRING,
false,
e7.comment
);
} else if (e7.name === "subjectKeyIdentifier" && options.cert) {
var ski = options.cert.generateSubjectKeyIdentifier();
e7.subjectKeyIdentifier = ski.toHex();
e7.value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
ski.getBytes()
);
} else if (e7.name === "authorityKeyIdentifier" && options.cert) {
e7.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
var seq = e7.value.value;
if (e7.keyIdentifier) {
var keyIdentifier = e7.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e7.keyIdentifier;
seq.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)
);
}
if (e7.authorityCertIssuer) {
var authorityCertIssuer = [
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [
_dnToAsn1(e7.authorityCertIssuer === true ? options.cert.issuer : e7.authorityCertIssuer)
])
];
seq.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)
);
}
if (e7.serialNumber) {
var serialNumber = forge.util.hexToBytes(e7.serialNumber === true ? options.cert.serialNumber : e7.serialNumber);
seq.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)
);
}
} else if (e7.name === "cRLDistributionPoints") {
e7.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
var seq = e7.value.value;
var subSeq = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[]
);
var fullNameGeneralNames = asn1.create(
asn1.Class.CONTEXT_SPECIFIC,
0,
true,
[]
);
var altName;
for (var n6 = 0; n6 < e7.altNames.length; ++n6) {
altName = e7.altNames[n6];
var value = altName.value;
if (altName.type === 7 && altName.ip) {
value = forge.util.bytesFromIP(altName.ip);
if (value === null) {
var error2 = new Error(
'Extension "ip" value is not a valid IPv4 or IPv6 address.'
);
error2.extension = e7;
throw error2;
}
} else if (altName.type === 8) {
if (altName.oid) {
value = asn1.oidToDer(asn1.oidToDer(altName.oid));
} else {
value = asn1.oidToDer(value);
}
}
fullNameGeneralNames.value.push(asn1.create(
asn1.Class.CONTEXT_SPECIFIC,
altName.type,
false,
value
));
}
subSeq.value.push(asn1.create(
asn1.Class.CONTEXT_SPECIFIC,
0,
true,
[fullNameGeneralNames]
));
seq.push(subSeq);
}
if (typeof e7.value === "undefined") {
var error2 = new Error("Extension value not specified.");
error2.extension = e7;
throw error2;
}
return e7;
}
__name(_fillMissingExtensionFields, "_fillMissingExtensionFields");
function _signatureParametersToAsn1(oid, params) {
switch (oid) {
case oids["RSASSA-PSS"]:
var parts = [];
if (params.hash.algorithmOid !== void 0) {
parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(params.hash.algorithmOid).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
])
]));
}
if (params.mgf.algorithmOid !== void 0) {
parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(params.mgf.algorithmOid).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
])
])
]));
}
if (params.saltLength !== void 0) {
parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(params.saltLength).getBytes()
)
]));
}
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);
default:
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "");
}
}
__name(_signatureParametersToAsn1, "_signatureParametersToAsn1");
function _CRIAttributesToAsn1(csr) {
var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
if (csr.attributes.length === 0) {
return rval;
}
var attrs = csr.attributes;
for (var i5 = 0; i5 < attrs.length; ++i5) {
var attr = attrs[i5];
var value = attr.value;
var valueTagClass = asn1.Type.UTF8;
if ("valueTagClass" in attr) {
valueTagClass = attr.valueTagClass;
}
if (valueTagClass === asn1.Type.UTF8) {
value = forge.util.encodeUtf8(value);
}
var valueConstructed = false;
if ("valueConstructed" in attr) {
valueConstructed = attr.valueConstructed;
}
var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// AttributeType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(attr.type).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
// AttributeValue
asn1.create(
asn1.Class.UNIVERSAL,
valueTagClass,
valueConstructed,
value
)
])
]);
rval.value.push(seq);
}
return rval;
}
__name(_CRIAttributesToAsn1, "_CRIAttributesToAsn1");
var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z");
var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z");
function _dateToAsn1(date) {
if (date >= jan_1_1950 && date < jan_1_2050) {
return asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.UTCTIME,
false,
asn1.dateToUtcTime(date)
);
} else {
return asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.GENERALIZEDTIME,
false,
asn1.dateToGeneralizedTime(date)
);
}
}
__name(_dateToAsn1, "_dateToAsn1");
pki.getTBSCertificate = function(cert) {
var notBefore = _dateToAsn1(cert.validity.notBefore);
var notAfter = _dateToAsn1(cert.validity.notAfter);
var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
// integer
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(cert.version).getBytes()
)
]),
// serialNumber
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
forge.util.hexToBytes(cert.serialNumber)
),
// signature
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()
),
// parameters
_signatureParametersToAsn1(
cert.siginfo.algorithmOid,
cert.siginfo.parameters
)
]),
// issuer
_dnToAsn1(cert.issuer),
// validity
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
notBefore,
notAfter
]),
// subject
_dnToAsn1(cert.subject),
// SubjectPublicKeyInfo
pki.publicKeyToAsn1(cert.publicKey)
]);
if (cert.issuer.uniqueId) {
tbs.value.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BITSTRING,
false,
// TODO: support arbitrary bit length ids
String.fromCharCode(0) + cert.issuer.uniqueId
)
])
);
}
if (cert.subject.uniqueId) {
tbs.value.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BITSTRING,
false,
// TODO: support arbitrary bit length ids
String.fromCharCode(0) + cert.subject.uniqueId
)
])
);
}
if (cert.extensions.length > 0) {
tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));
}
return tbs;
};
pki.getCertificationRequestInfo = function(csr) {
var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(csr.version).getBytes()
),
// subject
_dnToAsn1(csr.subject),
// SubjectPublicKeyInfo
pki.publicKeyToAsn1(csr.publicKey),
// attributes
_CRIAttributesToAsn1(csr)
]);
return cri;
};
pki.distinguishedNameToAsn1 = function(dn) {
return _dnToAsn1(dn);
};
pki.certificateToAsn1 = function(cert) {
var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// TBSCertificate
tbsCertificate,
// AlgorithmIdentifier (signature algorithm)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(cert.signatureOid).getBytes()
),
// parameters
_signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)
]),
// SignatureValue
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BITSTRING,
false,
String.fromCharCode(0) + cert.signature
)
]);
};
pki.certificateExtensionsToAsn1 = function(exts) {
var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
rval.value.push(seq);
for (var i5 = 0; i5 < exts.length; ++i5) {
seq.value.push(pki.certificateExtensionToAsn1(exts[i5]));
}
return rval;
};
pki.certificateExtensionToAsn1 = function(ext) {
var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(ext.id).getBytes()
));
if (ext.critical) {
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BOOLEAN,
false,
String.fromCharCode(255)
));
}
var value = ext.value;
if (typeof ext.value !== "string") {
value = asn1.toDer(value).getBytes();
}
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
value
));
return extseq;
};
pki.certificationRequestToAsn1 = function(csr) {
var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr);
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// CertificationRequestInfo
cri,
// AlgorithmIdentifier (signature algorithm)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(csr.signatureOid).getBytes()
),
// parameters
_signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)
]),
// signature
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BITSTRING,
false,
String.fromCharCode(0) + csr.signature
)
]);
};
pki.createCaStore = function(certs) {
var caStore = {
// stored certificates
certs: {}
};
caStore.getIssuer = function(cert2) {
var rval = getBySubject(cert2.issuer);
return rval;
};
caStore.addCertificate = function(cert2) {
if (typeof cert2 === "string") {
cert2 = forge.pki.certificateFromPem(cert2);
}
ensureSubjectHasHash(cert2.subject);
if (!caStore.hasCertificate(cert2)) {
if (cert2.subject.hash in caStore.certs) {
var tmp = caStore.certs[cert2.subject.hash];
if (!forge.util.isArray(tmp)) {
tmp = [tmp];
}
tmp.push(cert2);
caStore.certs[cert2.subject.hash] = tmp;
} else {
caStore.certs[cert2.subject.hash] = cert2;
}
}
};
caStore.hasCertificate = function(cert2) {
if (typeof cert2 === "string") {
cert2 = forge.pki.certificateFromPem(cert2);
}
var match2 = getBySubject(cert2.subject);
if (!match2) {
return false;
}
if (!forge.util.isArray(match2)) {
match2 = [match2];
}
var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();
for (var i6 = 0; i6 < match2.length; ++i6) {
var der2 = asn1.toDer(pki.certificateToAsn1(match2[i6])).getBytes();
if (der1 === der2) {
return true;
}
}
return false;
};
caStore.listAllCertificates = function() {
var certList = [];
for (var hash in caStore.certs) {
if (caStore.certs.hasOwnProperty(hash)) {
var value = caStore.certs[hash];
if (!forge.util.isArray(value)) {
certList.push(value);
} else {
for (var i6 = 0; i6 < value.length; ++i6) {
certList.push(value[i6]);
}
}
}
}
return certList;
};
caStore.removeCertificate = function(cert2) {
var result;
if (typeof cert2 === "string") {
cert2 = forge.pki.certificateFromPem(cert2);
}
ensureSubjectHasHash(cert2.subject);
if (!caStore.hasCertificate(cert2)) {
return null;
}
var match2 = getBySubject(cert2.subject);
if (!forge.util.isArray(match2)) {
result = caStore.certs[cert2.subject.hash];
delete caStore.certs[cert2.subject.hash];
return result;
}
var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();
for (var i6 = 0; i6 < match2.length; ++i6) {
var der2 = asn1.toDer(pki.certificateToAsn1(match2[i6])).getBytes();
if (der1 === der2) {
result = match2[i6];
match2.splice(i6, 1);
}
}
if (match2.length === 0) {
delete caStore.certs[cert2.subject.hash];
}
return result;
};
function getBySubject(subject) {
ensureSubjectHasHash(subject);
return caStore.certs[subject.hash] || null;
}
__name(getBySubject, "getBySubject");
function ensureSubjectHasHash(subject) {
if (!subject.hash) {
var md = forge.md.sha1.create();
subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);
subject.hash = md.digest().toHex();
}
}
__name(ensureSubjectHasHash, "ensureSubjectHasHash");
if (certs) {
for (var i5 = 0; i5 < certs.length; ++i5) {
var cert = certs[i5];
caStore.addCertificate(cert);
}
}
return caStore;
};
pki.certificateError = {
bad_certificate: "forge.pki.BadCertificate",
unsupported_certificate: "forge.pki.UnsupportedCertificate",
certificate_revoked: "forge.pki.CertificateRevoked",
certificate_expired: "forge.pki.CertificateExpired",
certificate_unknown: "forge.pki.CertificateUnknown",
unknown_ca: "forge.pki.UnknownCertificateAuthority"
};
pki.verifyCertificateChain = function(caStore, chain2, options) {
if (typeof options === "function") {
options = { verify: options };
}
options = options || {};
chain2 = chain2.slice(0);
var certs = chain2.slice(0);
var validityCheckDate = options.validityCheckDate;
if (typeof validityCheckDate === "undefined") {
validityCheckDate = /* @__PURE__ */ new Date();
}
var first = true;
var error2 = null;
var depth = 0;
do {
var cert = chain2.shift();
var parent = null;
var selfSigned = false;
if (validityCheckDate) {
if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) {
error2 = {
message: "Certificate is not valid yet or has expired.",
error: pki.certificateError.certificate_expired,
notBefore: cert.validity.notBefore,
notAfter: cert.validity.notAfter,
// TODO: we might want to reconsider renaming 'now' to
// 'validityCheckDate' should this API be changed in the future.
now: validityCheckDate
};
}
}
if (error2 === null) {
parent = chain2[0] || caStore.getIssuer(cert);
if (parent === null) {
if (cert.isIssuer(cert)) {
selfSigned = true;
parent = cert;
}
}
if (parent) {
var parents = parent;
if (!forge.util.isArray(parents)) {
parents = [parents];
}
var verified = false;
while (!verified && parents.length > 0) {
parent = parents.shift();
try {
verified = parent.verify(cert);
} catch (ex) {
}
}
if (!verified) {
error2 = {
message: "Certificate signature is invalid.",
error: pki.certificateError.bad_certificate
};
}
}
if (error2 === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) {
error2 = {
message: "Certificate is not trusted.",
error: pki.certificateError.unknown_ca
};
}
}
if (error2 === null && parent && !cert.isIssuer(parent)) {
error2 = {
message: "Certificate issuer is invalid.",
error: pki.certificateError.bad_certificate
};
}
if (error2 === null) {
var se = {
keyUsage: true,
basicConstraints: true
};
for (var i5 = 0; error2 === null && i5 < cert.extensions.length; ++i5) {
var ext = cert.extensions[i5];
if (ext.critical && !(ext.name in se)) {
error2 = {
message: "Certificate has an unsupported critical extension.",
error: pki.certificateError.unsupported_certificate
};
}
}
}
if (error2 === null && (!first || chain2.length === 0 && (!parent || selfSigned))) {
var bcExt = cert.getExtension("basicConstraints");
var keyUsageExt = cert.getExtension("keyUsage");
if (keyUsageExt !== null) {
if (!keyUsageExt.keyCertSign || bcExt === null) {
error2 = {
message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",
error: pki.certificateError.bad_certificate
};
}
}
if (error2 === null && bcExt !== null && !bcExt.cA) {
error2 = {
message: "Certificate basicConstraints indicates the certificate is not a CA.",
error: pki.certificateError.bad_certificate
};
}
if (error2 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) {
var pathLen = depth - 1;
if (pathLen > bcExt.pathLenConstraint) {
error2 = {
message: "Certificate basicConstraints pathLenConstraint violated.",
error: pki.certificateError.bad_certificate
};
}
}
}
var vfd = error2 === null ? true : error2.error;
var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;
if (ret === true) {
error2 = null;
} else {
if (vfd === true) {
error2 = {
message: "The application rejected the certificate.",
error: pki.certificateError.bad_certificate
};
}
if (ret || ret === 0) {
if (typeof ret === "object" && !forge.util.isArray(ret)) {
if (ret.message) {
error2.message = ret.message;
}
if (ret.error) {
error2.error = ret.error;
}
} else if (typeof ret === "string") {
error2.error = ret;
}
}
throw error2;
}
first = false;
++depth;
} while (chain2.length > 0);
return true;
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs12.js
var require_pkcs12 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs12.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_asn1();
require_hmac();
require_oids();
require_pkcs7asn1();
require_pbe();
require_random2();
require_rsa();
require_sha1();
require_util10();
require_x509();
var asn1 = forge.asn1;
var pki = forge.pki;
var p12 = module3.exports = forge.pkcs12 = forge.pkcs12 || {};
var contentInfoValidator = {
name: "ContentInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
// a ContentInfo
constructed: true,
value: [{
name: "ContentInfo.contentType",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "contentType"
}, {
name: "ContentInfo.content",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
constructed: true,
captureAsn1: "content"
}]
};
var pfxValidator = {
name: "PFX",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [
{
name: "PFX.version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "version"
},
contentInfoValidator,
{
name: "PFX.macData",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
optional: true,
captureAsn1: "mac",
value: [{
name: "PFX.macData.mac",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
// DigestInfo
constructed: true,
value: [{
name: "PFX.macData.mac.digestAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
// DigestAlgorithmIdentifier
constructed: true,
value: [{
name: "PFX.macData.mac.digestAlgorithm.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "macAlgorithm"
}, {
name: "PFX.macData.mac.digestAlgorithm.parameters",
tagClass: asn1.Class.UNIVERSAL,
captureAsn1: "macAlgorithmParameters"
}]
}, {
name: "PFX.macData.mac.digest",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "macDigest"
}]
}, {
name: "PFX.macData.macSalt",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "macSalt"
}, {
name: "PFX.macData.iterations",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
optional: true,
capture: "macIterations"
}]
}
]
};
var safeBagValidator = {
name: "SafeBag",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "SafeBag.bagId",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "bagId"
}, {
name: "SafeBag.bagValue",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
constructed: true,
captureAsn1: "bagValue"
}, {
name: "SafeBag.bagAttributes",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
constructed: true,
optional: true,
capture: "bagAttributes"
}]
};
var attributeValidator = {
name: "Attribute",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "Attribute.attrId",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "oid"
}, {
name: "Attribute.attrValues",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
constructed: true,
capture: "values"
}]
};
var certBagValidator = {
name: "CertBag",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "CertBag.certId",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "certId"
}, {
name: "CertBag.certValue",
tagClass: asn1.Class.CONTEXT_SPECIFIC,
constructed: true,
/* So far we only support X.509 certificates (which are wrapped in
an OCTET STRING, hence hard code that here). */
value: [{
name: "CertBag.certValue[0]",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.OCTETSTRING,
constructed: false,
capture: "cert"
}]
}]
};
function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {
var result = [];
for (var i5 = 0; i5 < safeContents.length; i5++) {
for (var j6 = 0; j6 < safeContents[i5].safeBags.length; j6++) {
var bag = safeContents[i5].safeBags[j6];
if (bagType !== void 0 && bag.type !== bagType) {
continue;
}
if (attrName === null) {
result.push(bag);
continue;
}
if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) {
result.push(bag);
}
}
}
return result;
}
__name(_getBagsByAttribute, "_getBagsByAttribute");
p12.pkcs12FromAsn1 = function(obj, strict, password) {
if (typeof strict === "string") {
password = strict;
strict = true;
} else if (strict === void 0) {
strict = true;
}
var capture = {};
var errors = [];
if (!asn1.validate(obj, pfxValidator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");
error2.errors = error2;
throw error2;
}
var pfx = {
version: capture.version.charCodeAt(0),
safeContents: [],
/**
* Gets bags with matching attributes.
*
* @param filter the attributes to filter by:
* [localKeyId] the localKeyId to search for.
* [localKeyIdHex] the localKeyId in hex to search for.
* [friendlyName] the friendly name to search for.
* [bagType] bag type to narrow each attribute search by.
*
* @return a map of attribute type to an array of matching bags or, if no
* attribute was given but a bag type, the map key will be the
* bag type.
*/
getBags: /* @__PURE__ */ __name(function(filter) {
var rval = {};
var localKeyId;
if ("localKeyId" in filter) {
localKeyId = filter.localKeyId;
} else if ("localKeyIdHex" in filter) {
localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);
}
if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) {
rval[filter.bagType] = _getBagsByAttribute(
pfx.safeContents,
null,
null,
filter.bagType
);
}
if (localKeyId !== void 0) {
rval.localKeyId = _getBagsByAttribute(
pfx.safeContents,
"localKeyId",
localKeyId,
filter.bagType
);
}
if ("friendlyName" in filter) {
rval.friendlyName = _getBagsByAttribute(
pfx.safeContents,
"friendlyName",
filter.friendlyName,
filter.bagType
);
}
return rval;
}, "getBags"),
/**
* DEPRECATED: use getBags() instead.
*
* Get bags with matching friendlyName attribute.
*
* @param friendlyName the friendly name to search for.
* @param [bagType] bag type to narrow search by.
*
* @return an array of bags with matching friendlyName attribute.
*/
getBagsByFriendlyName: /* @__PURE__ */ __name(function(friendlyName, bagType) {
return _getBagsByAttribute(
pfx.safeContents,
"friendlyName",
friendlyName,
bagType
);
}, "getBagsByFriendlyName"),
/**
* DEPRECATED: use getBags() instead.
*
* Get bags with matching localKeyId attribute.
*
* @param localKeyId the localKeyId to search for.
* @param [bagType] bag type to narrow search by.
*
* @return an array of bags with matching localKeyId attribute.
*/
getBagsByLocalKeyId: /* @__PURE__ */ __name(function(localKeyId, bagType) {
return _getBagsByAttribute(
pfx.safeContents,
"localKeyId",
localKeyId,
bagType
);
}, "getBagsByLocalKeyId")
};
if (capture.version.charCodeAt(0) !== 3) {
var error2 = new Error("PKCS#12 PFX of version other than 3 not supported.");
error2.version = capture.version.charCodeAt(0);
throw error2;
}
if (asn1.derToOid(capture.contentType) !== pki.oids.data) {
var error2 = new Error("Only PKCS#12 PFX in password integrity mode supported.");
error2.oid = asn1.derToOid(capture.contentType);
throw error2;
}
var data = capture.content.value[0];
if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) {
throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");
}
data = _decodePkcs7Data(data);
if (capture.mac) {
var md = null;
var macKeyBytes = 0;
var macAlgorithm = asn1.derToOid(capture.macAlgorithm);
switch (macAlgorithm) {
case pki.oids.sha1:
md = forge.md.sha1.create();
macKeyBytes = 20;
break;
case pki.oids.sha256:
md = forge.md.sha256.create();
macKeyBytes = 32;
break;
case pki.oids.sha384:
md = forge.md.sha384.create();
macKeyBytes = 48;
break;
case pki.oids.sha512:
md = forge.md.sha512.create();
macKeyBytes = 64;
break;
case pki.oids.md5:
md = forge.md.md5.create();
macKeyBytes = 16;
break;
}
if (md === null) {
throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm);
}
var macSalt = new forge.util.ByteBuffer(capture.macSalt);
var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1;
var macKey = p12.generateKey(
password,
macSalt,
3,
macIterations,
macKeyBytes,
md
);
var mac = forge.hmac.create();
mac.start(md, macKey);
mac.update(data.value);
var macValue = mac.getMac();
if (macValue.getBytes() !== capture.macDigest) {
throw new Error("PKCS#12 MAC could not be verified. Invalid password?");
}
}
_decodeAuthenticatedSafe(pfx, data.value, strict, password);
return pfx;
};
function _decodePkcs7Data(data) {
if (data.composed || data.constructed) {
var value = forge.util.createBuffer();
for (var i5 = 0; i5 < data.value.length; ++i5) {
value.putBytes(data.value[i5].value);
}
data.composed = data.constructed = false;
data.value = value.getBytes();
}
return data;
}
__name(_decodePkcs7Data, "_decodePkcs7Data");
function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {
authSafe = asn1.fromDer(authSafe, strict);
if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) {
throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");
}
for (var i5 = 0; i5 < authSafe.value.length; i5++) {
var contentInfo = authSafe.value[i5];
var capture = {};
var errors = [];
if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {
var error2 = new Error("Cannot read ContentInfo.");
error2.errors = errors;
throw error2;
}
var obj = {
encrypted: false
};
var safeContents = null;
var data = capture.content.value[0];
switch (asn1.derToOid(capture.contentType)) {
case pki.oids.data:
if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) {
throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");
}
safeContents = _decodePkcs7Data(data).value;
break;
case pki.oids.encryptedData:
safeContents = _decryptSafeContents(data, password);
obj.encrypted = true;
break;
default:
var error2 = new Error("Unsupported PKCS#12 contentType.");
error2.contentType = asn1.derToOid(capture.contentType);
throw error2;
}
obj.safeBags = _decodeSafeContents(safeContents, strict, password);
pfx.safeContents.push(obj);
}
}
__name(_decodeAuthenticatedSafe, "_decodeAuthenticatedSafe");
function _decryptSafeContents(data, password) {
var capture = {};
var errors = [];
if (!asn1.validate(
data,
forge.pkcs7.asn1.encryptedDataValidator,
capture,
errors
)) {
var error2 = new Error("Cannot read EncryptedContentInfo.");
error2.errors = errors;
throw error2;
}
var oid = asn1.derToOid(capture.contentType);
if (oid !== pki.oids.data) {
var error2 = new Error(
"PKCS#12 EncryptedContentInfo ContentType is not Data."
);
error2.oid = oid;
throw error2;
}
oid = asn1.derToOid(capture.encAlgorithm);
var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);
var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);
var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);
cipher.update(encrypted);
if (!cipher.finish()) {
throw new Error("Failed to decrypt PKCS#12 SafeContents.");
}
return cipher.output.getBytes();
}
__name(_decryptSafeContents, "_decryptSafeContents");
function _decodeSafeContents(safeContents, strict, password) {
if (!strict && safeContents.length === 0) {
return [];
}
safeContents = asn1.fromDer(safeContents, strict);
if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) {
throw new Error(
"PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag."
);
}
var res = [];
for (var i5 = 0; i5 < safeContents.value.length; i5++) {
var safeBag = safeContents.value[i5];
var capture = {};
var errors = [];
if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) {
var error2 = new Error("Cannot read SafeBag.");
error2.errors = errors;
throw error2;
}
var bag = {
type: asn1.derToOid(capture.bagId),
attributes: _decodeBagAttributes(capture.bagAttributes)
};
res.push(bag);
var validator, decoder;
var bagAsn1 = capture.bagValue.value[0];
switch (bag.type) {
case pki.oids.pkcs8ShroudedKeyBag:
bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);
if (bagAsn1 === null) {
throw new Error(
"Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?"
);
}
/* fall through */
case pki.oids.keyBag:
try {
bag.key = pki.privateKeyFromAsn1(bagAsn1);
} catch (e7) {
bag.key = null;
bag.asn1 = bagAsn1;
}
continue;
/* Nothing more to do. */
case pki.oids.certBag:
validator = certBagValidator;
decoder = /* @__PURE__ */ __name(function() {
if (asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {
var error3 = new Error(
"Unsupported certificate type, only X.509 supported."
);
error3.oid = asn1.derToOid(capture.certId);
throw error3;
}
var certAsn1 = asn1.fromDer(capture.cert, strict);
try {
bag.cert = pki.certificateFromAsn1(certAsn1, true);
} catch (e7) {
bag.cert = null;
bag.asn1 = certAsn1;
}
}, "decoder");
break;
default:
var error2 = new Error("Unsupported PKCS#12 SafeBag type.");
error2.oid = bag.type;
throw error2;
}
if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#12 " + validator.name);
error2.errors = errors;
throw error2;
}
decoder();
}
return res;
}
__name(_decodeSafeContents, "_decodeSafeContents");
function _decodeBagAttributes(attributes) {
var decodedAttrs = {};
if (attributes !== void 0) {
for (var i5 = 0; i5 < attributes.length; ++i5) {
var capture = {};
var errors = [];
if (!asn1.validate(attributes[i5], attributeValidator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#12 BagAttribute.");
error2.errors = errors;
throw error2;
}
var oid = asn1.derToOid(capture.oid);
if (pki.oids[oid] === void 0) {
continue;
}
decodedAttrs[pki.oids[oid]] = [];
for (var j6 = 0; j6 < capture.values.length; ++j6) {
decodedAttrs[pki.oids[oid]].push(capture.values[j6].value);
}
}
}
return decodedAttrs;
}
__name(_decodeBagAttributes, "_decodeBagAttributes");
p12.toPkcs12Asn1 = function(key, cert, password, options) {
options = options || {};
options.saltSize = options.saltSize || 8;
options.count = options.count || 2048;
options.algorithm = options.algorithm || options.encAlgorithm || "aes128";
if (!("useMac" in options)) {
options.useMac = true;
}
if (!("localKeyId" in options)) {
options.localKeyId = null;
}
if (!("generateLocalKeyId" in options)) {
options.generateLocalKeyId = true;
}
var localKeyId = options.localKeyId;
var bagAttrs;
if (localKeyId !== null) {
localKeyId = forge.util.hexToBytes(localKeyId);
} else if (options.generateLocalKeyId) {
if (cert) {
var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;
if (typeof pairedCert === "string") {
pairedCert = pki.certificateFromPem(pairedCert);
}
var sha1 = forge.md.sha1.create();
sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());
localKeyId = sha1.digest().getBytes();
} else {
localKeyId = forge.random.getBytes(20);
}
}
var attrs = [];
if (localKeyId !== null) {
attrs.push(
// localKeyID
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// attrId
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.localKeyId).getBytes()
),
// attrValues
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
localKeyId
)
])
])
);
}
if ("friendlyName" in options) {
attrs.push(
// friendlyName
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// attrId
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.friendlyName).getBytes()
),
// attrValues
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.BMPSTRING,
false,
options.friendlyName
)
])
])
);
}
if (attrs.length > 0) {
bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);
}
var contents = [];
var chain2 = [];
if (cert !== null) {
if (forge.util.isArray(cert)) {
chain2 = cert;
} else {
chain2 = [cert];
}
}
var certSafeBags = [];
for (var i5 = 0; i5 < chain2.length; ++i5) {
cert = chain2[i5];
if (typeof cert === "string") {
cert = pki.certificateFromPem(cert);
}
var certBagAttrs = i5 === 0 ? bagAttrs : void 0;
var certAsn1 = pki.certificateToAsn1(cert);
var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// bagId
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.certBag).getBytes()
),
// bagValue
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
// CertBag
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// certId
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.x509Certificate).getBytes()
),
// certValue (x509Certificate)
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
asn1.toDer(certAsn1).getBytes()
)
])
])
]),
// bagAttributes (OPTIONAL)
certBagAttrs
]);
certSafeBags.push(certSafeBag);
}
if (certSafeBags.length > 0) {
var certSafeContents = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
certSafeBags
);
var certCI = (
// PKCS#7 ContentInfo
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// contentType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
// OID for the content type is 'data'
asn1.oidToDer(pki.oids.data).getBytes()
),
// content
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
asn1.toDer(certSafeContents).getBytes()
)
])
])
);
contents.push(certCI);
}
var keyBag = null;
if (key !== null) {
var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));
if (password === null) {
keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// bagId
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.keyBag).getBytes()
),
// bagValue
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
// PrivateKeyInfo
pkAsn1
]),
// bagAttributes (OPTIONAL)
bagAttrs
]);
} else {
keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// bagId
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()
),
// bagValue
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
// EncryptedPrivateKeyInfo
pki.encryptPrivateKeyInfo(pkAsn1, password, options)
]),
// bagAttributes (OPTIONAL)
bagAttrs
]);
}
var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);
var keyCI = (
// PKCS#7 ContentInfo
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// contentType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
// OID for the content type is 'data'
asn1.oidToDer(pki.oids.data).getBytes()
),
// content
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
asn1.toDer(keySafeContents).getBytes()
)
])
])
);
contents.push(keyCI);
}
var safe = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
contents
);
var macData;
if (options.useMac) {
var sha1 = forge.md.sha1.create();
var macSalt = new forge.util.ByteBuffer(
forge.random.getBytes(options.saltSize)
);
var count = options.count;
var key = p12.generateKey(password, macSalt, 3, count, 20);
var mac = forge.hmac.create();
mac.start(sha1, key);
mac.update(asn1.toDer(safe).getBytes());
var macValue = mac.getMac();
macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// mac DigestInfo
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// digestAlgorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm = SHA-1
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(pki.oids.sha1).getBytes()
),
// parameters = Null
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
]),
// digest
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
macValue.getBytes()
)
]),
// macSalt OCTET STRING
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
macSalt.getBytes()
),
// iterations INTEGER (XXX: Only support count < 65536)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(count).getBytes()
)
]);
}
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version (3)
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(3).getBytes()
),
// PKCS#7 ContentInfo
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// contentType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
// OID for the content type is 'data'
asn1.oidToDer(pki.oids.data).getBytes()
),
// content
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
asn1.toDer(safe).getBytes()
)
])
]),
macData
]);
};
p12.generateKey = forge.pbe.generatePkcs12Key;
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pki.js
var require_pki = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pki.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_asn1();
require_oids();
require_pbe();
require_pem();
require_pbkdf2();
require_pkcs12();
require_pss();
require_rsa();
require_util10();
require_x509();
var asn1 = forge.asn1;
var pki = module3.exports = forge.pki = forge.pki || {};
pki.pemToDer = function(pem) {
var msg = forge.pem.decode(pem)[0];
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert PEM to DER; PEM is encrypted.");
}
return forge.util.createBuffer(msg.body);
};
pki.privateKeyFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") {
var error2 = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert private key from PEM; PEM is encrypted.");
}
var obj = asn1.fromDer(msg.body);
return pki.privateKeyFromAsn1(obj);
};
pki.privateKeyToPem = function(key, maxline) {
var msg = {
type: "RSA PRIVATE KEY",
body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
pki.privateKeyInfoToPem = function(pki2, maxline) {
var msg = {
type: "PRIVATE KEY",
body: asn1.toDer(pki2).getBytes()
};
return forge.pem.encode(msg, { maxline });
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/tls.js
var require_tls = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/tls.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_asn1();
require_hmac();
require_md5();
require_pem();
require_pki();
require_random2();
require_sha1();
require_util10();
var prf_TLS1 = /* @__PURE__ */ __name(function(secret, label, seed, length) {
var rval = forge.util.createBuffer();
var idx = secret.length >> 1;
var slen = idx + (secret.length & 1);
var s1 = secret.substr(0, slen);
var s22 = secret.substr(idx, slen);
var ai2 = forge.util.createBuffer();
var hmac2 = forge.hmac.create();
seed = label + seed;
var md5itr = Math.ceil(length / 16);
var sha1itr = Math.ceil(length / 20);
hmac2.start("MD5", s1);
var md5bytes = forge.util.createBuffer();
ai2.putBytes(seed);
for (var i5 = 0; i5 < md5itr; ++i5) {
hmac2.start(null, null);
hmac2.update(ai2.getBytes());
ai2.putBuffer(hmac2.digest());
hmac2.start(null, null);
hmac2.update(ai2.bytes() + seed);
md5bytes.putBuffer(hmac2.digest());
}
hmac2.start("SHA1", s22);
var sha1bytes = forge.util.createBuffer();
ai2.clear();
ai2.putBytes(seed);
for (var i5 = 0; i5 < sha1itr; ++i5) {
hmac2.start(null, null);
hmac2.update(ai2.getBytes());
ai2.putBuffer(hmac2.digest());
hmac2.start(null, null);
hmac2.update(ai2.bytes() + seed);
sha1bytes.putBuffer(hmac2.digest());
}
rval.putBytes(forge.util.xorBytes(
md5bytes.getBytes(),
sha1bytes.getBytes(),
length
));
return rval;
}, "prf_TLS1");
var hmac_sha1 = /* @__PURE__ */ __name(function(key2, seqNum, record) {
var hmac2 = forge.hmac.create();
hmac2.start("SHA1", key2);
var b6 = forge.util.createBuffer();
b6.putInt32(seqNum[0]);
b6.putInt32(seqNum[1]);
b6.putByte(record.type);
b6.putByte(record.version.major);
b6.putByte(record.version.minor);
b6.putInt16(record.length);
b6.putBytes(record.fragment.bytes());
hmac2.update(b6.getBytes());
return hmac2.digest().getBytes();
}, "hmac_sha1");
var deflate = /* @__PURE__ */ __name(function(c6, record, s5) {
var rval = false;
try {
var bytes = c6.deflate(record.fragment.getBytes());
record.fragment = forge.util.createBuffer(bytes);
record.length = bytes.length;
rval = true;
} catch (ex) {
}
return rval;
}, "deflate");
var inflate = /* @__PURE__ */ __name(function(c6, record, s5) {
var rval = false;
try {
var bytes = c6.inflate(record.fragment.getBytes());
record.fragment = forge.util.createBuffer(bytes);
record.length = bytes.length;
rval = true;
} catch (ex) {
}
return rval;
}, "inflate");
var readVector = /* @__PURE__ */ __name(function(b6, lenBytes) {
var len = 0;
switch (lenBytes) {
case 1:
len = b6.getByte();
break;
case 2:
len = b6.getInt16();
break;
case 3:
len = b6.getInt24();
break;
case 4:
len = b6.getInt32();
break;
}
return forge.util.createBuffer(b6.getBytes(len));
}, "readVector");
var writeVector = /* @__PURE__ */ __name(function(b6, lenBytes, v7) {
b6.putInt(v7.length(), lenBytes << 3);
b6.putBuffer(v7);
}, "writeVector");
var tls = {};
tls.Versions = {
TLS_1_0: { major: 3, minor: 1 },
TLS_1_1: { major: 3, minor: 2 },
TLS_1_2: { major: 3, minor: 3 }
};
tls.SupportedVersions = [
tls.Versions.TLS_1_1,
tls.Versions.TLS_1_0
];
tls.Version = tls.SupportedVersions[0];
tls.MaxFragment = 16384 - 1024;
tls.ConnectionEnd = {
server: 0,
client: 1
};
tls.PRFAlgorithm = {
tls_prf_sha256: 0
};
tls.BulkCipherAlgorithm = {
none: null,
rc4: 0,
des3: 1,
aes: 2
};
tls.CipherType = {
stream: 0,
block: 1,
aead: 2
};
tls.MACAlgorithm = {
none: null,
hmac_md5: 0,
hmac_sha1: 1,
hmac_sha256: 2,
hmac_sha384: 3,
hmac_sha512: 4
};
tls.CompressionMethod = {
none: 0,
deflate: 1
};
tls.ContentType = {
change_cipher_spec: 20,
alert: 21,
handshake: 22,
application_data: 23,
heartbeat: 24
};
tls.HandshakeType = {
hello_request: 0,
client_hello: 1,
server_hello: 2,
certificate: 11,
server_key_exchange: 12,
certificate_request: 13,
server_hello_done: 14,
certificate_verify: 15,
client_key_exchange: 16,
finished: 20
};
tls.Alert = {};
tls.Alert.Level = {
warning: 1,
fatal: 2
};
tls.Alert.Description = {
close_notify: 0,
unexpected_message: 10,
bad_record_mac: 20,
decryption_failed: 21,
record_overflow: 22,
decompression_failure: 30,
handshake_failure: 40,
bad_certificate: 42,
unsupported_certificate: 43,
certificate_revoked: 44,
certificate_expired: 45,
certificate_unknown: 46,
illegal_parameter: 47,
unknown_ca: 48,
access_denied: 49,
decode_error: 50,
decrypt_error: 51,
export_restriction: 60,
protocol_version: 70,
insufficient_security: 71,
internal_error: 80,
user_canceled: 90,
no_renegotiation: 100
};
tls.HeartbeatMessageType = {
heartbeat_request: 1,
heartbeat_response: 2
};
tls.CipherSuites = {};
tls.getCipherSuite = function(twoBytes) {
var rval = null;
for (var key2 in tls.CipherSuites) {
var cs2 = tls.CipherSuites[key2];
if (cs2.id[0] === twoBytes.charCodeAt(0) && cs2.id[1] === twoBytes.charCodeAt(1)) {
rval = cs2;
break;
}
}
return rval;
};
tls.handleUnexpected = function(c6, record) {
var ignore2 = !c6.open && c6.entity === tls.ConnectionEnd.client;
if (!ignore2) {
c6.error(c6, {
message: "Unexpected message. Received TLS record out of order.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.unexpected_message
}
});
}
};
tls.handleHelloRequest = function(c6, record, length) {
if (!c6.handshaking && c6.handshakes > 0) {
tls.queue(c6, tls.createAlert(c6, {
level: tls.Alert.Level.warning,
description: tls.Alert.Description.no_renegotiation
}));
tls.flush(c6);
}
c6.process();
};
tls.parseHelloMessage = function(c6, record, length) {
var msg = null;
var client = c6.entity === tls.ConnectionEnd.client;
if (length < 38) {
c6.error(c6, {
message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.illegal_parameter
}
});
} else {
var b6 = record.fragment;
var remaining = b6.length();
msg = {
version: {
major: b6.getByte(),
minor: b6.getByte()
},
random: forge.util.createBuffer(b6.getBytes(32)),
session_id: readVector(b6, 1),
extensions: []
};
if (client) {
msg.cipher_suite = b6.getBytes(2);
msg.compression_method = b6.getByte();
} else {
msg.cipher_suites = readVector(b6, 2);
msg.compression_methods = readVector(b6, 1);
}
remaining = length - (remaining - b6.length());
if (remaining > 0) {
var exts = readVector(b6, 2);
while (exts.length() > 0) {
msg.extensions.push({
type: [exts.getByte(), exts.getByte()],
data: readVector(exts, 2)
});
}
if (!client) {
for (var i5 = 0; i5 < msg.extensions.length; ++i5) {
var ext = msg.extensions[i5];
if (ext.type[0] === 0 && ext.type[1] === 0) {
var snl = readVector(ext.data, 2);
while (snl.length() > 0) {
var snType = snl.getByte();
if (snType !== 0) {
break;
}
c6.session.extensions.server_name.serverNameList.push(
readVector(snl, 2).getBytes()
);
}
}
}
}
}
if (c6.session.version) {
if (msg.version.major !== c6.session.version.major || msg.version.minor !== c6.session.version.minor) {
return c6.error(c6, {
message: "TLS version change is disallowed during renegotiation.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.protocol_version
}
});
}
}
if (client) {
c6.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);
} else {
var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());
while (tmp.length() > 0) {
c6.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));
if (c6.session.cipherSuite !== null) {
break;
}
}
}
if (c6.session.cipherSuite === null) {
return c6.error(c6, {
message: "No cipher suites in common.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.handshake_failure
},
cipherSuite: forge.util.bytesToHex(msg.cipher_suite)
});
}
if (client) {
c6.session.compressionMethod = msg.compression_method;
} else {
c6.session.compressionMethod = tls.CompressionMethod.none;
}
}
return msg;
};
tls.createSecurityParameters = function(c6, msg) {
var client = c6.entity === tls.ConnectionEnd.client;
var msgRandom = msg.random.bytes();
var cRandom = client ? c6.session.sp.client_random : msgRandom;
var sRandom = client ? msgRandom : tls.createRandom().getBytes();
c6.session.sp = {
entity: c6.entity,
prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,
bulk_cipher_algorithm: null,
cipher_type: null,
enc_key_length: null,
block_length: null,
fixed_iv_length: null,
record_iv_length: null,
mac_algorithm: null,
mac_length: null,
mac_key_length: null,
compression_algorithm: c6.session.compressionMethod,
pre_master_secret: null,
master_secret: null,
client_random: cRandom,
server_random: sRandom
};
};
tls.handleServerHello = function(c6, record, length) {
var msg = tls.parseHelloMessage(c6, record, length);
if (c6.fail) {
return;
}
if (msg.version.minor <= c6.version.minor) {
c6.version.minor = msg.version.minor;
} else {
return c6.error(c6, {
message: "Incompatible TLS version.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.protocol_version
}
});
}
c6.session.version = c6.version;
var sessionId = msg.session_id.bytes();
if (sessionId.length > 0 && sessionId === c6.session.id) {
c6.expect = SCC;
c6.session.resuming = true;
c6.session.sp.server_random = msg.random.bytes();
} else {
c6.expect = SCE;
c6.session.resuming = false;
tls.createSecurityParameters(c6, msg);
}
c6.session.id = sessionId;
c6.process();
};
tls.handleClientHello = function(c6, record, length) {
var msg = tls.parseHelloMessage(c6, record, length);
if (c6.fail) {
return;
}
var sessionId = msg.session_id.bytes();
var session = null;
if (c6.sessionCache) {
session = c6.sessionCache.getSession(sessionId);
if (session === null) {
sessionId = "";
} else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) {
session = null;
sessionId = "";
}
}
if (sessionId.length === 0) {
sessionId = forge.random.getBytes(32);
}
c6.session.id = sessionId;
c6.session.clientHelloVersion = msg.version;
c6.session.sp = {};
if (session) {
c6.version = c6.session.version = session.version;
c6.session.sp = session.sp;
} else {
var version5;
for (var i5 = 1; i5 < tls.SupportedVersions.length; ++i5) {
version5 = tls.SupportedVersions[i5];
if (version5.minor <= msg.version.minor) {
break;
}
}
c6.version = { major: version5.major, minor: version5.minor };
c6.session.version = c6.version;
}
if (session !== null) {
c6.expect = CCC;
c6.session.resuming = true;
c6.session.sp.client_random = msg.random.bytes();
} else {
c6.expect = c6.verifyClient !== false ? CCE : CKE;
c6.session.resuming = false;
tls.createSecurityParameters(c6, msg);
}
c6.open = true;
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createServerHello(c6)
}));
if (c6.session.resuming) {
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.change_cipher_spec,
data: tls.createChangeCipherSpec()
}));
c6.state.pending = tls.createConnectionState(c6);
c6.state.current.write = c6.state.pending.write;
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createFinished(c6)
}));
} else {
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createCertificate(c6)
}));
if (!c6.fail) {
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createServerKeyExchange(c6)
}));
if (c6.verifyClient !== false) {
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createCertificateRequest(c6)
}));
}
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createServerHelloDone(c6)
}));
}
}
tls.flush(c6);
c6.process();
};
tls.handleCertificate = function(c6, record, length) {
if (length < 3) {
return c6.error(c6, {
message: "Invalid Certificate message. Message too short.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.illegal_parameter
}
});
}
var b6 = record.fragment;
var msg = {
certificate_list: readVector(b6, 3)
};
var cert, asn1;
var certs = [];
try {
while (msg.certificate_list.length() > 0) {
cert = readVector(msg.certificate_list, 3);
asn1 = forge.asn1.fromDer(cert);
cert = forge.pki.certificateFromAsn1(asn1, true);
certs.push(cert);
}
} catch (ex) {
return c6.error(c6, {
message: "Could not parse certificate list.",
cause: ex,
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.bad_certificate
}
});
}
var client = c6.entity === tls.ConnectionEnd.client;
if ((client || c6.verifyClient === true) && certs.length === 0) {
c6.error(c6, {
message: client ? "No server certificate provided." : "No client certificate provided.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.illegal_parameter
}
});
} else if (certs.length === 0) {
c6.expect = client ? SKE : CKE;
} else {
if (client) {
c6.session.serverCertificate = certs[0];
} else {
c6.session.clientCertificate = certs[0];
}
if (tls.verifyCertificateChain(c6, certs)) {
c6.expect = client ? SKE : CKE;
}
}
c6.process();
};
tls.handleServerKeyExchange = function(c6, record, length) {
if (length > 0) {
return c6.error(c6, {
message: "Invalid key parameters. Only RSA is supported.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.unsupported_certificate
}
});
}
c6.expect = SCR;
c6.process();
};
tls.handleClientKeyExchange = function(c6, record, length) {
if (length < 48) {
return c6.error(c6, {
message: "Invalid key parameters. Only RSA is supported.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.unsupported_certificate
}
});
}
var b6 = record.fragment;
var msg = {
enc_pre_master_secret: readVector(b6, 2).getBytes()
};
var privateKey = null;
if (c6.getPrivateKey) {
try {
privateKey = c6.getPrivateKey(c6, c6.session.serverCertificate);
privateKey = forge.pki.privateKeyFromPem(privateKey);
} catch (ex) {
c6.error(c6, {
message: "Could not get private key.",
cause: ex,
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.internal_error
}
});
}
}
if (privateKey === null) {
return c6.error(c6, {
message: "No private key set.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.internal_error
}
});
}
try {
var sp = c6.session.sp;
sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);
var version5 = c6.session.clientHelloVersion;
if (version5.major !== sp.pre_master_secret.charCodeAt(0) || version5.minor !== sp.pre_master_secret.charCodeAt(1)) {
throw new Error("TLS version rollback attack detected.");
}
} catch (ex) {
sp.pre_master_secret = forge.random.getBytes(48);
}
c6.expect = CCC;
if (c6.session.clientCertificate !== null) {
c6.expect = CCV;
}
c6.process();
};
tls.handleCertificateRequest = function(c6, record, length) {
if (length < 3) {
return c6.error(c6, {
message: "Invalid CertificateRequest. Message too short.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.illegal_parameter
}
});
}
var b6 = record.fragment;
var msg = {
certificate_types: readVector(b6, 1),
certificate_authorities: readVector(b6, 2)
};
c6.session.certificateRequest = msg;
c6.expect = SHD;
c6.process();
};
tls.handleCertificateVerify = function(c6, record, length) {
if (length < 2) {
return c6.error(c6, {
message: "Invalid CertificateVerify. Message too short.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.illegal_parameter
}
});
}
var b6 = record.fragment;
b6.read -= 4;
var msgBytes = b6.bytes();
b6.read += 4;
var msg = {
signature: readVector(b6, 2).getBytes()
};
var verify = forge.util.createBuffer();
verify.putBuffer(c6.session.md5.digest());
verify.putBuffer(c6.session.sha1.digest());
verify = verify.getBytes();
try {
var cert = c6.session.clientCertificate;
if (!cert.publicKey.verify(verify, msg.signature, "NONE")) {
throw new Error("CertificateVerify signature does not match.");
}
c6.session.md5.update(msgBytes);
c6.session.sha1.update(msgBytes);
} catch (ex) {
return c6.error(c6, {
message: "Bad signature in CertificateVerify.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.handshake_failure
}
});
}
c6.expect = CCC;
c6.process();
};
tls.handleServerHelloDone = function(c6, record, length) {
if (length > 0) {
return c6.error(c6, {
message: "Invalid ServerHelloDone message. Invalid length.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.record_overflow
}
});
}
if (c6.serverCertificate === null) {
var error2 = {
message: "No server certificate provided. Not enough security.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.insufficient_security
}
};
var depth = 0;
var ret = c6.verify(c6, error2.alert.description, depth, []);
if (ret !== true) {
if (ret || ret === 0) {
if (typeof ret === "object" && !forge.util.isArray(ret)) {
if (ret.message) {
error2.message = ret.message;
}
if (ret.alert) {
error2.alert.description = ret.alert;
}
} else if (typeof ret === "number") {
error2.alert.description = ret;
}
}
return c6.error(c6, error2);
}
}
if (c6.session.certificateRequest !== null) {
record = tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createCertificate(c6)
});
tls.queue(c6, record);
}
record = tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createClientKeyExchange(c6)
});
tls.queue(c6, record);
c6.expect = SER;
var callback = /* @__PURE__ */ __name(function(c7, signature) {
if (c7.session.certificateRequest !== null && c7.session.clientCertificate !== null) {
tls.queue(c7, tls.createRecord(c7, {
type: tls.ContentType.handshake,
data: tls.createCertificateVerify(c7, signature)
}));
}
tls.queue(c7, tls.createRecord(c7, {
type: tls.ContentType.change_cipher_spec,
data: tls.createChangeCipherSpec()
}));
c7.state.pending = tls.createConnectionState(c7);
c7.state.current.write = c7.state.pending.write;
tls.queue(c7, tls.createRecord(c7, {
type: tls.ContentType.handshake,
data: tls.createFinished(c7)
}));
c7.expect = SCC;
tls.flush(c7);
c7.process();
}, "callback");
if (c6.session.certificateRequest === null || c6.session.clientCertificate === null) {
return callback(c6, null);
}
tls.getClientSignature(c6, callback);
};
tls.handleChangeCipherSpec = function(c6, record) {
if (record.fragment.getByte() !== 1) {
return c6.error(c6, {
message: "Invalid ChangeCipherSpec message received.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.illegal_parameter
}
});
}
var client = c6.entity === tls.ConnectionEnd.client;
if (c6.session.resuming && client || !c6.session.resuming && !client) {
c6.state.pending = tls.createConnectionState(c6);
}
c6.state.current.read = c6.state.pending.read;
if (!c6.session.resuming && client || c6.session.resuming && !client) {
c6.state.pending = null;
}
c6.expect = client ? SFI : CFI;
c6.process();
};
tls.handleFinished = function(c6, record, length) {
var b6 = record.fragment;
b6.read -= 4;
var msgBytes = b6.bytes();
b6.read += 4;
var vd = record.fragment.getBytes();
b6 = forge.util.createBuffer();
b6.putBuffer(c6.session.md5.digest());
b6.putBuffer(c6.session.sha1.digest());
var client = c6.entity === tls.ConnectionEnd.client;
var label = client ? "server finished" : "client finished";
var sp = c6.session.sp;
var vdl = 12;
var prf = prf_TLS1;
b6 = prf(sp.master_secret, label, b6.getBytes(), vdl);
if (b6.getBytes() !== vd) {
return c6.error(c6, {
message: "Invalid verify_data in Finished message.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.decrypt_error
}
});
}
c6.session.md5.update(msgBytes);
c6.session.sha1.update(msgBytes);
if (c6.session.resuming && client || !c6.session.resuming && !client) {
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.change_cipher_spec,
data: tls.createChangeCipherSpec()
}));
c6.state.current.write = c6.state.pending.write;
c6.state.pending = null;
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createFinished(c6)
}));
}
c6.expect = client ? SAD : CAD;
c6.handshaking = false;
++c6.handshakes;
c6.peerCertificate = client ? c6.session.serverCertificate : c6.session.clientCertificate;
tls.flush(c6);
c6.isConnected = true;
c6.connected(c6);
c6.process();
};
tls.handleAlert = function(c6, record) {
var b6 = record.fragment;
var alert = {
level: b6.getByte(),
description: b6.getByte()
};
var msg;
switch (alert.description) {
case tls.Alert.Description.close_notify:
msg = "Connection closed.";
break;
case tls.Alert.Description.unexpected_message:
msg = "Unexpected message.";
break;
case tls.Alert.Description.bad_record_mac:
msg = "Bad record MAC.";
break;
case tls.Alert.Description.decryption_failed:
msg = "Decryption failed.";
break;
case tls.Alert.Description.record_overflow:
msg = "Record overflow.";
break;
case tls.Alert.Description.decompression_failure:
msg = "Decompression failed.";
break;
case tls.Alert.Description.handshake_failure:
msg = "Handshake failure.";
break;
case tls.Alert.Description.bad_certificate:
msg = "Bad certificate.";
break;
case tls.Alert.Description.unsupported_certificate:
msg = "Unsupported certificate.";
break;
case tls.Alert.Description.certificate_revoked:
msg = "Certificate revoked.";
break;
case tls.Alert.Description.certificate_expired:
msg = "Certificate expired.";
break;
case tls.Alert.Description.certificate_unknown:
msg = "Certificate unknown.";
break;
case tls.Alert.Description.illegal_parameter:
msg = "Illegal parameter.";
break;
case tls.Alert.Description.unknown_ca:
msg = "Unknown certificate authority.";
break;
case tls.Alert.Description.access_denied:
msg = "Access denied.";
break;
case tls.Alert.Description.decode_error:
msg = "Decode error.";
break;
case tls.Alert.Description.decrypt_error:
msg = "Decrypt error.";
break;
case tls.Alert.Description.export_restriction:
msg = "Export restriction.";
break;
case tls.Alert.Description.protocol_version:
msg = "Unsupported protocol version.";
break;
case tls.Alert.Description.insufficient_security:
msg = "Insufficient security.";
break;
case tls.Alert.Description.internal_error:
msg = "Internal error.";
break;
case tls.Alert.Description.user_canceled:
msg = "User canceled.";
break;
case tls.Alert.Description.no_renegotiation:
msg = "Renegotiation not supported.";
break;
default:
msg = "Unknown error.";
break;
}
if (alert.description === tls.Alert.Description.close_notify) {
return c6.close();
}
c6.error(c6, {
message: msg,
send: false,
// origin is the opposite end
origin: c6.entity === tls.ConnectionEnd.client ? "server" : "client",
alert
});
c6.process();
};
tls.handleHandshake = function(c6, record) {
var b6 = record.fragment;
var type = b6.getByte();
var length = b6.getInt24();
if (length > b6.length()) {
c6.fragmented = record;
record.fragment = forge.util.createBuffer();
b6.read -= 4;
return c6.process();
}
c6.fragmented = null;
b6.read -= 4;
var bytes = b6.bytes(length + 4);
b6.read += 4;
if (type in hsTable[c6.entity][c6.expect]) {
if (c6.entity === tls.ConnectionEnd.server && !c6.open && !c6.fail) {
c6.handshaking = true;
c6.session = {
version: null,
extensions: {
server_name: {
serverNameList: []
}
},
cipherSuite: null,
compressionMethod: null,
serverCertificate: null,
clientCertificate: null,
md5: forge.md.md5.create(),
sha1: forge.md.sha1.create()
};
}
if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) {
c6.session.md5.update(bytes);
c6.session.sha1.update(bytes);
}
hsTable[c6.entity][c6.expect][type](c6, record, length);
} else {
tls.handleUnexpected(c6, record);
}
};
tls.handleApplicationData = function(c6, record) {
c6.data.putBuffer(record.fragment);
c6.dataReady(c6);
c6.process();
};
tls.handleHeartbeat = function(c6, record) {
var b6 = record.fragment;
var type = b6.getByte();
var length = b6.getInt16();
var payload = b6.getBytes(length);
if (type === tls.HeartbeatMessageType.heartbeat_request) {
if (c6.handshaking || length > payload.length) {
return c6.process();
}
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.heartbeat,
data: tls.createHeartbeat(
tls.HeartbeatMessageType.heartbeat_response,
payload
)
}));
tls.flush(c6);
} else if (type === tls.HeartbeatMessageType.heartbeat_response) {
if (payload !== c6.expectedHeartbeatPayload) {
return c6.process();
}
if (c6.heartbeatReceived) {
c6.heartbeatReceived(c6, forge.util.createBuffer(payload));
}
}
c6.process();
};
var SHE = 0;
var SCE = 1;
var SKE = 2;
var SCR = 3;
var SHD = 4;
var SCC = 5;
var SFI = 6;
var SAD = 7;
var SER = 8;
var CHE = 0;
var CCE = 1;
var CKE = 2;
var CCV = 3;
var CCC = 4;
var CFI = 5;
var CAD = 6;
var __ = tls.handleUnexpected;
var R0 = tls.handleChangeCipherSpec;
var R1 = tls.handleAlert;
var R22 = tls.handleHandshake;
var R3 = tls.handleApplicationData;
var R4 = tls.handleHeartbeat;
var ctTable = [];
ctTable[tls.ConnectionEnd.client] = [
// CC,AL,HS,AD,HB
/*SHE*/
[__, R1, R22, __, R4],
/*SCE*/
[__, R1, R22, __, R4],
/*SKE*/
[__, R1, R22, __, R4],
/*SCR*/
[__, R1, R22, __, R4],
/*SHD*/
[__, R1, R22, __, R4],
/*SCC*/
[R0, R1, __, __, R4],
/*SFI*/
[__, R1, R22, __, R4],
/*SAD*/
[__, R1, R22, R3, R4],
/*SER*/
[__, R1, R22, __, R4]
];
ctTable[tls.ConnectionEnd.server] = [
// CC,AL,HS,AD
/*CHE*/
[__, R1, R22, __, R4],
/*CCE*/
[__, R1, R22, __, R4],
/*CKE*/
[__, R1, R22, __, R4],
/*CCV*/
[__, R1, R22, __, R4],
/*CCC*/
[R0, R1, __, __, R4],
/*CFI*/
[__, R1, R22, __, R4],
/*CAD*/
[__, R1, R22, R3, R4],
/*CER*/
[__, R1, R22, __, R4]
];
var H0 = tls.handleHelloRequest;
var H1 = tls.handleServerHello;
var H22 = tls.handleCertificate;
var H32 = tls.handleServerKeyExchange;
var H4 = tls.handleCertificateRequest;
var H5 = tls.handleServerHelloDone;
var H6 = tls.handleFinished;
var hsTable = [];
hsTable[tls.ConnectionEnd.client] = [
// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI
/*SHE*/
[__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
/*SCE*/
[H0, __, __, __, __, __, __, __, __, __, __, H22, H32, H4, H5, __, __, __, __, __, __],
/*SKE*/
[H0, __, __, __, __, __, __, __, __, __, __, __, H32, H4, H5, __, __, __, __, __, __],
/*SCR*/
[H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __],
/*SHD*/
[H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __],
/*SCC*/
[H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
/*SFI*/
[H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6],
/*SAD*/
[H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
/*SER*/
[H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __]
];
var H7 = tls.handleClientHello;
var H8 = tls.handleClientKeyExchange;
var H9 = tls.handleCertificateVerify;
hsTable[tls.ConnectionEnd.server] = [
// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI
/*CHE*/
[__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
/*CCE*/
[__, __, __, __, __, __, __, __, __, __, __, H22, __, __, __, __, __, __, __, __, __],
/*CKE*/
[__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __],
/*CCV*/
[__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __],
/*CCC*/
[__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
/*CFI*/
[__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6],
/*CAD*/
[__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __],
/*CER*/
[__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __]
];
tls.generateKeys = function(c6, sp) {
var prf = prf_TLS1;
var random = sp.client_random + sp.server_random;
if (!c6.session.resuming) {
sp.master_secret = prf(
sp.pre_master_secret,
"master secret",
random,
48
).bytes();
sp.pre_master_secret = null;
}
random = sp.server_random + sp.client_random;
var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;
var tls10 = c6.version.major === tls.Versions.TLS_1_0.major && c6.version.minor === tls.Versions.TLS_1_0.minor;
if (tls10) {
length += 2 * sp.fixed_iv_length;
}
var km = prf(sp.master_secret, "key expansion", random, length);
var rval = {
client_write_MAC_key: km.getBytes(sp.mac_key_length),
server_write_MAC_key: km.getBytes(sp.mac_key_length),
client_write_key: km.getBytes(sp.enc_key_length),
server_write_key: km.getBytes(sp.enc_key_length)
};
if (tls10) {
rval.client_write_IV = km.getBytes(sp.fixed_iv_length);
rval.server_write_IV = km.getBytes(sp.fixed_iv_length);
}
return rval;
};
tls.createConnectionState = function(c6) {
var client = c6.entity === tls.ConnectionEnd.client;
var createMode = /* @__PURE__ */ __name(function() {
var mode = {
// two 32-bit numbers, first is most significant
sequenceNumber: [0, 0],
macKey: null,
macLength: 0,
macFunction: null,
cipherState: null,
cipherFunction: /* @__PURE__ */ __name(function(record) {
return true;
}, "cipherFunction"),
compressionState: null,
compressFunction: /* @__PURE__ */ __name(function(record) {
return true;
}, "compressFunction"),
updateSequenceNumber: /* @__PURE__ */ __name(function() {
if (mode.sequenceNumber[1] === 4294967295) {
mode.sequenceNumber[1] = 0;
++mode.sequenceNumber[0];
} else {
++mode.sequenceNumber[1];
}
}, "updateSequenceNumber")
};
return mode;
}, "createMode");
var state2 = {
read: createMode(),
write: createMode()
};
state2.read.update = function(c7, record) {
if (!state2.read.cipherFunction(record, state2.read)) {
c7.error(c7, {
message: "Could not decrypt record or bad MAC.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
// doesn't matter if decryption failed or MAC was
// invalid, return the same error so as not to reveal
// which one occurred
description: tls.Alert.Description.bad_record_mac
}
});
} else if (!state2.read.compressFunction(c7, record, state2.read)) {
c7.error(c7, {
message: "Could not decompress record.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.decompression_failure
}
});
}
return !c7.fail;
};
state2.write.update = function(c7, record) {
if (!state2.write.compressFunction(c7, record, state2.write)) {
c7.error(c7, {
message: "Could not compress record.",
send: false,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.internal_error
}
});
} else if (!state2.write.cipherFunction(record, state2.write)) {
c7.error(c7, {
message: "Could not encrypt record.",
send: false,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.internal_error
}
});
}
return !c7.fail;
};
if (c6.session) {
var sp = c6.session.sp;
c6.session.cipherSuite.initSecurityParameters(sp);
sp.keys = tls.generateKeys(c6, sp);
state2.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;
state2.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;
c6.session.cipherSuite.initConnectionState(state2, c6, sp);
switch (sp.compression_algorithm) {
case tls.CompressionMethod.none:
break;
case tls.CompressionMethod.deflate:
state2.read.compressFunction = inflate;
state2.write.compressFunction = deflate;
break;
default:
throw new Error("Unsupported compression algorithm.");
}
}
return state2;
};
tls.createRandom = function() {
var d6 = /* @__PURE__ */ new Date();
var utc = +d6 + d6.getTimezoneOffset() * 6e4;
var rval = forge.util.createBuffer();
rval.putInt32(utc);
rval.putBytes(forge.random.getBytes(28));
return rval;
};
tls.createRecord = function(c6, options) {
if (!options.data) {
return null;
}
var record = {
type: options.type,
version: {
major: c6.version.major,
minor: c6.version.minor
},
length: options.data.length(),
fragment: options.data
};
return record;
};
tls.createAlert = function(c6, alert) {
var b6 = forge.util.createBuffer();
b6.putByte(alert.level);
b6.putByte(alert.description);
return tls.createRecord(c6, {
type: tls.ContentType.alert,
data: b6
});
};
tls.createClientHello = function(c6) {
c6.session.clientHelloVersion = {
major: c6.version.major,
minor: c6.version.minor
};
var cipherSuites = forge.util.createBuffer();
for (var i5 = 0; i5 < c6.cipherSuites.length; ++i5) {
var cs2 = c6.cipherSuites[i5];
cipherSuites.putByte(cs2.id[0]);
cipherSuites.putByte(cs2.id[1]);
}
var cSuites = cipherSuites.length();
var compressionMethods = forge.util.createBuffer();
compressionMethods.putByte(tls.CompressionMethod.none);
var cMethods = compressionMethods.length();
var extensions = forge.util.createBuffer();
if (c6.virtualHost) {
var ext = forge.util.createBuffer();
ext.putByte(0);
ext.putByte(0);
var serverName = forge.util.createBuffer();
serverName.putByte(0);
writeVector(serverName, 2, forge.util.createBuffer(c6.virtualHost));
var snList = forge.util.createBuffer();
writeVector(snList, 2, serverName);
writeVector(ext, 2, snList);
extensions.putBuffer(ext);
}
var extLength = extensions.length();
if (extLength > 0) {
extLength += 2;
}
var sessionId = c6.session.id;
var length = sessionId.length + 1 + // session ID vector
2 + // version (major + minor)
4 + 28 + // random time and random bytes
2 + cSuites + // cipher suites vector
1 + cMethods + // compression methods vector
extLength;
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.client_hello);
rval.putInt24(length);
rval.putByte(c6.version.major);
rval.putByte(c6.version.minor);
rval.putBytes(c6.session.sp.client_random);
writeVector(rval, 1, forge.util.createBuffer(sessionId));
writeVector(rval, 2, cipherSuites);
writeVector(rval, 1, compressionMethods);
if (extLength > 0) {
writeVector(rval, 2, extensions);
}
return rval;
};
tls.createServerHello = function(c6) {
var sessionId = c6.session.id;
var length = sessionId.length + 1 + // session ID vector
2 + // version (major + minor)
4 + 28 + // random time and random bytes
2 + // chosen cipher suite
1;
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.server_hello);
rval.putInt24(length);
rval.putByte(c6.version.major);
rval.putByte(c6.version.minor);
rval.putBytes(c6.session.sp.server_random);
writeVector(rval, 1, forge.util.createBuffer(sessionId));
rval.putByte(c6.session.cipherSuite.id[0]);
rval.putByte(c6.session.cipherSuite.id[1]);
rval.putByte(c6.session.compressionMethod);
return rval;
};
tls.createCertificate = function(c6) {
var client = c6.entity === tls.ConnectionEnd.client;
var cert = null;
if (c6.getCertificate) {
var hint;
if (client) {
hint = c6.session.certificateRequest;
} else {
hint = c6.session.extensions.server_name.serverNameList;
}
cert = c6.getCertificate(c6, hint);
}
var certList = forge.util.createBuffer();
if (cert !== null) {
try {
if (!forge.util.isArray(cert)) {
cert = [cert];
}
var asn1 = null;
for (var i5 = 0; i5 < cert.length; ++i5) {
var msg = forge.pem.decode(cert[i5])[0];
if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") {
var error2 = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert certificate from PEM; PEM is encrypted.");
}
var der = forge.util.createBuffer(msg.body);
if (asn1 === null) {
asn1 = forge.asn1.fromDer(der.bytes(), false);
}
var certBuffer = forge.util.createBuffer();
writeVector(certBuffer, 3, der);
certList.putBuffer(certBuffer);
}
cert = forge.pki.certificateFromAsn1(asn1);
if (client) {
c6.session.clientCertificate = cert;
} else {
c6.session.serverCertificate = cert;
}
} catch (ex) {
return c6.error(c6, {
message: "Could not send certificate list.",
cause: ex,
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.bad_certificate
}
});
}
}
var length = 3 + certList.length();
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.certificate);
rval.putInt24(length);
writeVector(rval, 3, certList);
return rval;
};
tls.createClientKeyExchange = function(c6) {
var b6 = forge.util.createBuffer();
b6.putByte(c6.session.clientHelloVersion.major);
b6.putByte(c6.session.clientHelloVersion.minor);
b6.putBytes(forge.random.getBytes(46));
var sp = c6.session.sp;
sp.pre_master_secret = b6.getBytes();
var key2 = c6.session.serverCertificate.publicKey;
b6 = key2.encrypt(sp.pre_master_secret);
var length = b6.length + 2;
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.client_key_exchange);
rval.putInt24(length);
rval.putInt16(b6.length);
rval.putBytes(b6);
return rval;
};
tls.createServerKeyExchange = function(c6) {
var length = 0;
var rval = forge.util.createBuffer();
if (length > 0) {
rval.putByte(tls.HandshakeType.server_key_exchange);
rval.putInt24(length);
}
return rval;
};
tls.getClientSignature = function(c6, callback) {
var b6 = forge.util.createBuffer();
b6.putBuffer(c6.session.md5.digest());
b6.putBuffer(c6.session.sha1.digest());
b6 = b6.getBytes();
c6.getSignature = c6.getSignature || function(c7, b7, callback2) {
var privateKey = null;
if (c7.getPrivateKey) {
try {
privateKey = c7.getPrivateKey(c7, c7.session.clientCertificate);
privateKey = forge.pki.privateKeyFromPem(privateKey);
} catch (ex) {
c7.error(c7, {
message: "Could not get private key.",
cause: ex,
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.internal_error
}
});
}
}
if (privateKey === null) {
c7.error(c7, {
message: "No private key set.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.internal_error
}
});
} else {
b7 = privateKey.sign(b7, null);
}
callback2(c7, b7);
};
c6.getSignature(c6, b6, callback);
};
tls.createCertificateVerify = function(c6, signature) {
var length = signature.length + 2;
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.certificate_verify);
rval.putInt24(length);
rval.putInt16(signature.length);
rval.putBytes(signature);
return rval;
};
tls.createCertificateRequest = function(c6) {
var certTypes = forge.util.createBuffer();
certTypes.putByte(1);
var cAs = forge.util.createBuffer();
for (var key2 in c6.caStore.certs) {
var cert = c6.caStore.certs[key2];
var dn = forge.pki.distinguishedNameToAsn1(cert.subject);
var byteBuffer = forge.asn1.toDer(dn);
cAs.putInt16(byteBuffer.length());
cAs.putBuffer(byteBuffer);
}
var length = 1 + certTypes.length() + 2 + cAs.length();
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.certificate_request);
rval.putInt24(length);
writeVector(rval, 1, certTypes);
writeVector(rval, 2, cAs);
return rval;
};
tls.createServerHelloDone = function(c6) {
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.server_hello_done);
rval.putInt24(0);
return rval;
};
tls.createChangeCipherSpec = function() {
var rval = forge.util.createBuffer();
rval.putByte(1);
return rval;
};
tls.createFinished = function(c6) {
var b6 = forge.util.createBuffer();
b6.putBuffer(c6.session.md5.digest());
b6.putBuffer(c6.session.sha1.digest());
var client = c6.entity === tls.ConnectionEnd.client;
var sp = c6.session.sp;
var vdl = 12;
var prf = prf_TLS1;
var label = client ? "client finished" : "server finished";
b6 = prf(sp.master_secret, label, b6.getBytes(), vdl);
var rval = forge.util.createBuffer();
rval.putByte(tls.HandshakeType.finished);
rval.putInt24(b6.length());
rval.putBuffer(b6);
return rval;
};
tls.createHeartbeat = function(type, payload, payloadLength) {
if (typeof payloadLength === "undefined") {
payloadLength = payload.length;
}
var rval = forge.util.createBuffer();
rval.putByte(type);
rval.putInt16(payloadLength);
rval.putBytes(payload);
var plaintextLength = rval.length();
var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);
rval.putBytes(forge.random.getBytes(paddingLength));
return rval;
};
tls.queue = function(c6, record) {
if (!record) {
return;
}
if (record.fragment.length() === 0) {
if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) {
return;
}
}
if (record.type === tls.ContentType.handshake) {
var bytes = record.fragment.bytes();
c6.session.md5.update(bytes);
c6.session.sha1.update(bytes);
bytes = null;
}
var records;
if (record.fragment.length() <= tls.MaxFragment) {
records = [record];
} else {
records = [];
var data = record.fragment.bytes();
while (data.length > tls.MaxFragment) {
records.push(tls.createRecord(c6, {
type: record.type,
data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))
}));
data = data.slice(tls.MaxFragment);
}
if (data.length > 0) {
records.push(tls.createRecord(c6, {
type: record.type,
data: forge.util.createBuffer(data)
}));
}
}
for (var i5 = 0; i5 < records.length && !c6.fail; ++i5) {
var rec = records[i5];
var s5 = c6.state.current.write;
if (s5.update(c6, rec)) {
c6.records.push(rec);
}
}
};
tls.flush = function(c6) {
for (var i5 = 0; i5 < c6.records.length; ++i5) {
var record = c6.records[i5];
c6.tlsData.putByte(record.type);
c6.tlsData.putByte(record.version.major);
c6.tlsData.putByte(record.version.minor);
c6.tlsData.putInt16(record.fragment.length());
c6.tlsData.putBuffer(c6.records[i5].fragment);
}
c6.records = [];
return c6.tlsDataReady(c6);
};
var _certErrorToAlertDesc = /* @__PURE__ */ __name(function(error2) {
switch (error2) {
case true:
return true;
case forge.pki.certificateError.bad_certificate:
return tls.Alert.Description.bad_certificate;
case forge.pki.certificateError.unsupported_certificate:
return tls.Alert.Description.unsupported_certificate;
case forge.pki.certificateError.certificate_revoked:
return tls.Alert.Description.certificate_revoked;
case forge.pki.certificateError.certificate_expired:
return tls.Alert.Description.certificate_expired;
case forge.pki.certificateError.certificate_unknown:
return tls.Alert.Description.certificate_unknown;
case forge.pki.certificateError.unknown_ca:
return tls.Alert.Description.unknown_ca;
default:
return tls.Alert.Description.bad_certificate;
}
}, "_certErrorToAlertDesc");
var _alertDescToCertError = /* @__PURE__ */ __name(function(desc) {
switch (desc) {
case true:
return true;
case tls.Alert.Description.bad_certificate:
return forge.pki.certificateError.bad_certificate;
case tls.Alert.Description.unsupported_certificate:
return forge.pki.certificateError.unsupported_certificate;
case tls.Alert.Description.certificate_revoked:
return forge.pki.certificateError.certificate_revoked;
case tls.Alert.Description.certificate_expired:
return forge.pki.certificateError.certificate_expired;
case tls.Alert.Description.certificate_unknown:
return forge.pki.certificateError.certificate_unknown;
case tls.Alert.Description.unknown_ca:
return forge.pki.certificateError.unknown_ca;
default:
return forge.pki.certificateError.bad_certificate;
}
}, "_alertDescToCertError");
tls.verifyCertificateChain = function(c6, chain2) {
try {
var options = {};
for (var key2 in c6.verifyOptions) {
options[key2] = c6.verifyOptions[key2];
}
options.verify = function(vfd, depth, chain3) {
var desc = _certErrorToAlertDesc(vfd);
var ret = c6.verify(c6, vfd, depth, chain3);
if (ret !== true) {
if (typeof ret === "object" && !forge.util.isArray(ret)) {
var error2 = new Error("The application rejected the certificate.");
error2.send = true;
error2.alert = {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.bad_certificate
};
if (ret.message) {
error2.message = ret.message;
}
if (ret.alert) {
error2.alert.description = ret.alert;
}
throw error2;
}
if (ret !== vfd) {
ret = _alertDescToCertError(ret);
}
}
return ret;
};
forge.pki.verifyCertificateChain(c6.caStore, chain2, options);
} catch (ex) {
var err = ex;
if (typeof err !== "object" || forge.util.isArray(err)) {
err = {
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: _certErrorToAlertDesc(ex)
}
};
}
if (!("send" in err)) {
err.send = true;
}
if (!("alert" in err)) {
err.alert = {
level: tls.Alert.Level.fatal,
description: _certErrorToAlertDesc(err.error)
};
}
c6.error(c6, err);
}
return !c6.fail;
};
tls.createSessionCache = function(cache6, capacity) {
var rval = null;
if (cache6 && cache6.getSession && cache6.setSession && cache6.order) {
rval = cache6;
} else {
rval = {};
rval.cache = cache6 || {};
rval.capacity = Math.max(capacity || 100, 1);
rval.order = [];
for (var key2 in cache6) {
if (rval.order.length <= capacity) {
rval.order.push(key2);
} else {
delete cache6[key2];
}
}
rval.getSession = function(sessionId) {
var session = null;
var key3 = null;
if (sessionId) {
key3 = forge.util.bytesToHex(sessionId);
} else if (rval.order.length > 0) {
key3 = rval.order[0];
}
if (key3 !== null && key3 in rval.cache) {
session = rval.cache[key3];
delete rval.cache[key3];
for (var i5 in rval.order) {
if (rval.order[i5] === key3) {
rval.order.splice(i5, 1);
break;
}
}
}
return session;
};
rval.setSession = function(sessionId, session) {
if (rval.order.length === rval.capacity) {
var key3 = rval.order.shift();
delete rval.cache[key3];
}
var key3 = forge.util.bytesToHex(sessionId);
rval.order.push(key3);
rval.cache[key3] = session;
};
}
return rval;
};
tls.createConnection = function(options) {
var caStore = null;
if (options.caStore) {
if (forge.util.isArray(options.caStore)) {
caStore = forge.pki.createCaStore(options.caStore);
} else {
caStore = options.caStore;
}
} else {
caStore = forge.pki.createCaStore();
}
var cipherSuites = options.cipherSuites || null;
if (cipherSuites === null) {
cipherSuites = [];
for (var key2 in tls.CipherSuites) {
cipherSuites.push(tls.CipherSuites[key2]);
}
}
var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client;
var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null;
var c6 = {
version: { major: tls.Version.major, minor: tls.Version.minor },
entity,
sessionId: options.sessionId,
caStore,
sessionCache,
cipherSuites,
connected: options.connected,
virtualHost: options.virtualHost || null,
verifyClient: options.verifyClient || false,
verify: options.verify || function(cn2, vfd, dpth, cts) {
return vfd;
},
verifyOptions: options.verifyOptions || {},
getCertificate: options.getCertificate || null,
getPrivateKey: options.getPrivateKey || null,
getSignature: options.getSignature || null,
input: forge.util.createBuffer(),
tlsData: forge.util.createBuffer(),
data: forge.util.createBuffer(),
tlsDataReady: options.tlsDataReady,
dataReady: options.dataReady,
heartbeatReceived: options.heartbeatReceived,
closed: options.closed,
error: /* @__PURE__ */ __name(function(c7, ex) {
ex.origin = ex.origin || (c7.entity === tls.ConnectionEnd.client ? "client" : "server");
if (ex.send) {
tls.queue(c7, tls.createAlert(c7, ex.alert));
tls.flush(c7);
}
var fatal = ex.fatal !== false;
if (fatal) {
c7.fail = true;
}
options.error(c7, ex);
if (fatal) {
c7.close(false);
}
}, "error"),
deflate: options.deflate || null,
inflate: options.inflate || null
};
c6.reset = function(clearFail) {
c6.version = { major: tls.Version.major, minor: tls.Version.minor };
c6.record = null;
c6.session = null;
c6.peerCertificate = null;
c6.state = {
pending: null,
current: null
};
c6.expect = c6.entity === tls.ConnectionEnd.client ? SHE : CHE;
c6.fragmented = null;
c6.records = [];
c6.open = false;
c6.handshakes = 0;
c6.handshaking = false;
c6.isConnected = false;
c6.fail = !(clearFail || typeof clearFail === "undefined");
c6.input.clear();
c6.tlsData.clear();
c6.data.clear();
c6.state.current = tls.createConnectionState(c6);
};
c6.reset();
var _update = /* @__PURE__ */ __name(function(c7, record) {
var aligned = record.type - tls.ContentType.change_cipher_spec;
var handlers2 = ctTable[c7.entity][c7.expect];
if (aligned in handlers2) {
handlers2[aligned](c7, record);
} else {
tls.handleUnexpected(c7, record);
}
}, "_update");
var _readRecordHeader = /* @__PURE__ */ __name(function(c7) {
var rval = 0;
var b6 = c7.input;
var len = b6.length();
if (len < 5) {
rval = 5 - len;
} else {
c7.record = {
type: b6.getByte(),
version: {
major: b6.getByte(),
minor: b6.getByte()
},
length: b6.getInt16(),
fragment: forge.util.createBuffer(),
ready: false
};
var compatibleVersion = c7.record.version.major === c7.version.major;
if (compatibleVersion && c7.session && c7.session.version) {
compatibleVersion = c7.record.version.minor === c7.version.minor;
}
if (!compatibleVersion) {
c7.error(c7, {
message: "Incompatible TLS version.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.protocol_version
}
});
}
}
return rval;
}, "_readRecordHeader");
var _readRecord = /* @__PURE__ */ __name(function(c7) {
var rval = 0;
var b6 = c7.input;
var len = b6.length();
if (len < c7.record.length) {
rval = c7.record.length - len;
} else {
c7.record.fragment.putBytes(b6.getBytes(c7.record.length));
b6.compact();
var s5 = c7.state.current.read;
if (s5.update(c7, c7.record)) {
if (c7.fragmented !== null) {
if (c7.fragmented.type === c7.record.type) {
c7.fragmented.fragment.putBuffer(c7.record.fragment);
c7.record = c7.fragmented;
} else {
c7.error(c7, {
message: "Invalid fragmented record.",
send: true,
alert: {
level: tls.Alert.Level.fatal,
description: tls.Alert.Description.unexpected_message
}
});
}
}
c7.record.ready = true;
}
}
return rval;
}, "_readRecord");
c6.handshake = function(sessionId) {
if (c6.entity !== tls.ConnectionEnd.client) {
c6.error(c6, {
message: "Cannot initiate handshake as a server.",
fatal: false
});
} else if (c6.handshaking) {
c6.error(c6, {
message: "Handshake already in progress.",
fatal: false
});
} else {
if (c6.fail && !c6.open && c6.handshakes === 0) {
c6.fail = false;
}
c6.handshaking = true;
sessionId = sessionId || "";
var session = null;
if (sessionId.length > 0) {
if (c6.sessionCache) {
session = c6.sessionCache.getSession(sessionId);
}
if (session === null) {
sessionId = "";
}
}
if (sessionId.length === 0 && c6.sessionCache) {
session = c6.sessionCache.getSession();
if (session !== null) {
sessionId = session.id;
}
}
c6.session = {
id: sessionId,
version: null,
cipherSuite: null,
compressionMethod: null,
serverCertificate: null,
certificateRequest: null,
clientCertificate: null,
sp: {},
md5: forge.md.md5.create(),
sha1: forge.md.sha1.create()
};
if (session) {
c6.version = session.version;
c6.session.sp = session.sp;
}
c6.session.sp.client_random = tls.createRandom().getBytes();
c6.open = true;
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.handshake,
data: tls.createClientHello(c6)
}));
tls.flush(c6);
}
};
c6.process = function(data) {
var rval = 0;
if (data) {
c6.input.putBytes(data);
}
if (!c6.fail) {
if (c6.record !== null && c6.record.ready && c6.record.fragment.isEmpty()) {
c6.record = null;
}
if (c6.record === null) {
rval = _readRecordHeader(c6);
}
if (!c6.fail && c6.record !== null && !c6.record.ready) {
rval = _readRecord(c6);
}
if (!c6.fail && c6.record !== null && c6.record.ready) {
_update(c6, c6.record);
}
}
return rval;
};
c6.prepare = function(data) {
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.application_data,
data: forge.util.createBuffer(data)
}));
return tls.flush(c6);
};
c6.prepareHeartbeatRequest = function(payload, payloadLength) {
if (payload instanceof forge.util.ByteBuffer) {
payload = payload.bytes();
}
if (typeof payloadLength === "undefined") {
payloadLength = payload.length;
}
c6.expectedHeartbeatPayload = payload;
tls.queue(c6, tls.createRecord(c6, {
type: tls.ContentType.heartbeat,
data: tls.createHeartbeat(
tls.HeartbeatMessageType.heartbeat_request,
payload,
payloadLength
)
}));
return tls.flush(c6);
};
c6.close = function(clearFail) {
if (!c6.fail && c6.sessionCache && c6.session) {
var session = {
id: c6.session.id,
version: c6.session.version,
sp: c6.session.sp
};
session.sp.keys = null;
c6.sessionCache.setSession(session.id, session);
}
if (c6.open) {
c6.open = false;
c6.input.clear();
if (c6.isConnected || c6.handshaking) {
c6.isConnected = c6.handshaking = false;
tls.queue(c6, tls.createAlert(c6, {
level: tls.Alert.Level.warning,
description: tls.Alert.Description.close_notify
}));
tls.flush(c6);
}
c6.closed(c6);
}
c6.reset(clearFail);
};
return c6;
};
module3.exports = forge.tls = forge.tls || {};
for (key in tls) {
if (typeof tls[key] !== "function") {
forge.tls[key] = tls[key];
}
}
var key;
forge.tls.prf_tls1 = prf_TLS1;
forge.tls.hmac_sha1 = hmac_sha1;
forge.tls.createSessionCache = tls.createSessionCache;
forge.tls.createConnection = tls.createConnection;
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/aesCipherSuites.js
var require_aesCipherSuites = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/aesCipherSuites.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_aes();
require_tls();
var tls = module3.exports = forge.tls;
tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = {
id: [0, 47],
name: "TLS_RSA_WITH_AES_128_CBC_SHA",
initSecurityParameters: /* @__PURE__ */ __name(function(sp) {
sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;
sp.cipher_type = tls.CipherType.block;
sp.enc_key_length = 16;
sp.block_length = 16;
sp.fixed_iv_length = 16;
sp.record_iv_length = 16;
sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;
sp.mac_length = 20;
sp.mac_key_length = 20;
}, "initSecurityParameters"),
initConnectionState
};
tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = {
id: [0, 53],
name: "TLS_RSA_WITH_AES_256_CBC_SHA",
initSecurityParameters: /* @__PURE__ */ __name(function(sp) {
sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;
sp.cipher_type = tls.CipherType.block;
sp.enc_key_length = 32;
sp.block_length = 16;
sp.fixed_iv_length = 16;
sp.record_iv_length = 16;
sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;
sp.mac_length = 20;
sp.mac_key_length = 20;
}, "initSecurityParameters"),
initConnectionState
};
function initConnectionState(state2, c6, sp) {
var client = c6.entity === forge.tls.ConnectionEnd.client;
state2.read.cipherState = {
init: false,
cipher: forge.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key),
iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV
};
state2.write.cipherState = {
init: false,
cipher: forge.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key),
iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV
};
state2.read.cipherFunction = decrypt_aes_cbc_sha1;
state2.write.cipherFunction = encrypt_aes_cbc_sha1;
state2.read.macLength = state2.write.macLength = sp.mac_length;
state2.read.macFunction = state2.write.macFunction = tls.hmac_sha1;
}
__name(initConnectionState, "initConnectionState");
function encrypt_aes_cbc_sha1(record, s5) {
var rval = false;
var mac = s5.macFunction(s5.macKey, s5.sequenceNumber, record);
record.fragment.putBytes(mac);
s5.updateSequenceNumber();
var iv;
if (record.version.minor === tls.Versions.TLS_1_0.minor) {
iv = s5.cipherState.init ? null : s5.cipherState.iv;
} else {
iv = forge.random.getBytesSync(16);
}
s5.cipherState.init = true;
var cipher = s5.cipherState.cipher;
cipher.start({ iv });
if (record.version.minor >= tls.Versions.TLS_1_1.minor) {
cipher.output.putBytes(iv);
}
cipher.update(record.fragment);
if (cipher.finish(encrypt_aes_cbc_sha1_padding)) {
record.fragment = cipher.output;
record.length = record.fragment.length();
rval = true;
}
return rval;
}
__name(encrypt_aes_cbc_sha1, "encrypt_aes_cbc_sha1");
function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {
if (!decrypt) {
var padding = blockSize - input.length() % blockSize;
input.fillWithByte(padding - 1, padding);
}
return true;
}
__name(encrypt_aes_cbc_sha1_padding, "encrypt_aes_cbc_sha1_padding");
function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {
var rval = true;
if (decrypt) {
var len = output.length();
var paddingLength = output.last();
for (var i5 = len - 1 - paddingLength; i5 < len - 1; ++i5) {
rval = rval && output.at(i5) == paddingLength;
}
if (rval) {
output.truncate(paddingLength + 1);
}
}
return rval;
}
__name(decrypt_aes_cbc_sha1_padding, "decrypt_aes_cbc_sha1_padding");
function decrypt_aes_cbc_sha1(record, s5) {
var rval = false;
var iv;
if (record.version.minor === tls.Versions.TLS_1_0.minor) {
iv = s5.cipherState.init ? null : s5.cipherState.iv;
} else {
iv = record.fragment.getBytes(16);
}
s5.cipherState.init = true;
var cipher = s5.cipherState.cipher;
cipher.start({ iv });
cipher.update(record.fragment);
rval = cipher.finish(decrypt_aes_cbc_sha1_padding);
var macLen = s5.macLength;
var mac = forge.random.getBytesSync(macLen);
var len = cipher.output.length();
if (len >= macLen) {
record.fragment = cipher.output.getBytes(len - macLen);
mac = cipher.output.getBytes(macLen);
} else {
record.fragment = cipher.output.getBytes();
}
record.fragment = forge.util.createBuffer(record.fragment);
record.length = record.fragment.length();
var mac2 = s5.macFunction(s5.macKey, s5.sequenceNumber, record);
s5.updateSequenceNumber();
rval = compareMacs(s5.macKey, mac, mac2) && rval;
return rval;
}
__name(decrypt_aes_cbc_sha1, "decrypt_aes_cbc_sha1");
function compareMacs(key, mac1, mac2) {
var hmac2 = forge.hmac.create();
hmac2.start("SHA1", key);
hmac2.update(mac1);
mac1 = hmac2.digest().getBytes();
hmac2.start(null, null);
hmac2.update(mac2);
mac2 = hmac2.digest().getBytes();
return mac1 === mac2;
}
__name(compareMacs, "compareMacs");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha512.js
var require_sha512 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha512.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_md();
require_util10();
var sha512 = module3.exports = forge.sha512 = forge.sha512 || {};
forge.md.sha512 = forge.md.algorithms.sha512 = sha512;
var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};
sha384.create = function() {
return sha512.create("SHA-384");
};
forge.md.sha384 = forge.md.algorithms.sha384 = sha384;
forge.sha512.sha256 = forge.sha512.sha256 || {
create: /* @__PURE__ */ __name(function() {
return sha512.create("SHA-512/256");
}, "create")
};
forge.md["sha512/256"] = forge.md.algorithms["sha512/256"] = forge.sha512.sha256;
forge.sha512.sha224 = forge.sha512.sha224 || {
create: /* @__PURE__ */ __name(function() {
return sha512.create("SHA-512/224");
}, "create")
};
forge.md["sha512/224"] = forge.md.algorithms["sha512/224"] = forge.sha512.sha224;
sha512.create = function(algorithm) {
if (!_initialized) {
_init();
}
if (typeof algorithm === "undefined") {
algorithm = "SHA-512";
}
if (!(algorithm in _states)) {
throw new Error("Invalid SHA-512 algorithm: " + algorithm);
}
var _state = _states[algorithm];
var _h = null;
var _input = forge.util.createBuffer();
var _w2 = new Array(80);
for (var wi = 0; wi < 80; ++wi) {
_w2[wi] = new Array(2);
}
var digestLength = 64;
switch (algorithm) {
case "SHA-384":
digestLength = 48;
break;
case "SHA-512/256":
digestLength = 32;
break;
case "SHA-512/224":
digestLength = 28;
break;
}
var md = {
// SHA-512 => sha512
algorithm: algorithm.replace("-", "").toLowerCase(),
blockLength: 128,
digestLength,
// 56-bit length of message so far (does not including padding)
messageLength: 0,
// true message length
fullMessageLength: null,
// size of message length in bytes
messageLengthSize: 16
};
md.start = function() {
md.messageLength = 0;
md.fullMessageLength = md.messageLength128 = [];
var int32s = md.messageLengthSize / 4;
for (var i5 = 0; i5 < int32s; ++i5) {
md.fullMessageLength.push(0);
}
_input = forge.util.createBuffer();
_h = new Array(_state.length);
for (var i5 = 0; i5 < _state.length; ++i5) {
_h[i5] = _state[i5].slice(0);
}
return md;
};
md.start();
md.update = function(msg, encoding) {
if (encoding === "utf8") {
msg = forge.util.encodeUtf8(msg);
}
var len = msg.length;
md.messageLength += len;
len = [len / 4294967296 >>> 0, len >>> 0];
for (var i5 = md.fullMessageLength.length - 1; i5 >= 0; --i5) {
md.fullMessageLength[i5] += len[1];
len[1] = len[0] + (md.fullMessageLength[i5] / 4294967296 >>> 0);
md.fullMessageLength[i5] = md.fullMessageLength[i5] >>> 0;
len[0] = len[1] / 4294967296 >>> 0;
}
_input.putBytes(msg);
_update(_h, _w2, _input);
if (_input.read > 2048 || _input.length() === 0) {
_input.compact();
}
return md;
};
md.digest = function() {
var finalBlock = forge.util.createBuffer();
finalBlock.putBytes(_input.bytes());
var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize;
var overflow = remaining & md.blockLength - 1;
finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
var next, carry;
var bits = md.fullMessageLength[0] * 8;
for (var i5 = 0; i5 < md.fullMessageLength.length - 1; ++i5) {
next = md.fullMessageLength[i5 + 1] * 8;
carry = next / 4294967296 >>> 0;
bits += carry;
finalBlock.putInt32(bits >>> 0);
bits = next >>> 0;
}
finalBlock.putInt32(bits);
var h6 = new Array(_h.length);
for (var i5 = 0; i5 < _h.length; ++i5) {
h6[i5] = _h[i5].slice(0);
}
_update(h6, _w2, finalBlock);
var rval = forge.util.createBuffer();
var hlen;
if (algorithm === "SHA-512") {
hlen = h6.length;
} else if (algorithm === "SHA-384") {
hlen = h6.length - 2;
} else {
hlen = h6.length - 4;
}
for (var i5 = 0; i5 < hlen; ++i5) {
rval.putInt32(h6[i5][0]);
if (i5 !== hlen - 1 || algorithm !== "SHA-512/224") {
rval.putInt32(h6[i5][1]);
}
}
return rval;
};
return md;
};
var _padding = null;
var _initialized = false;
var _k = null;
var _states = null;
function _init() {
_padding = String.fromCharCode(128);
_padding += forge.util.fillString(String.fromCharCode(0), 128);
_k = [
[1116352408, 3609767458],
[1899447441, 602891725],
[3049323471, 3964484399],
[3921009573, 2173295548],
[961987163, 4081628472],
[1508970993, 3053834265],
[2453635748, 2937671579],
[2870763221, 3664609560],
[3624381080, 2734883394],
[310598401, 1164996542],
[607225278, 1323610764],
[1426881987, 3590304994],
[1925078388, 4068182383],
[2162078206, 991336113],
[2614888103, 633803317],
[3248222580, 3479774868],
[3835390401, 2666613458],
[4022224774, 944711139],
[264347078, 2341262773],
[604807628, 2007800933],
[770255983, 1495990901],
[1249150122, 1856431235],
[1555081692, 3175218132],
[1996064986, 2198950837],
[2554220882, 3999719339],
[2821834349, 766784016],
[2952996808, 2566594879],
[3210313671, 3203337956],
[3336571891, 1034457026],
[3584528711, 2466948901],
[113926993, 3758326383],
[338241895, 168717936],
[666307205, 1188179964],
[773529912, 1546045734],
[1294757372, 1522805485],
[1396182291, 2643833823],
[1695183700, 2343527390],
[1986661051, 1014477480],
[2177026350, 1206759142],
[2456956037, 344077627],
[2730485921, 1290863460],
[2820302411, 3158454273],
[3259730800, 3505952657],
[3345764771, 106217008],
[3516065817, 3606008344],
[3600352804, 1432725776],
[4094571909, 1467031594],
[275423344, 851169720],
[430227734, 3100823752],
[506948616, 1363258195],
[659060556, 3750685593],
[883997877, 3785050280],
[958139571, 3318307427],
[1322822218, 3812723403],
[1537002063, 2003034995],
[1747873779, 3602036899],
[1955562222, 1575990012],
[2024104815, 1125592928],
[2227730452, 2716904306],
[2361852424, 442776044],
[2428436474, 593698344],
[2756734187, 3733110249],
[3204031479, 2999351573],
[3329325298, 3815920427],
[3391569614, 3928383900],
[3515267271, 566280711],
[3940187606, 3454069534],
[4118630271, 4000239992],
[116418474, 1914138554],
[174292421, 2731055270],
[289380356, 3203993006],
[460393269, 320620315],
[685471733, 587496836],
[852142971, 1086792851],
[1017036298, 365543100],
[1126000580, 2618297676],
[1288033470, 3409855158],
[1501505948, 4234509866],
[1607167915, 987167468],
[1816402316, 1246189591]
];
_states = {};
_states["SHA-512"] = [
[1779033703, 4089235720],
[3144134277, 2227873595],
[1013904242, 4271175723],
[2773480762, 1595750129],
[1359893119, 2917565137],
[2600822924, 725511199],
[528734635, 4215389547],
[1541459225, 327033209]
];
_states["SHA-384"] = [
[3418070365, 3238371032],
[1654270250, 914150663],
[2438529370, 812702999],
[355462360, 4144912697],
[1731405415, 4290775857],
[2394180231, 1750603025],
[3675008525, 1694076839],
[1203062813, 3204075428]
];
_states["SHA-512/256"] = [
[573645204, 4230739756],
[2673172387, 3360449730],
[596883563, 1867755857],
[2520282905, 1497426621],
[2519219938, 2827943907],
[3193839141, 1401305490],
[721525244, 746961066],
[246885852, 2177182882]
];
_states["SHA-512/224"] = [
[2352822216, 424955298],
[1944164710, 2312950998],
[502970286, 855612546],
[1738396948, 1479516111],
[258812777, 2077511080],
[2011393907, 79989058],
[1067287976, 1780299464],
[286451373, 2446758561]
];
_initialized = true;
}
__name(_init, "_init");
function _update(s5, w6, bytes) {
var t1_hi, t1_lo;
var t2_hi, t2_lo;
var s0_hi, s0_lo;
var s1_hi, s1_lo;
var ch_hi, ch_lo;
var maj_hi, maj_lo;
var a_hi, a_lo;
var b_hi, b_lo;
var c_hi, c_lo;
var d_hi, d_lo;
var e_hi, e_lo;
var f_hi, f_lo;
var g_hi, g_lo;
var h_hi, h_lo;
var i5, hi, lo, w22, w7, w15, w16;
var len = bytes.length();
while (len >= 128) {
for (i5 = 0; i5 < 16; ++i5) {
w6[i5][0] = bytes.getInt32() >>> 0;
w6[i5][1] = bytes.getInt32() >>> 0;
}
for (; i5 < 80; ++i5) {
w22 = w6[i5 - 2];
hi = w22[0];
lo = w22[1];
t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19
(lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29)
hi >>> 6) >>> 0;
t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19
(lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29)
(hi << 26 | lo >>> 6)) >>> 0;
w15 = w6[i5 - 15];
hi = w15[0];
lo = w15[1];
t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1
(hi >>> 8 | lo << 24) ^ // ROTR 8
hi >>> 7) >>> 0;
t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1
(hi << 24 | lo >>> 8) ^ // ROTR 8
(hi << 25 | lo >>> 7)) >>> 0;
w7 = w6[i5 - 7];
w16 = w6[i5 - 16];
lo = t1_lo + w7[1] + t2_lo + w16[1];
w6[i5][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0;
w6[i5][1] = lo >>> 0;
}
a_hi = s5[0][0];
a_lo = s5[0][1];
b_hi = s5[1][0];
b_lo = s5[1][1];
c_hi = s5[2][0];
c_lo = s5[2][1];
d_hi = s5[3][0];
d_lo = s5[3][1];
e_hi = s5[4][0];
e_lo = s5[4][1];
f_hi = s5[5][0];
f_lo = s5[5][1];
g_hi = s5[6][0];
g_lo = s5[6][1];
h_hi = s5[7][0];
h_lo = s5[7][1];
for (i5 = 0; i5 < 80; ++i5) {
s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14
(e_hi >>> 18 | e_lo << 14) ^ // ROTR 18
(e_lo >>> 9 | e_hi << 23)) >>> 0;
s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14
(e_hi << 14 | e_lo >>> 18) ^ // ROTR 18
(e_lo << 23 | e_hi >>> 9)) >>> 0;
ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0;
ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0;
s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28
(a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2)
(a_lo >>> 7 | a_hi << 25)) >>> 0;
s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28
(a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2)
(a_lo << 25 | a_hi >>> 7)) >>> 0;
maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0;
maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0;
lo = h_lo + s1_lo + ch_lo + _k[i5][1] + w6[i5][1];
t1_hi = h_hi + s1_hi + ch_hi + _k[i5][0] + w6[i5][0] + (lo / 4294967296 >>> 0) >>> 0;
t1_lo = lo >>> 0;
lo = s0_lo + maj_lo;
t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0;
t2_lo = lo >>> 0;
h_hi = g_hi;
h_lo = g_lo;
g_hi = f_hi;
g_lo = f_lo;
f_hi = e_hi;
f_lo = e_lo;
lo = d_lo + t1_lo;
e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0;
e_lo = lo >>> 0;
d_hi = c_hi;
d_lo = c_lo;
c_hi = b_hi;
c_lo = b_lo;
b_hi = a_hi;
b_lo = a_lo;
lo = t1_lo + t2_lo;
a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0;
a_lo = lo >>> 0;
}
lo = s5[0][1] + a_lo;
s5[0][0] = s5[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[0][1] = lo >>> 0;
lo = s5[1][1] + b_lo;
s5[1][0] = s5[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[1][1] = lo >>> 0;
lo = s5[2][1] + c_lo;
s5[2][0] = s5[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[2][1] = lo >>> 0;
lo = s5[3][1] + d_lo;
s5[3][0] = s5[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[3][1] = lo >>> 0;
lo = s5[4][1] + e_lo;
s5[4][0] = s5[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[4][1] = lo >>> 0;
lo = s5[5][1] + f_lo;
s5[5][0] = s5[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[5][1] = lo >>> 0;
lo = s5[6][1] + g_lo;
s5[6][0] = s5[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[6][1] = lo >>> 0;
lo = s5[7][1] + h_lo;
s5[7][0] = s5[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0;
s5[7][1] = lo >>> 0;
len -= 128;
}
}
__name(_update, "_update");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/asn1-validator.js
var require_asn1_validator = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/asn1-validator.js"(exports2) {
init_import_meta_url();
var forge = require_forge();
require_asn1();
var asn1 = forge.asn1;
exports2.privateKeyValidator = {
// PrivateKeyInfo
name: "PrivateKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// Version (INTEGER)
name: "PrivateKeyInfo.version",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: "privateKeyVersion"
}, {
// privateKeyAlgorithm
name: "PrivateKeyInfo.privateKeyAlgorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "privateKeyOid"
}]
}, {
// PrivateKey
name: "PrivateKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: "privateKey"
}]
};
exports2.publicKeyValidator = {
name: "SubjectPublicKeyInfo",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: "subjectPublicKeyInfo",
value: [
{
name: "SubjectPublicKeyInfo.AlgorithmIdentifier",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: "AlgorithmIdentifier.algorithm",
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: "publicKeyOid"
}]
},
// capture group for ed25519PublicKey
{
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
composed: true,
captureBitStringValue: "ed25519PublicKey"
}
// FIXME: this is capture group for rsaPublicKey, use it in this API or
// discard?
/* {
// subjectPublicKey
name: 'SubjectPublicKeyInfo.subjectPublicKey',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
value: [{
// RSAPublicKey
name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
optional: true,
captureAsn1: 'rsaPublicKey'
}]
} */
]
};
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/ed25519.js
var require_ed25519 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/ed25519.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_jsbn();
require_random2();
require_sha512();
require_util10();
var asn1Validator = require_asn1_validator();
var publicKeyValidator = asn1Validator.publicKeyValidator;
var privateKeyValidator = asn1Validator.privateKeyValidator;
if (typeof BigInteger === "undefined") {
BigInteger = forge.jsbn.BigInteger;
}
var BigInteger;
var ByteBuffer = forge.util.ByteBuffer;
var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer;
forge.pki = forge.pki || {};
module3.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};
var ed25519 = forge.ed25519;
ed25519.constants = {};
ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;
ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;
ed25519.constants.SEED_BYTE_LENGTH = 32;
ed25519.constants.SIGN_BYTE_LENGTH = 64;
ed25519.constants.HASH_BYTE_LENGTH = 64;
ed25519.generateKeyPair = function(options) {
options = options || {};
var seed = options.seed;
if (seed === void 0) {
seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);
} else if (typeof seed === "string") {
if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {
throw new TypeError(
'"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length."
);
}
} else if (!(seed instanceof Uint8Array)) {
throw new TypeError(
'"seed" must be a node.js Buffer, Uint8Array, or a binary string.'
);
}
seed = messageToNativeBuffer({ message: seed, encoding: "binary" });
var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
for (var i5 = 0; i5 < 32; ++i5) {
sk[i5] = seed[i5];
}
crypto_sign_keypair(pk, sk);
return { publicKey: pk, privateKey: sk };
};
ed25519.privateKeyFromAsn1 = function(obj) {
var capture = {};
var errors = [];
var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);
if (!valid) {
var error2 = new Error("Invalid Key.");
error2.errors = errors;
throw error2;
}
var oid = forge.asn1.derToOid(capture.privateKeyOid);
var ed25519Oid = forge.oids.EdDSA25519;
if (oid !== ed25519Oid) {
throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".');
}
var privateKey = capture.privateKey;
var privateKeyBytes = messageToNativeBuffer({
message: forge.asn1.fromDer(privateKey).value,
encoding: "binary"
});
return { privateKeyBytes };
};
ed25519.publicKeyFromAsn1 = function(obj) {
var capture = {};
var errors = [];
var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);
if (!valid) {
var error2 = new Error("Invalid Key.");
error2.errors = errors;
throw error2;
}
var oid = forge.asn1.derToOid(capture.publicKeyOid);
var ed25519Oid = forge.oids.EdDSA25519;
if (oid !== ed25519Oid) {
throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".');
}
var publicKeyBytes = capture.ed25519PublicKey;
if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
throw new Error("Key length is invalid.");
}
return messageToNativeBuffer({
message: publicKeyBytes,
encoding: "binary"
});
};
ed25519.publicKeyFromPrivateKey = function(options) {
options = options || {};
var privateKey = messageToNativeBuffer({
message: options.privateKey,
encoding: "binary"
});
if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {
throw new TypeError(
'"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH
);
}
var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
for (var i5 = 0; i5 < pk.length; ++i5) {
pk[i5] = privateKey[32 + i5];
}
return pk;
};
ed25519.sign = function(options) {
options = options || {};
var msg = messageToNativeBuffer(options);
var privateKey = messageToNativeBuffer({
message: options.privateKey,
encoding: "binary"
});
if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {
var keyPair = ed25519.generateKeyPair({ seed: privateKey });
privateKey = keyPair.privateKey;
} else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {
throw new TypeError(
'"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH
);
}
var signedMsg = new NativeBuffer(
ed25519.constants.SIGN_BYTE_LENGTH + msg.length
);
crypto_sign(signedMsg, msg, msg.length, privateKey);
var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);
for (var i5 = 0; i5 < sig.length; ++i5) {
sig[i5] = signedMsg[i5];
}
return sig;
};
ed25519.verify = function(options) {
options = options || {};
var msg = messageToNativeBuffer(options);
if (options.signature === void 0) {
throw new TypeError(
'"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.'
);
}
var sig = messageToNativeBuffer({
message: options.signature,
encoding: "binary"
});
if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {
throw new TypeError(
'"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH
);
}
var publicKey = messageToNativeBuffer({
message: options.publicKey,
encoding: "binary"
});
if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
throw new TypeError(
'"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH
);
}
var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
var m6 = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
var i5;
for (i5 = 0; i5 < ed25519.constants.SIGN_BYTE_LENGTH; ++i5) {
sm[i5] = sig[i5];
}
for (i5 = 0; i5 < msg.length; ++i5) {
sm[i5 + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i5];
}
return crypto_sign_open(m6, sm, sm.length, publicKey) >= 0;
};
function messageToNativeBuffer(options) {
var message = options.message;
if (message instanceof Uint8Array || message instanceof NativeBuffer) {
return message;
}
var encoding = options.encoding;
if (message === void 0) {
if (options.md) {
message = options.md.digest().getBytes();
encoding = "binary";
} else {
throw new TypeError('"options.message" or "options.md" not specified.');
}
}
if (typeof message === "string" && !encoding) {
throw new TypeError('"options.encoding" must be "binary" or "utf8".');
}
if (typeof message === "string") {
if (typeof Buffer !== "undefined") {
return Buffer.from(message, encoding);
}
message = new ByteBuffer(message, encoding);
} else if (!(message instanceof ByteBuffer)) {
throw new TypeError(
'"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.'
);
}
var buffer = new NativeBuffer(message.length());
for (var i5 = 0; i5 < buffer.length; ++i5) {
buffer[i5] = message.at(i5);
}
return buffer;
}
__name(messageToNativeBuffer, "messageToNativeBuffer");
var gf0 = gf();
var gf1 = gf([1]);
var D3 = gf([
30883,
4953,
19914,
30187,
55467,
16705,
2637,
112,
59544,
30585,
16505,
36039,
65139,
11119,
27886,
20995
]);
var D22 = gf([
61785,
9906,
39828,
60374,
45398,
33411,
5274,
224,
53552,
61171,
33010,
6542,
64743,
22239,
55772,
9222
]);
var X3 = gf([
54554,
36645,
11616,
51542,
42930,
38181,
51040,
26924,
56412,
64982,
57905,
49316,
21502,
52590,
14035,
8553
]);
var Y3 = gf([
26200,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214
]);
var L3 = new Float64Array([
237,
211,
245,
92,
26,
99,
18,
88,
214,
156,
247,
162,
222,
249,
222,
20,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
16
]);
var I4 = gf([
41136,
18958,
6951,
50414,
58488,
44335,
6150,
12099,
55207,
15867,
153,
11085,
57099,
20417,
9344,
11139
]);
function sha512(msg, msgLen) {
var md = forge.md.sha512.create();
var buffer = new ByteBuffer(msg);
md.update(buffer.getBytes(msgLen), "binary");
var hash = md.digest().getBytes();
if (typeof Buffer !== "undefined") {
return Buffer.from(hash, "binary");
}
var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);
for (var i5 = 0; i5 < 64; ++i5) {
out[i5] = hash.charCodeAt(i5);
}
return out;
}
__name(sha512, "sha512");
function crypto_sign_keypair(pk, sk) {
var p6 = [gf(), gf(), gf(), gf()];
var i5;
var d6 = sha512(sk, 32);
d6[0] &= 248;
d6[31] &= 127;
d6[31] |= 64;
scalarbase(p6, d6);
pack(pk, p6);
for (i5 = 0; i5 < 32; ++i5) {
sk[i5 + 32] = pk[i5];
}
return 0;
}
__name(crypto_sign_keypair, "crypto_sign_keypair");
function crypto_sign(sm, m6, n6, sk) {
var i5, j6, x6 = new Float64Array(64);
var p6 = [gf(), gf(), gf(), gf()];
var d6 = sha512(sk, 32);
d6[0] &= 248;
d6[31] &= 127;
d6[31] |= 64;
var smlen = n6 + 64;
for (i5 = 0; i5 < n6; ++i5) {
sm[64 + i5] = m6[i5];
}
for (i5 = 0; i5 < 32; ++i5) {
sm[32 + i5] = d6[32 + i5];
}
var r7 = sha512(sm.subarray(32), n6 + 32);
reduce(r7);
scalarbase(p6, r7);
pack(sm, p6);
for (i5 = 32; i5 < 64; ++i5) {
sm[i5] = sk[i5];
}
var h6 = sha512(sm, n6 + 64);
reduce(h6);
for (i5 = 32; i5 < 64; ++i5) {
x6[i5] = 0;
}
for (i5 = 0; i5 < 32; ++i5) {
x6[i5] = r7[i5];
}
for (i5 = 0; i5 < 32; ++i5) {
for (j6 = 0; j6 < 32; j6++) {
x6[i5 + j6] += h6[i5] * d6[j6];
}
}
modL(sm.subarray(32), x6);
return smlen;
}
__name(crypto_sign, "crypto_sign");
function crypto_sign_open(m6, sm, n6, pk) {
var i5, mlen;
var t7 = new NativeBuffer(32);
var p6 = [gf(), gf(), gf(), gf()], q6 = [gf(), gf(), gf(), gf()];
mlen = -1;
if (n6 < 64) {
return -1;
}
if (unpackneg(q6, pk)) {
return -1;
}
for (i5 = 0; i5 < n6; ++i5) {
m6[i5] = sm[i5];
}
for (i5 = 0; i5 < 32; ++i5) {
m6[i5 + 32] = pk[i5];
}
var h6 = sha512(m6, n6);
reduce(h6);
scalarmult(p6, q6, h6);
scalarbase(q6, sm.subarray(32));
add(p6, q6);
pack(t7, p6);
n6 -= 64;
if (crypto_verify_32(sm, 0, t7, 0)) {
for (i5 = 0; i5 < n6; ++i5) {
m6[i5] = 0;
}
return -1;
}
for (i5 = 0; i5 < n6; ++i5) {
m6[i5] = sm[i5 + 64];
}
mlen = n6;
return mlen;
}
__name(crypto_sign_open, "crypto_sign_open");
function modL(r7, x6) {
var carry, i5, j6, k6;
for (i5 = 63; i5 >= 32; --i5) {
carry = 0;
for (j6 = i5 - 32, k6 = i5 - 12; j6 < k6; ++j6) {
x6[j6] += carry - 16 * x6[i5] * L3[j6 - (i5 - 32)];
carry = x6[j6] + 128 >> 8;
x6[j6] -= carry * 256;
}
x6[j6] += carry;
x6[i5] = 0;
}
carry = 0;
for (j6 = 0; j6 < 32; ++j6) {
x6[j6] += carry - (x6[31] >> 4) * L3[j6];
carry = x6[j6] >> 8;
x6[j6] &= 255;
}
for (j6 = 0; j6 < 32; ++j6) {
x6[j6] -= carry * L3[j6];
}
for (i5 = 0; i5 < 32; ++i5) {
x6[i5 + 1] += x6[i5] >> 8;
r7[i5] = x6[i5] & 255;
}
}
__name(modL, "modL");
function reduce(r7) {
var x6 = new Float64Array(64);
for (var i5 = 0; i5 < 64; ++i5) {
x6[i5] = r7[i5];
r7[i5] = 0;
}
modL(r7, x6);
}
__name(reduce, "reduce");
function add(p6, q6) {
var a5 = gf(), b6 = gf(), c6 = gf(), d6 = gf(), e7 = gf(), f6 = gf(), g6 = gf(), h6 = gf(), t7 = gf();
Z3(a5, p6[1], p6[0]);
Z3(t7, q6[1], q6[0]);
M3(a5, a5, t7);
A3(b6, p6[0], p6[1]);
A3(t7, q6[0], q6[1]);
M3(b6, b6, t7);
M3(c6, p6[3], q6[3]);
M3(c6, c6, D22);
M3(d6, p6[2], q6[2]);
A3(d6, d6, d6);
Z3(e7, b6, a5);
Z3(f6, d6, c6);
A3(g6, d6, c6);
A3(h6, b6, a5);
M3(p6[0], e7, f6);
M3(p6[1], h6, g6);
M3(p6[2], g6, f6);
M3(p6[3], e7, h6);
}
__name(add, "add");
function cswap(p6, q6, b6) {
for (var i5 = 0; i5 < 4; ++i5) {
sel25519(p6[i5], q6[i5], b6);
}
}
__name(cswap, "cswap");
function pack(r7, p6) {
var tx = gf(), ty = gf(), zi = gf();
inv25519(zi, p6[2]);
M3(tx, p6[0], zi);
M3(ty, p6[1], zi);
pack25519(r7, ty);
r7[31] ^= par25519(tx) << 7;
}
__name(pack, "pack");
function pack25519(o5, n6) {
var i5, j6, b6;
var m6 = gf(), t7 = gf();
for (i5 = 0; i5 < 16; ++i5) {
t7[i5] = n6[i5];
}
car25519(t7);
car25519(t7);
car25519(t7);
for (j6 = 0; j6 < 2; ++j6) {
m6[0] = t7[0] - 65517;
for (i5 = 1; i5 < 15; ++i5) {
m6[i5] = t7[i5] - 65535 - (m6[i5 - 1] >> 16 & 1);
m6[i5 - 1] &= 65535;
}
m6[15] = t7[15] - 32767 - (m6[14] >> 16 & 1);
b6 = m6[15] >> 16 & 1;
m6[14] &= 65535;
sel25519(t7, m6, 1 - b6);
}
for (i5 = 0; i5 < 16; i5++) {
o5[2 * i5] = t7[i5] & 255;
o5[2 * i5 + 1] = t7[i5] >> 8;
}
}
__name(pack25519, "pack25519");
function unpackneg(r7, p6) {
var t7 = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
set25519(r7[2], gf1);
unpack25519(r7[1], p6);
S4(num, r7[1]);
M3(den, num, D3);
Z3(num, num, r7[2]);
A3(den, r7[2], den);
S4(den2, den);
S4(den4, den2);
M3(den6, den4, den2);
M3(t7, den6, num);
M3(t7, t7, den);
pow2523(t7, t7);
M3(t7, t7, num);
M3(t7, t7, den);
M3(t7, t7, den);
M3(r7[0], t7, den);
S4(chk, r7[0]);
M3(chk, chk, den);
if (neq25519(chk, num)) {
M3(r7[0], r7[0], I4);
}
S4(chk, r7[0]);
M3(chk, chk, den);
if (neq25519(chk, num)) {
return -1;
}
if (par25519(r7[0]) === p6[31] >> 7) {
Z3(r7[0], gf0, r7[0]);
}
M3(r7[3], r7[0], r7[1]);
return 0;
}
__name(unpackneg, "unpackneg");
function unpack25519(o5, n6) {
var i5;
for (i5 = 0; i5 < 16; ++i5) {
o5[i5] = n6[2 * i5] + (n6[2 * i5 + 1] << 8);
}
o5[15] &= 32767;
}
__name(unpack25519, "unpack25519");
function pow2523(o5, i5) {
var c6 = gf();
var a5;
for (a5 = 0; a5 < 16; ++a5) {
c6[a5] = i5[a5];
}
for (a5 = 250; a5 >= 0; --a5) {
S4(c6, c6);
if (a5 !== 1) {
M3(c6, c6, i5);
}
}
for (a5 = 0; a5 < 16; ++a5) {
o5[a5] = c6[a5];
}
}
__name(pow2523, "pow2523");
function neq25519(a5, b6) {
var c6 = new NativeBuffer(32);
var d6 = new NativeBuffer(32);
pack25519(c6, a5);
pack25519(d6, b6);
return crypto_verify_32(c6, 0, d6, 0);
}
__name(neq25519, "neq25519");
function crypto_verify_32(x6, xi, y4, yi) {
return vn(x6, xi, y4, yi, 32);
}
__name(crypto_verify_32, "crypto_verify_32");
function vn(x6, xi, y4, yi, n6) {
var i5, d6 = 0;
for (i5 = 0; i5 < n6; ++i5) {
d6 |= x6[xi + i5] ^ y4[yi + i5];
}
return (1 & d6 - 1 >>> 8) - 1;
}
__name(vn, "vn");
function par25519(a5) {
var d6 = new NativeBuffer(32);
pack25519(d6, a5);
return d6[0] & 1;
}
__name(par25519, "par25519");
function scalarmult(p6, q6, s5) {
var b6, i5;
set25519(p6[0], gf0);
set25519(p6[1], gf1);
set25519(p6[2], gf1);
set25519(p6[3], gf0);
for (i5 = 255; i5 >= 0; --i5) {
b6 = s5[i5 / 8 | 0] >> (i5 & 7) & 1;
cswap(p6, q6, b6);
add(q6, p6);
add(p6, p6);
cswap(p6, q6, b6);
}
}
__name(scalarmult, "scalarmult");
function scalarbase(p6, s5) {
var q6 = [gf(), gf(), gf(), gf()];
set25519(q6[0], X3);
set25519(q6[1], Y3);
set25519(q6[2], gf1);
M3(q6[3], X3, Y3);
scalarmult(p6, q6, s5);
}
__name(scalarbase, "scalarbase");
function set25519(r7, a5) {
var i5;
for (i5 = 0; i5 < 16; i5++) {
r7[i5] = a5[i5] | 0;
}
}
__name(set25519, "set25519");
function inv25519(o5, i5) {
var c6 = gf();
var a5;
for (a5 = 0; a5 < 16; ++a5) {
c6[a5] = i5[a5];
}
for (a5 = 253; a5 >= 0; --a5) {
S4(c6, c6);
if (a5 !== 2 && a5 !== 4) {
M3(c6, c6, i5);
}
}
for (a5 = 0; a5 < 16; ++a5) {
o5[a5] = c6[a5];
}
}
__name(inv25519, "inv25519");
function car25519(o5) {
var i5, v7, c6 = 1;
for (i5 = 0; i5 < 16; ++i5) {
v7 = o5[i5] + c6 + 65535;
c6 = Math.floor(v7 / 65536);
o5[i5] = v7 - c6 * 65536;
}
o5[0] += c6 - 1 + 37 * (c6 - 1);
}
__name(car25519, "car25519");
function sel25519(p6, q6, b6) {
var t7, c6 = ~(b6 - 1);
for (var i5 = 0; i5 < 16; ++i5) {
t7 = c6 & (p6[i5] ^ q6[i5]);
p6[i5] ^= t7;
q6[i5] ^= t7;
}
}
__name(sel25519, "sel25519");
function gf(init3) {
var i5, r7 = new Float64Array(16);
if (init3) {
for (i5 = 0; i5 < init3.length; ++i5) {
r7[i5] = init3[i5];
}
}
return r7;
}
__name(gf, "gf");
function A3(o5, a5, b6) {
for (var i5 = 0; i5 < 16; ++i5) {
o5[i5] = a5[i5] + b6[i5];
}
}
__name(A3, "A");
function Z3(o5, a5, b6) {
for (var i5 = 0; i5 < 16; ++i5) {
o5[i5] = a5[i5] - b6[i5];
}
}
__name(Z3, "Z");
function S4(o5, a5) {
M3(o5, a5, a5);
}
__name(S4, "S");
function M3(o5, a5, b6) {
var v7, c6, t0 = 0, t1 = 0, t22 = 0, t32 = 0, t42 = 0, t52 = 0, t62 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t222 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b6[0], b1 = b6[1], b22 = b6[2], b32 = b6[3], b42 = b6[4], b52 = b6[5], b62 = b6[6], b7 = b6[7], b8 = b6[8], b9 = b6[9], b10 = b6[10], b11 = b6[11], b12 = b6[12], b13 = b6[13], b14 = b6[14], b15 = b6[15];
v7 = a5[0];
t0 += v7 * b0;
t1 += v7 * b1;
t22 += v7 * b22;
t32 += v7 * b32;
t42 += v7 * b42;
t52 += v7 * b52;
t62 += v7 * b62;
t7 += v7 * b7;
t8 += v7 * b8;
t9 += v7 * b9;
t10 += v7 * b10;
t11 += v7 * b11;
t12 += v7 * b12;
t13 += v7 * b13;
t14 += v7 * b14;
t15 += v7 * b15;
v7 = a5[1];
t1 += v7 * b0;
t22 += v7 * b1;
t32 += v7 * b22;
t42 += v7 * b32;
t52 += v7 * b42;
t62 += v7 * b52;
t7 += v7 * b62;
t8 += v7 * b7;
t9 += v7 * b8;
t10 += v7 * b9;
t11 += v7 * b10;
t12 += v7 * b11;
t13 += v7 * b12;
t14 += v7 * b13;
t15 += v7 * b14;
t16 += v7 * b15;
v7 = a5[2];
t22 += v7 * b0;
t32 += v7 * b1;
t42 += v7 * b22;
t52 += v7 * b32;
t62 += v7 * b42;
t7 += v7 * b52;
t8 += v7 * b62;
t9 += v7 * b7;
t10 += v7 * b8;
t11 += v7 * b9;
t12 += v7 * b10;
t13 += v7 * b11;
t14 += v7 * b12;
t15 += v7 * b13;
t16 += v7 * b14;
t17 += v7 * b15;
v7 = a5[3];
t32 += v7 * b0;
t42 += v7 * b1;
t52 += v7 * b22;
t62 += v7 * b32;
t7 += v7 * b42;
t8 += v7 * b52;
t9 += v7 * b62;
t10 += v7 * b7;
t11 += v7 * b8;
t12 += v7 * b9;
t13 += v7 * b10;
t14 += v7 * b11;
t15 += v7 * b12;
t16 += v7 * b13;
t17 += v7 * b14;
t18 += v7 * b15;
v7 = a5[4];
t42 += v7 * b0;
t52 += v7 * b1;
t62 += v7 * b22;
t7 += v7 * b32;
t8 += v7 * b42;
t9 += v7 * b52;
t10 += v7 * b62;
t11 += v7 * b7;
t12 += v7 * b8;
t13 += v7 * b9;
t14 += v7 * b10;
t15 += v7 * b11;
t16 += v7 * b12;
t17 += v7 * b13;
t18 += v7 * b14;
t19 += v7 * b15;
v7 = a5[5];
t52 += v7 * b0;
t62 += v7 * b1;
t7 += v7 * b22;
t8 += v7 * b32;
t9 += v7 * b42;
t10 += v7 * b52;
t11 += v7 * b62;
t12 += v7 * b7;
t13 += v7 * b8;
t14 += v7 * b9;
t15 += v7 * b10;
t16 += v7 * b11;
t17 += v7 * b12;
t18 += v7 * b13;
t19 += v7 * b14;
t20 += v7 * b15;
v7 = a5[6];
t62 += v7 * b0;
t7 += v7 * b1;
t8 += v7 * b22;
t9 += v7 * b32;
t10 += v7 * b42;
t11 += v7 * b52;
t12 += v7 * b62;
t13 += v7 * b7;
t14 += v7 * b8;
t15 += v7 * b9;
t16 += v7 * b10;
t17 += v7 * b11;
t18 += v7 * b12;
t19 += v7 * b13;
t20 += v7 * b14;
t21 += v7 * b15;
v7 = a5[7];
t7 += v7 * b0;
t8 += v7 * b1;
t9 += v7 * b22;
t10 += v7 * b32;
t11 += v7 * b42;
t12 += v7 * b52;
t13 += v7 * b62;
t14 += v7 * b7;
t15 += v7 * b8;
t16 += v7 * b9;
t17 += v7 * b10;
t18 += v7 * b11;
t19 += v7 * b12;
t20 += v7 * b13;
t21 += v7 * b14;
t222 += v7 * b15;
v7 = a5[8];
t8 += v7 * b0;
t9 += v7 * b1;
t10 += v7 * b22;
t11 += v7 * b32;
t12 += v7 * b42;
t13 += v7 * b52;
t14 += v7 * b62;
t15 += v7 * b7;
t16 += v7 * b8;
t17 += v7 * b9;
t18 += v7 * b10;
t19 += v7 * b11;
t20 += v7 * b12;
t21 += v7 * b13;
t222 += v7 * b14;
t23 += v7 * b15;
v7 = a5[9];
t9 += v7 * b0;
t10 += v7 * b1;
t11 += v7 * b22;
t12 += v7 * b32;
t13 += v7 * b42;
t14 += v7 * b52;
t15 += v7 * b62;
t16 += v7 * b7;
t17 += v7 * b8;
t18 += v7 * b9;
t19 += v7 * b10;
t20 += v7 * b11;
t21 += v7 * b12;
t222 += v7 * b13;
t23 += v7 * b14;
t24 += v7 * b15;
v7 = a5[10];
t10 += v7 * b0;
t11 += v7 * b1;
t12 += v7 * b22;
t13 += v7 * b32;
t14 += v7 * b42;
t15 += v7 * b52;
t16 += v7 * b62;
t17 += v7 * b7;
t18 += v7 * b8;
t19 += v7 * b9;
t20 += v7 * b10;
t21 += v7 * b11;
t222 += v7 * b12;
t23 += v7 * b13;
t24 += v7 * b14;
t25 += v7 * b15;
v7 = a5[11];
t11 += v7 * b0;
t12 += v7 * b1;
t13 += v7 * b22;
t14 += v7 * b32;
t15 += v7 * b42;
t16 += v7 * b52;
t17 += v7 * b62;
t18 += v7 * b7;
t19 += v7 * b8;
t20 += v7 * b9;
t21 += v7 * b10;
t222 += v7 * b11;
t23 += v7 * b12;
t24 += v7 * b13;
t25 += v7 * b14;
t26 += v7 * b15;
v7 = a5[12];
t12 += v7 * b0;
t13 += v7 * b1;
t14 += v7 * b22;
t15 += v7 * b32;
t16 += v7 * b42;
t17 += v7 * b52;
t18 += v7 * b62;
t19 += v7 * b7;
t20 += v7 * b8;
t21 += v7 * b9;
t222 += v7 * b10;
t23 += v7 * b11;
t24 += v7 * b12;
t25 += v7 * b13;
t26 += v7 * b14;
t27 += v7 * b15;
v7 = a5[13];
t13 += v7 * b0;
t14 += v7 * b1;
t15 += v7 * b22;
t16 += v7 * b32;
t17 += v7 * b42;
t18 += v7 * b52;
t19 += v7 * b62;
t20 += v7 * b7;
t21 += v7 * b8;
t222 += v7 * b9;
t23 += v7 * b10;
t24 += v7 * b11;
t25 += v7 * b12;
t26 += v7 * b13;
t27 += v7 * b14;
t28 += v7 * b15;
v7 = a5[14];
t14 += v7 * b0;
t15 += v7 * b1;
t16 += v7 * b22;
t17 += v7 * b32;
t18 += v7 * b42;
t19 += v7 * b52;
t20 += v7 * b62;
t21 += v7 * b7;
t222 += v7 * b8;
t23 += v7 * b9;
t24 += v7 * b10;
t25 += v7 * b11;
t26 += v7 * b12;
t27 += v7 * b13;
t28 += v7 * b14;
t29 += v7 * b15;
v7 = a5[15];
t15 += v7 * b0;
t16 += v7 * b1;
t17 += v7 * b22;
t18 += v7 * b32;
t19 += v7 * b42;
t20 += v7 * b52;
t21 += v7 * b62;
t222 += v7 * b7;
t23 += v7 * b8;
t24 += v7 * b9;
t25 += v7 * b10;
t26 += v7 * b11;
t27 += v7 * b12;
t28 += v7 * b13;
t29 += v7 * b14;
t30 += v7 * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t22 += 38 * t18;
t32 += 38 * t19;
t42 += 38 * t20;
t52 += 38 * t21;
t62 += 38 * t222;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
c6 = 1;
v7 = t0 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t0 = v7 - c6 * 65536;
v7 = t1 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t1 = v7 - c6 * 65536;
v7 = t22 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t22 = v7 - c6 * 65536;
v7 = t32 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t32 = v7 - c6 * 65536;
v7 = t42 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t42 = v7 - c6 * 65536;
v7 = t52 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t52 = v7 - c6 * 65536;
v7 = t62 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t62 = v7 - c6 * 65536;
v7 = t7 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t7 = v7 - c6 * 65536;
v7 = t8 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t8 = v7 - c6 * 65536;
v7 = t9 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t9 = v7 - c6 * 65536;
v7 = t10 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t10 = v7 - c6 * 65536;
v7 = t11 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t11 = v7 - c6 * 65536;
v7 = t12 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t12 = v7 - c6 * 65536;
v7 = t13 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t13 = v7 - c6 * 65536;
v7 = t14 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t14 = v7 - c6 * 65536;
v7 = t15 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t15 = v7 - c6 * 65536;
t0 += c6 - 1 + 37 * (c6 - 1);
c6 = 1;
v7 = t0 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t0 = v7 - c6 * 65536;
v7 = t1 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t1 = v7 - c6 * 65536;
v7 = t22 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t22 = v7 - c6 * 65536;
v7 = t32 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t32 = v7 - c6 * 65536;
v7 = t42 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t42 = v7 - c6 * 65536;
v7 = t52 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t52 = v7 - c6 * 65536;
v7 = t62 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t62 = v7 - c6 * 65536;
v7 = t7 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t7 = v7 - c6 * 65536;
v7 = t8 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t8 = v7 - c6 * 65536;
v7 = t9 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t9 = v7 - c6 * 65536;
v7 = t10 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t10 = v7 - c6 * 65536;
v7 = t11 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t11 = v7 - c6 * 65536;
v7 = t12 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t12 = v7 - c6 * 65536;
v7 = t13 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t13 = v7 - c6 * 65536;
v7 = t14 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t14 = v7 - c6 * 65536;
v7 = t15 + c6 + 65535;
c6 = Math.floor(v7 / 65536);
t15 = v7 - c6 * 65536;
t0 += c6 - 1 + 37 * (c6 - 1);
o5[0] = t0;
o5[1] = t1;
o5[2] = t22;
o5[3] = t32;
o5[4] = t42;
o5[5] = t52;
o5[6] = t62;
o5[7] = t7;
o5[8] = t8;
o5[9] = t9;
o5[10] = t10;
o5[11] = t11;
o5[12] = t12;
o5[13] = t13;
o5[14] = t14;
o5[15] = t15;
}
__name(M3, "M");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/kem.js
var require_kem = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/kem.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
require_random2();
require_jsbn();
module3.exports = forge.kem = forge.kem || {};
var BigInteger = forge.jsbn.BigInteger;
forge.kem.rsa = {};
forge.kem.rsa.create = function(kdf, options) {
options = options || {};
var prng = options.prng || forge.random;
var kem = {};
kem.encrypt = function(publicKey, keyLength) {
var byteLength = Math.ceil(publicKey.n.bitLength() / 8);
var r7;
do {
r7 = new BigInteger(
forge.util.bytesToHex(prng.getBytesSync(byteLength)),
16
).mod(publicKey.n);
} while (r7.compareTo(BigInteger.ONE) <= 0);
r7 = forge.util.hexToBytes(r7.toString(16));
var zeros = byteLength - r7.length;
if (zeros > 0) {
r7 = forge.util.fillString(String.fromCharCode(0), zeros) + r7;
}
var encapsulation = publicKey.encrypt(r7, "NONE");
var key = kdf.generate(r7, keyLength);
return { encapsulation, key };
};
kem.decrypt = function(privateKey, encapsulation, keyLength) {
var r7 = privateKey.decrypt(encapsulation, "NONE");
return kdf.generate(r7, keyLength);
};
return kem;
};
forge.kem.kdf1 = function(md, digestLength) {
_createKDF(this, md, 0, digestLength || md.digestLength);
};
forge.kem.kdf2 = function(md, digestLength) {
_createKDF(this, md, 1, digestLength || md.digestLength);
};
function _createKDF(kdf, md, counterStart, digestLength) {
kdf.generate = function(x6, length) {
var key = new forge.util.ByteBuffer();
var k6 = Math.ceil(length / digestLength) + counterStart;
var c6 = new forge.util.ByteBuffer();
for (var i5 = counterStart; i5 < k6; ++i5) {
c6.putInt32(i5);
md.start();
md.update(x6 + c6.getBytes());
var hash = md.digest();
key.putBytes(hash.getBytes(digestLength));
}
key.truncate(key.length() - length);
return key.getBytes();
};
}
__name(_createKDF, "_createKDF");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/log.js
var require_log = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/log.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_util10();
module3.exports = forge.log = forge.log || {};
forge.log.levels = [
"none",
"error",
"warning",
"info",
"debug",
"verbose",
"max"
];
var sLevelInfo = {};
var sLoggers = [];
var sConsoleLogger = null;
forge.log.LEVEL_LOCKED = 1 << 1;
forge.log.NO_LEVEL_CHECK = 1 << 2;
forge.log.INTERPOLATE = 1 << 3;
for (i5 = 0; i5 < forge.log.levels.length; ++i5) {
level = forge.log.levels[i5];
sLevelInfo[level] = {
index: i5,
name: level.toUpperCase()
};
}
var level;
var i5;
forge.log.logMessage = function(message) {
var messageLevelIndex = sLevelInfo[message.level].index;
for (var i6 = 0; i6 < sLoggers.length; ++i6) {
var logger5 = sLoggers[i6];
if (logger5.flags & forge.log.NO_LEVEL_CHECK) {
logger5.f(message);
} else {
var loggerLevelIndex = sLevelInfo[logger5.level].index;
if (messageLevelIndex <= loggerLevelIndex) {
logger5.f(logger5, message);
}
}
}
};
forge.log.prepareStandard = function(message) {
if (!("standard" in message)) {
message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp +
" [" + message.category + "] " + message.message;
}
};
forge.log.prepareFull = function(message) {
if (!("full" in message)) {
var args = [message.message];
args = args.concat([]);
message.full = forge.util.format.apply(this, args);
}
};
forge.log.prepareStandardFull = function(message) {
if (!("standardFull" in message)) {
forge.log.prepareStandard(message);
message.standardFull = message.standard;
}
};
if (true) {
levels = ["error", "warning", "info", "debug", "verbose"];
for (i5 = 0; i5 < levels.length; ++i5) {
(function(level2) {
forge.log[level2] = function(category, message) {
var args = Array.prototype.slice.call(arguments).slice(2);
var msg = {
timestamp: /* @__PURE__ */ new Date(),
level: level2,
category,
message,
"arguments": args
/*standard*/
/*full*/
/*fullMessage*/
};
forge.log.logMessage(msg);
};
})(levels[i5]);
}
}
var levels;
var i5;
forge.log.makeLogger = function(logFunction) {
var logger5 = {
flags: 0,
f: logFunction
};
forge.log.setLevel(logger5, "none");
return logger5;
};
forge.log.setLevel = function(logger5, level2) {
var rval = false;
if (logger5 && !(logger5.flags & forge.log.LEVEL_LOCKED)) {
for (var i6 = 0; i6 < forge.log.levels.length; ++i6) {
var aValidLevel = forge.log.levels[i6];
if (level2 == aValidLevel) {
logger5.level = level2;
rval = true;
break;
}
}
}
return rval;
};
forge.log.lock = function(logger5, lock2) {
if (typeof lock2 === "undefined" || lock2) {
logger5.flags |= forge.log.LEVEL_LOCKED;
} else {
logger5.flags &= ~forge.log.LEVEL_LOCKED;
}
};
forge.log.addLogger = function(logger5) {
sLoggers.push(logger5);
};
if (typeof console !== "undefined" && "log" in console) {
if (console.error && console.warn && console.info && console.debug) {
levelHandlers = {
error: console.error,
warning: console.warn,
info: console.info,
debug: console.debug,
verbose: console.debug
};
f6 = /* @__PURE__ */ __name(function(logger5, message) {
forge.log.prepareStandard(message);
var handler = levelHandlers[message.level];
var args = [message.standard];
args = args.concat(message["arguments"].slice());
handler.apply(console, args);
}, "f");
logger4 = forge.log.makeLogger(f6);
} else {
f6 = /* @__PURE__ */ __name(function(logger5, message) {
forge.log.prepareStandardFull(message);
console.log(message.standardFull);
}, "f");
logger4 = forge.log.makeLogger(f6);
}
forge.log.setLevel(logger4, "debug");
forge.log.addLogger(logger4);
sConsoleLogger = logger4;
} else {
console = {
log: /* @__PURE__ */ __name(function() {
}, "log")
};
}
var logger4;
var levelHandlers;
var f6;
if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) {
query = new URL(window.location.href).searchParams;
if (query.has("console.level")) {
forge.log.setLevel(
sConsoleLogger,
query.get("console.level").slice(-1)[0]
);
}
if (query.has("console.lock")) {
lock = query.get("console.lock").slice(-1)[0];
if (lock == "true") {
forge.log.lock(sConsoleLogger);
}
}
}
var query;
var lock;
forge.log.consoleLogger = sConsoleLogger;
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md.all.js
var require_md_all = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md.all.js"(exports2, module3) {
init_import_meta_url();
module3.exports = require_md();
require_md5();
require_sha1();
require_sha256();
require_sha512();
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs7.js
var require_pkcs7 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs7.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_aes();
require_asn1();
require_des();
require_oids();
require_pem();
require_pkcs7asn1();
require_random2();
require_util10();
require_x509();
var asn1 = forge.asn1;
var p7 = module3.exports = forge.pkcs7 = forge.pkcs7 || {};
p7.messageFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if (msg.type !== "PKCS7") {
var error2 = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');
error2.headerType = msg.type;
throw error2;
}
if (msg.procType && msg.procType.type === "ENCRYPTED") {
throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");
}
var obj = asn1.fromDer(msg.body);
return p7.messageFromAsn1(obj);
};
p7.messageToPem = function(msg, maxline) {
var pemObj = {
type: "PKCS7",
body: asn1.toDer(msg.toAsn1()).getBytes()
};
return forge.pem.encode(pemObj, { maxline });
};
p7.messageFromAsn1 = function(obj) {
var capture = {};
var errors = [];
if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");
error2.errors = errors;
throw error2;
}
var contentType = asn1.derToOid(capture.contentType);
var msg;
switch (contentType) {
case forge.pki.oids.envelopedData:
msg = p7.createEnvelopedData();
break;
case forge.pki.oids.encryptedData:
msg = p7.createEncryptedData();
break;
case forge.pki.oids.signedData:
msg = p7.createSignedData();
break;
default:
throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported.");
}
msg.fromAsn1(capture.content.value[0]);
return msg;
};
p7.createSignedData = function() {
var msg = null;
msg = {
type: forge.pki.oids.signedData,
version: 1,
certificates: [],
crls: [],
// TODO: add json-formatted signer stuff here?
signers: [],
// populated during sign()
digestAlgorithmIdentifiers: [],
contentInfo: null,
signerInfos: [],
fromAsn1: /* @__PURE__ */ __name(function(obj) {
_fromAsn1(msg, obj, p7.asn1.signedDataValidator);
msg.certificates = [];
msg.crls = [];
msg.digestAlgorithmIdentifiers = [];
msg.contentInfo = null;
msg.signerInfos = [];
if (msg.rawCapture.certificates) {
var certs = msg.rawCapture.certificates.value;
for (var i5 = 0; i5 < certs.length; ++i5) {
msg.certificates.push(forge.pki.certificateFromAsn1(certs[i5]));
}
}
}, "fromAsn1"),
toAsn1: /* @__PURE__ */ __name(function() {
if (!msg.contentInfo) {
msg.sign();
}
var certs = [];
for (var i5 = 0; i5 < msg.certificates.length; ++i5) {
certs.push(forge.pki.certificateToAsn1(msg.certificates[i5]));
}
var crls = [];
var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Version
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(msg.version).getBytes()
),
// DigestAlgorithmIdentifiers
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SET,
true,
msg.digestAlgorithmIdentifiers
),
// ContentInfo
msg.contentInfo
])
]);
if (certs.length > 0) {
signedData.value[0].value.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)
);
}
if (crls.length > 0) {
signedData.value[0].value.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)
);
}
signedData.value[0].value.push(
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SET,
true,
msg.signerInfos
)
);
return asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[
// ContentType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(msg.type).getBytes()
),
// [0] SignedData
signedData
]
);
}, "toAsn1"),
/**
* Add (another) entity to list of signers.
*
* Note: If authenticatedAttributes are provided, then, per RFC 2315,
* they must include at least two attributes: content type and
* message digest. The message digest attribute value will be
* auto-calculated during signing and will be ignored if provided.
*
* Here's an example of providing these two attributes:
*
* forge.pkcs7.createSignedData();
* p7.addSigner({
* issuer: cert.issuer.attributes,
* serialNumber: cert.serialNumber,
* key: privateKey,
* digestAlgorithm: forge.pki.oids.sha1,
* authenticatedAttributes: [{
* type: forge.pki.oids.contentType,
* value: forge.pki.oids.data
* }, {
* type: forge.pki.oids.messageDigest
* }]
* });
*
* TODO: Support [subjectKeyIdentifier] as signer's ID.
*
* @param signer the signer information:
* key the signer's private key.
* [certificate] a certificate containing the public key
* associated with the signer's private key; use this option as
* an alternative to specifying signer.issuer and
* signer.serialNumber.
* [issuer] the issuer attributes (eg: cert.issuer.attributes).
* [serialNumber] the signer's certificate's serial number in
* hexadecimal (eg: cert.serialNumber).
* [digestAlgorithm] the message digest OID, as a string, to use
* (eg: forge.pki.oids.sha1).
* [authenticatedAttributes] an optional array of attributes
* to also sign along with the content.
*/
addSigner: /* @__PURE__ */ __name(function(signer) {
var issuer = signer.issuer;
var serialNumber = signer.serialNumber;
if (signer.certificate) {
var cert = signer.certificate;
if (typeof cert === "string") {
cert = forge.pki.certificateFromPem(cert);
}
issuer = cert.issuer.attributes;
serialNumber = cert.serialNumber;
}
var key = signer.key;
if (!key) {
throw new Error(
"Could not add PKCS#7 signer; no private key specified."
);
}
if (typeof key === "string") {
key = forge.pki.privateKeyFromPem(key);
}
var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;
switch (digestAlgorithm) {
case forge.pki.oids.sha1:
case forge.pki.oids.sha256:
case forge.pki.oids.sha384:
case forge.pki.oids.sha512:
case forge.pki.oids.md5:
break;
default:
throw new Error(
"Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm
);
}
var authenticatedAttributes = signer.authenticatedAttributes || [];
if (authenticatedAttributes.length > 0) {
var contentType = false;
var messageDigest = false;
for (var i5 = 0; i5 < authenticatedAttributes.length; ++i5) {
var attr = authenticatedAttributes[i5];
if (!contentType && attr.type === forge.pki.oids.contentType) {
contentType = true;
if (messageDigest) {
break;
}
continue;
}
if (!messageDigest && attr.type === forge.pki.oids.messageDigest) {
messageDigest = true;
if (contentType) {
break;
}
continue;
}
}
if (!contentType || !messageDigest) {
throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.");
}
}
msg.signers.push({
key,
version: 1,
issuer,
serialNumber,
digestAlgorithm,
signatureAlgorithm: forge.pki.oids.rsaEncryption,
signature: null,
authenticatedAttributes,
unauthenticatedAttributes: []
});
}, "addSigner"),
/**
* Signs the content.
* @param options Options to apply when signing:
* [detached] boolean. If signing should be done in detached mode. Defaults to false.
*/
sign: /* @__PURE__ */ __name(function(options) {
options = options || {};
if (typeof msg.content !== "object" || msg.contentInfo === null) {
msg.contentInfo = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
[
// ContentType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(forge.pki.oids.data).getBytes()
)
]
);
if ("content" in msg) {
var content;
if (msg.content instanceof forge.util.ByteBuffer) {
content = msg.content.bytes();
} else if (typeof msg.content === "string") {
content = forge.util.encodeUtf8(msg.content);
}
if (options.detached) {
msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);
} else {
msg.contentInfo.value.push(
// [0] EXPLICIT content
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
content
)
])
);
}
}
}
if (msg.signers.length === 0) {
return;
}
var mds = addDigestAlgorithmIds();
addSignerInfos(mds);
}, "sign"),
verify: /* @__PURE__ */ __name(function() {
throw new Error("PKCS#7 signature verification not yet implemented.");
}, "verify"),
/**
* Add a certificate.
*
* @param cert the certificate to add.
*/
addCertificate: /* @__PURE__ */ __name(function(cert) {
if (typeof cert === "string") {
cert = forge.pki.certificateFromPem(cert);
}
msg.certificates.push(cert);
}, "addCertificate"),
/**
* Add a certificate revokation list.
*
* @param crl the certificate revokation list to add.
*/
addCertificateRevokationList: /* @__PURE__ */ __name(function(crl) {
throw new Error("PKCS#7 CRL support not yet implemented.");
}, "addCertificateRevokationList")
};
return msg;
function addDigestAlgorithmIds() {
var mds = {};
for (var i5 = 0; i5 < msg.signers.length; ++i5) {
var signer = msg.signers[i5];
var oid = signer.digestAlgorithm;
if (!(oid in mds)) {
mds[oid] = forge.md[forge.pki.oids[oid]].create();
}
if (signer.authenticatedAttributes.length === 0) {
signer.md = mds[oid];
} else {
signer.md = forge.md[forge.pki.oids[oid]].create();
}
}
msg.digestAlgorithmIdentifiers = [];
for (var oid in mds) {
msg.digestAlgorithmIdentifiers.push(
// AlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(oid).getBytes()
),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
])
);
}
return mds;
}
__name(addDigestAlgorithmIds, "addDigestAlgorithmIds");
function addSignerInfos(mds) {
var content;
if (msg.detachedContent) {
content = msg.detachedContent;
} else {
content = msg.contentInfo.value[1];
content = content.value[0];
}
if (!content) {
throw new Error(
"Could not sign PKCS#7 message; there is no content to sign."
);
}
var contentType = asn1.derToOid(msg.contentInfo.value[0].value);
var bytes = asn1.toDer(content);
bytes.getByte();
asn1.getBerValueLength(bytes);
bytes = bytes.getBytes();
for (var oid in mds) {
mds[oid].start().update(bytes);
}
var signingTime = /* @__PURE__ */ new Date();
for (var i5 = 0; i5 < msg.signers.length; ++i5) {
var signer = msg.signers[i5];
if (signer.authenticatedAttributes.length === 0) {
if (contentType !== forge.pki.oids.data) {
throw new Error(
"Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data."
);
}
} else {
signer.authenticatedAttributesAsn1 = asn1.create(
asn1.Class.CONTEXT_SPECIFIC,
0,
true,
[]
);
var attrsAsn1 = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SET,
true,
[]
);
for (var ai2 = 0; ai2 < signer.authenticatedAttributes.length; ++ai2) {
var attr = signer.authenticatedAttributes[ai2];
if (attr.type === forge.pki.oids.messageDigest) {
attr.value = mds[signer.digestAlgorithm].digest();
} else if (attr.type === forge.pki.oids.signingTime) {
if (!attr.value) {
attr.value = signingTime;
}
}
attrsAsn1.value.push(_attributeToAsn1(attr));
signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));
}
bytes = asn1.toDer(attrsAsn1).getBytes();
signer.md.start().update(bytes);
}
signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5");
}
msg.signerInfos = _signersToAsn1(msg.signers);
}
__name(addSignerInfos, "addSignerInfos");
};
p7.createEncryptedData = function() {
var msg = null;
msg = {
type: forge.pki.oids.encryptedData,
version: 0,
encryptedContent: {
algorithm: forge.pki.oids["aes256-CBC"]
},
/**
* Reads an EncryptedData content block (in ASN.1 format)
*
* @param obj The ASN.1 representation of the EncryptedData content block
*/
fromAsn1: /* @__PURE__ */ __name(function(obj) {
_fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);
}, "fromAsn1"),
/**
* Decrypt encrypted content
*
* @param key The (symmetric) key as a byte buffer
*/
decrypt: /* @__PURE__ */ __name(function(key) {
if (key !== void 0) {
msg.encryptedContent.key = key;
}
_decryptContent(msg);
}, "decrypt")
};
return msg;
};
p7.createEnvelopedData = function() {
var msg = null;
msg = {
type: forge.pki.oids.envelopedData,
version: 0,
recipients: [],
encryptedContent: {
algorithm: forge.pki.oids["aes256-CBC"]
},
/**
* Reads an EnvelopedData content block (in ASN.1 format)
*
* @param obj the ASN.1 representation of the EnvelopedData content block.
*/
fromAsn1: /* @__PURE__ */ __name(function(obj) {
var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);
msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
}, "fromAsn1"),
toAsn1: /* @__PURE__ */ __name(function() {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// ContentType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(msg.type).getBytes()
),
// [0] EnvelopedData
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Version
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(msg.version).getBytes()
),
// RecipientInfos
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SET,
true,
_recipientsToAsn1(msg.recipients)
),
// EncryptedContentInfo
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.SEQUENCE,
true,
_encryptedContentToAsn1(msg.encryptedContent)
)
])
])
]);
}, "toAsn1"),
/**
* Find recipient by X.509 certificate's issuer.
*
* @param cert the certificate with the issuer to look for.
*
* @return the recipient object.
*/
findRecipient: /* @__PURE__ */ __name(function(cert) {
var sAttr = cert.issuer.attributes;
for (var i5 = 0; i5 < msg.recipients.length; ++i5) {
var r7 = msg.recipients[i5];
var rAttr = r7.issuer;
if (r7.serialNumber !== cert.serialNumber) {
continue;
}
if (rAttr.length !== sAttr.length) {
continue;
}
var match2 = true;
for (var j6 = 0; j6 < sAttr.length; ++j6) {
if (rAttr[j6].type !== sAttr[j6].type || rAttr[j6].value !== sAttr[j6].value) {
match2 = false;
break;
}
}
if (match2) {
return r7;
}
}
return null;
}, "findRecipient"),
/**
* Decrypt enveloped content
*
* @param recipient The recipient object related to the private key
* @param privKey The (RSA) private key object
*/
decrypt: /* @__PURE__ */ __name(function(recipient, privKey) {
if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) {
switch (recipient.encryptedContent.algorithm) {
case forge.pki.oids.rsaEncryption:
case forge.pki.oids.desCBC:
var key = privKey.decrypt(recipient.encryptedContent.content);
msg.encryptedContent.key = forge.util.createBuffer(key);
break;
default:
throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm);
}
}
_decryptContent(msg);
}, "decrypt"),
/**
* Add (another) entity to list of recipients.
*
* @param cert The certificate of the entity to add.
*/
addRecipient: /* @__PURE__ */ __name(function(cert) {
msg.recipients.push({
version: 0,
issuer: cert.issuer.attributes,
serialNumber: cert.serialNumber,
encryptedContent: {
// We simply assume rsaEncryption here, since forge.pki only
// supports RSA so far. If the PKI module supports other
// ciphers one day, we need to modify this one as well.
algorithm: forge.pki.oids.rsaEncryption,
key: cert.publicKey
}
});
}, "addRecipient"),
/**
* Encrypt enveloped content.
*
* This function supports two optional arguments, cipher and key, which
* can be used to influence symmetric encryption. Unless cipher is
* provided, the cipher specified in encryptedContent.algorithm is used
* (defaults to AES-256-CBC). If no key is provided, encryptedContent.key
* is (re-)used. If that one's not set, a random key will be generated
* automatically.
*
* @param [key] The key to be used for symmetric encryption.
* @param [cipher] The OID of the symmetric cipher to use.
*/
encrypt: /* @__PURE__ */ __name(function(key, cipher) {
if (msg.encryptedContent.content === void 0) {
cipher = cipher || msg.encryptedContent.algorithm;
key = key || msg.encryptedContent.key;
var keyLen, ivLen, ciphFn;
switch (cipher) {
case forge.pki.oids["aes128-CBC"]:
keyLen = 16;
ivLen = 16;
ciphFn = forge.aes.createEncryptionCipher;
break;
case forge.pki.oids["aes192-CBC"]:
keyLen = 24;
ivLen = 16;
ciphFn = forge.aes.createEncryptionCipher;
break;
case forge.pki.oids["aes256-CBC"]:
keyLen = 32;
ivLen = 16;
ciphFn = forge.aes.createEncryptionCipher;
break;
case forge.pki.oids["des-EDE3-CBC"]:
keyLen = 24;
ivLen = 8;
ciphFn = forge.des.createEncryptionCipher;
break;
default:
throw new Error("Unsupported symmetric cipher, OID " + cipher);
}
if (key === void 0) {
key = forge.util.createBuffer(forge.random.getBytes(keyLen));
} else if (key.length() != keyLen) {
throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + ".");
}
msg.encryptedContent.algorithm = cipher;
msg.encryptedContent.key = key;
msg.encryptedContent.parameter = forge.util.createBuffer(
forge.random.getBytes(ivLen)
);
var ciph = ciphFn(key);
ciph.start(msg.encryptedContent.parameter.copy());
ciph.update(msg.content);
if (!ciph.finish()) {
throw new Error("Symmetric encryption failed.");
}
msg.encryptedContent.content = ciph.output;
}
for (var i5 = 0; i5 < msg.recipients.length; ++i5) {
var recipient = msg.recipients[i5];
if (recipient.encryptedContent.content !== void 0) {
continue;
}
switch (recipient.encryptedContent.algorithm) {
case forge.pki.oids.rsaEncryption:
recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt(
msg.encryptedContent.key.data
);
break;
default:
throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm);
}
}
}, "encrypt")
};
return msg;
};
function _recipientFromAsn1(obj) {
var capture = {};
var errors = [];
if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");
error2.errors = errors;
throw error2;
}
return {
version: capture.version.charCodeAt(0),
issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
serialNumber: forge.util.createBuffer(capture.serial).toHex(),
encryptedContent: {
algorithm: asn1.derToOid(capture.encAlgorithm),
parameter: capture.encParameter ? capture.encParameter.value : void 0,
content: capture.encKey
}
};
}
__name(_recipientFromAsn1, "_recipientFromAsn1");
function _recipientToAsn1(obj) {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Version
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(obj.version).getBytes()
),
// IssuerAndSerialNumber
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Name
forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }),
// Serial
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
forge.util.hexToBytes(obj.serialNumber)
)
]),
// KeyEncryptionAlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()
),
// Parameter, force NULL, only RSA supported for now.
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
]),
// EncryptedKey
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
obj.encryptedContent.content
)
]);
}
__name(_recipientToAsn1, "_recipientToAsn1");
function _recipientsFromAsn1(infos) {
var ret = [];
for (var i5 = 0; i5 < infos.length; ++i5) {
ret.push(_recipientFromAsn1(infos[i5]));
}
return ret;
}
__name(_recipientsFromAsn1, "_recipientsFromAsn1");
function _recipientsToAsn1(recipients) {
var ret = [];
for (var i5 = 0; i5 < recipients.length; ++i5) {
ret.push(_recipientToAsn1(recipients[i5]));
}
return ret;
}
__name(_recipientsToAsn1, "_recipientsToAsn1");
function _signerToAsn1(obj) {
var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
asn1.integerToDer(obj.version).getBytes()
),
// issuerAndSerialNumber
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// name
forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }),
// serial
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.INTEGER,
false,
forge.util.hexToBytes(obj.serialNumber)
)
]),
// digestAlgorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(obj.digestAlgorithm).getBytes()
),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
])
]);
if (obj.authenticatedAttributesAsn1) {
rval.value.push(obj.authenticatedAttributesAsn1);
}
rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(obj.signatureAlgorithm).getBytes()
),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "")
]));
rval.value.push(asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
obj.signature
));
if (obj.unauthenticatedAttributes.length > 0) {
var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);
for (var i5 = 0; i5 < obj.unauthenticatedAttributes.length; ++i5) {
var attr = obj.unauthenticatedAttributes[i5];
attrsAsn1.values.push(_attributeToAsn1(attr));
}
rval.value.push(attrsAsn1);
}
return rval;
}
__name(_signerToAsn1, "_signerToAsn1");
function _signersToAsn1(signers) {
var ret = [];
for (var i5 = 0; i5 < signers.length; ++i5) {
ret.push(_signerToAsn1(signers[i5]));
}
return ret;
}
__name(_signersToAsn1, "_signersToAsn1");
function _attributeToAsn1(attr) {
var value;
if (attr.type === forge.pki.oids.contentType) {
value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(attr.value).getBytes()
);
} else if (attr.type === forge.pki.oids.messageDigest) {
value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
attr.value.bytes()
);
} else if (attr.type === forge.pki.oids.signingTime) {
var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z");
var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z");
var date = attr.value;
if (typeof date === "string") {
var timestamp = Date.parse(date);
if (!isNaN(timestamp)) {
date = new Date(timestamp);
} else if (date.length === 13) {
date = asn1.utcTimeToDate(date);
} else {
date = asn1.generalizedTimeToDate(date);
}
}
if (date >= jan_1_1950 && date < jan_1_2050) {
value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.UTCTIME,
false,
asn1.dateToUtcTime(date)
);
} else {
value = asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.GENERALIZEDTIME,
false,
asn1.dateToGeneralizedTime(date)
);
}
}
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// AttributeType
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(attr.type).getBytes()
),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
// AttributeValue
value
])
]);
}
__name(_attributeToAsn1, "_attributeToAsn1");
function _encryptedContentToAsn1(ec) {
return [
// ContentType, always Data for the moment
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(forge.pki.oids.data).getBytes()
),
// ContentEncryptionAlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Algorithm
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OID,
false,
asn1.oidToDer(ec.algorithm).getBytes()
),
// Parameters (IV)
!ec.parameter ? void 0 : asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
ec.parameter.getBytes()
)
]),
// [0] EncryptedContent
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(
asn1.Class.UNIVERSAL,
asn1.Type.OCTETSTRING,
false,
ec.content.getBytes()
)
])
];
}
__name(_encryptedContentToAsn1, "_encryptedContentToAsn1");
function _fromAsn1(msg, obj, validator) {
var capture = {};
var errors = [];
if (!asn1.validate(obj, validator, capture, errors)) {
var error2 = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");
error2.errors = error2;
throw error2;
}
var contentType = asn1.derToOid(capture.contentType);
if (contentType !== forge.pki.oids.data) {
throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");
}
if (capture.encryptedContent) {
var content = "";
if (forge.util.isArray(capture.encryptedContent)) {
for (var i5 = 0; i5 < capture.encryptedContent.length; ++i5) {
if (capture.encryptedContent[i5].type !== asn1.Type.OCTETSTRING) {
throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");
}
content += capture.encryptedContent[i5].value;
}
} else {
content = capture.encryptedContent;
}
msg.encryptedContent = {
algorithm: asn1.derToOid(capture.encAlgorithm),
parameter: forge.util.createBuffer(capture.encParameter.value),
content: forge.util.createBuffer(content)
};
}
if (capture.content) {
var content = "";
if (forge.util.isArray(capture.content)) {
for (var i5 = 0; i5 < capture.content.length; ++i5) {
if (capture.content[i5].type !== asn1.Type.OCTETSTRING) {
throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");
}
content += capture.content[i5].value;
}
} else {
content = capture.content;
}
msg.content = forge.util.createBuffer(content);
}
msg.version = capture.version.charCodeAt(0);
msg.rawCapture = capture;
return capture;
}
__name(_fromAsn1, "_fromAsn1");
function _decryptContent(msg) {
if (msg.encryptedContent.key === void 0) {
throw new Error("Symmetric key not available.");
}
if (msg.content === void 0) {
var ciph;
switch (msg.encryptedContent.algorithm) {
case forge.pki.oids["aes128-CBC"]:
case forge.pki.oids["aes192-CBC"]:
case forge.pki.oids["aes256-CBC"]:
ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);
break;
case forge.pki.oids["desCBC"]:
case forge.pki.oids["des-EDE3-CBC"]:
ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);
break;
default:
throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm);
}
ciph.start(msg.encryptedContent.parameter);
ciph.update(msg.encryptedContent.content);
if (!ciph.finish()) {
throw new Error("Symmetric decryption failed.");
}
msg.content = ciph.output;
}
}
__name(_decryptContent, "_decryptContent");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/ssh.js
var require_ssh = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/ssh.js"(exports2, module3) {
init_import_meta_url();
var forge = require_forge();
require_aes();
require_hmac();
require_md5();
require_sha1();
require_util10();
var ssh = module3.exports = forge.ssh = forge.ssh || {};
ssh.privateKeyToPutty = function(privateKey, passphrase, comment) {
comment = comment || "";
passphrase = passphrase || "";
var algorithm = "ssh-rsa";
var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc";
var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n";
ppk += "Encryption: " + encryptionAlgorithm + "\r\n";
ppk += "Comment: " + comment + "\r\n";
var pubbuffer = forge.util.createBuffer();
_addStringToBuffer(pubbuffer, algorithm);
_addBigIntegerToBuffer(pubbuffer, privateKey.e);
_addBigIntegerToBuffer(pubbuffer, privateKey.n);
var pub = forge.util.encode64(pubbuffer.bytes(), 64);
var length = Math.floor(pub.length / 66) + 1;
ppk += "Public-Lines: " + length + "\r\n";
ppk += pub;
var privbuffer = forge.util.createBuffer();
_addBigIntegerToBuffer(privbuffer, privateKey.d);
_addBigIntegerToBuffer(privbuffer, privateKey.p);
_addBigIntegerToBuffer(privbuffer, privateKey.q);
_addBigIntegerToBuffer(privbuffer, privateKey.qInv);
var priv;
if (!passphrase) {
priv = forge.util.encode64(privbuffer.bytes(), 64);
} else {
var encLen = privbuffer.length() + 16 - 1;
encLen -= encLen % 16;
var padding = _sha1(privbuffer.bytes());
padding.truncate(padding.length() - encLen + privbuffer.length());
privbuffer.putBuffer(padding);
var aeskey = forge.util.createBuffer();
aeskey.putBuffer(_sha1("\0\0\0\0", passphrase));
aeskey.putBuffer(_sha1("\0\0\0", passphrase));
var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), "CBC");
cipher.start(forge.util.createBuffer().fillWithByte(0, 16));
cipher.update(privbuffer.copy());
cipher.finish();
var encrypted = cipher.output;
encrypted.truncate(16);
priv = forge.util.encode64(encrypted.bytes(), 64);
}
length = Math.floor(priv.length / 66) + 1;
ppk += "\r\nPrivate-Lines: " + length + "\r\n";
ppk += priv;
var mackey = _sha1("putty-private-key-file-mac-key", passphrase);
var macbuffer = forge.util.createBuffer();
_addStringToBuffer(macbuffer, algorithm);
_addStringToBuffer(macbuffer, encryptionAlgorithm);
_addStringToBuffer(macbuffer, comment);
macbuffer.putInt32(pubbuffer.length());
macbuffer.putBuffer(pubbuffer);
macbuffer.putInt32(privbuffer.length());
macbuffer.putBuffer(privbuffer);
var hmac2 = forge.hmac.create();
hmac2.start("sha1", mackey);
hmac2.update(macbuffer.bytes());
ppk += "\r\nPrivate-MAC: " + hmac2.digest().toHex() + "\r\n";
return ppk;
};
ssh.publicKeyToOpenSSH = function(key, comment) {
var type = "ssh-rsa";
comment = comment || "";
var buffer = forge.util.createBuffer();
_addStringToBuffer(buffer, type);
_addBigIntegerToBuffer(buffer, key.e);
_addBigIntegerToBuffer(buffer, key.n);
return type + " " + forge.util.encode64(buffer.bytes()) + " " + comment;
};
ssh.privateKeyToOpenSSH = function(privateKey, passphrase) {
if (!passphrase) {
return forge.pki.privateKeyToPem(privateKey);
}
return forge.pki.encryptRsaPrivateKey(
privateKey,
passphrase,
{ legacy: true, algorithm: "aes128" }
);
};
ssh.getPublicKeyFingerprint = function(key, options) {
options = options || {};
var md = options.md || forge.md.md5.create();
var type = "ssh-rsa";
var buffer = forge.util.createBuffer();
_addStringToBuffer(buffer, type);
_addBigIntegerToBuffer(buffer, key.e);
_addBigIntegerToBuffer(buffer, key.n);
md.start();
md.update(buffer.getBytes());
var digest = md.digest();
if (options.encoding === "hex") {
var hex = digest.toHex();
if (options.delimiter) {
return hex.match(/.{2}/g).join(options.delimiter);
}
return hex;
} else if (options.encoding === "binary") {
return digest.getBytes();
} else if (options.encoding) {
throw new Error('Unknown encoding "' + options.encoding + '".');
}
return digest;
};
function _addBigIntegerToBuffer(buffer, val2) {
var hexVal = val2.toString(16);
if (hexVal[0] >= "8") {
hexVal = "00" + hexVal;
}
var bytes = forge.util.hexToBytes(hexVal);
buffer.putInt32(bytes.length);
buffer.putBytes(bytes);
}
__name(_addBigIntegerToBuffer, "_addBigIntegerToBuffer");
function _addStringToBuffer(buffer, val2) {
buffer.putInt32(val2.length);
buffer.putString(val2);
}
__name(_addStringToBuffer, "_addStringToBuffer");
function _sha1() {
var sha = forge.md.sha1.create();
var num = arguments.length;
for (var i5 = 0; i5 < num; ++i5) {
sha.update(arguments[i5]);
}
return sha.digest();
}
__name(_sha1, "_sha1");
}
});
// ../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/index.js
var require_lib2 = __commonJS({
"../../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/index.js"(exports2, module3) {
init_import_meta_url();
module3.exports = require_forge();
require_aes();
require_aesCipherSuites();
require_asn1();
require_cipher();
require_des();
require_ed25519();
require_hmac();
require_kem();
require_log();
require_md_all();
require_mgf1();
require_pbkdf2();
require_pem();
require_pkcs1();
require_pkcs12();
require_pkcs7();
require_pki();
require_prime();
require_prng();
require_pss();
require_random2();
require_rc2();
require_ssh();
require_tls();
require_util10();
}
});
// ../../node_modules/.pnpm/selfsigned@2.1.1/node_modules/selfsigned/index.js
var require_selfsigned = __commonJS({
"../../node_modules/.pnpm/selfsigned@2.1.1/node_modules/selfsigned/index.js"(exports2) {
init_import_meta_url();
var forge = require_lib2();
function toPositiveHex(hexString) {
var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);
if (mostSiginficativeHexAsInt < 8) {
return hexString;
}
mostSiginficativeHexAsInt -= 8;
return mostSiginficativeHexAsInt.toString() + hexString.substring(1);
}
__name(toPositiveHex, "toPositiveHex");
function getAlgorithm(key) {
switch (key) {
case "sha256":
return forge.md.sha256.create();
default:
return forge.md.sha1.create();
}
}
__name(getAlgorithm, "getAlgorithm");
exports2.generate = /* @__PURE__ */ __name(function generate2(attrs, options, done) {
if (typeof attrs === "function") {
done = attrs;
attrs = void 0;
} else if (typeof options === "function") {
done = options;
options = {};
}
options = options || {};
var generatePem = /* @__PURE__ */ __name(function(keyPair2) {
var cert = forge.pki.createCertificate();
cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));
cert.validity.notBefore = /* @__PURE__ */ new Date();
cert.validity.notAfter = /* @__PURE__ */ new Date();
cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365));
attrs = attrs || [{
name: "commonName",
value: "example.org"
}, {
name: "countryName",
value: "US"
}, {
shortName: "ST",
value: "Virginia"
}, {
name: "localityName",
value: "Blacksburg"
}, {
name: "organizationName",
value: "Test"
}, {
shortName: "OU",
value: "Test"
}];
cert.setSubject(attrs);
cert.setIssuer(attrs);
cert.publicKey = keyPair2.publicKey;
cert.setExtensions(options.extensions || [{
name: "basicConstraints",
cA: true
}, {
name: "keyUsage",
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true
}, {
name: "subjectAltName",
altNames: [{
type: 6,
// URI
value: "http://example.org/webid#me"
}]
}]);
cert.sign(keyPair2.privateKey, getAlgorithm(options && options.algorithm));
const fingerprint = forge.md.sha1.create().update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes()).digest().toHex().match(/.{2}/g).join(":");
var pem = {
private: forge.pki.privateKeyToPem(keyPair2.privateKey),
public: forge.pki.publicKeyToPem(keyPair2.publicKey),
cert: forge.pki.certificateToPem(cert),
fingerprint
};
if (options && options.pkcs7) {
var p7 = forge.pkcs7.createSignedData();
p7.addCertificate(cert);
pem.pkcs7 = forge.pkcs7.messageToPem(p7);
}
if (options && options.clientCertificate) {
var clientkeys = forge.pki.rsa.generateKeyPair(1024);
var clientcert = forge.pki.createCertificate();
clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));
clientcert.validity.notBefore = /* @__PURE__ */ new Date();
clientcert.validity.notAfter = /* @__PURE__ */ new Date();
clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);
var clientAttrs = JSON.parse(JSON.stringify(attrs));
for (var i5 = 0; i5 < clientAttrs.length; i5++) {
if (clientAttrs[i5].name === "commonName") {
if (options.clientCertificateCN)
clientAttrs[i5] = { name: "commonName", value: options.clientCertificateCN };
else
clientAttrs[i5] = { name: "commonName", value: "John Doe jdoe123" };
}
}
clientcert.setSubject(clientAttrs);
clientcert.setIssuer(attrs);
clientcert.publicKey = clientkeys.publicKey;
clientcert.sign(keyPair2.privateKey);
pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);
pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);
pem.clientcert = forge.pki.certificateToPem(clientcert);
if (options.pkcs7) {
var clientp7 = forge.pkcs7.createSignedData();
clientp7.addCertificate(clientcert);
pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);
}
}
var caStore = forge.pki.createCaStore();
caStore.addCertificate(cert);
try {
forge.pki.verifyCertificateChain(
caStore,
[cert],
function(vfd, depth, chain2) {
if (vfd !== true) {
throw new Error("Certificate could not be verified.");
}
return true;
}
);
} catch (ex) {
throw new Error(ex);
}
return pem;
}, "generatePem");
var keySize = options.keySize || 1024;
if (done) {
return forge.pki.rsa.generateKeyPair({ bits: keySize }, function(err, keyPair2) {
if (err) {
return done(err);
}
try {
return done(null, generatePem(keyPair2));
} catch (ex) {
return done(ex);
}
});
}
var keyPair = options.keyPair ? {
privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),
publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)
} : forge.pki.rsa.generateKeyPair(keySize);
return generatePem(keyPair);
}, "generate");
}
});
// src/https-options.ts
function getHttpsOptions(customHttpsKeyPath = getHttpsKeyPathFromEnv(), customHttpsCertPath = getHttpsCertPathFromEnv()) {
if (customHttpsKeyPath !== void 0 || customHttpsCertPath !== void 0) {
if (customHttpsKeyPath === void 0 || customHttpsCertPath === void 0) {
throw new UserError(
"Must specify both certificate path and key path to use a Custom Certificate."
);
}
if (!fs23.existsSync(customHttpsKeyPath)) {
throw new UserError(
"Missing Custom Certificate Key at " + customHttpsKeyPath
);
}
if (!fs23.existsSync(customHttpsCertPath)) {
throw new UserError(
"Missing Custom Certificate File at " + customHttpsCertPath
);
}
logger.log("Using custom certificate at ", customHttpsKeyPath);
return {
key: fs23.readFileSync(customHttpsKeyPath, "utf8"),
cert: fs23.readFileSync(customHttpsCertPath, "utf8")
};
}
const certDirectory = path67.join(getGlobalWranglerConfigPath(), "local-cert");
const keyPath = path67.join(certDirectory, "key.pem");
const certPath = path67.join(certDirectory, "cert.pem");
const regenerate = !fs23.existsSync(keyPath) || !fs23.existsSync(certPath) || hasCertificateExpired(keyPath, certPath);
if (regenerate) {
logger.log("Generating new self-signed certificate...");
const { key, cert } = generateCertificate();
try {
fs23.mkdirSync(certDirectory, { recursive: true });
fs23.writeFileSync(keyPath, key, "utf8");
fs23.writeFileSync(certPath, cert, "utf8");
} catch (e7) {
const message = e7 instanceof Error ? e7.message : `${e7}`;
logger.warn(
`Unable to cache generated self-signed certificate in ${path67.relative(
process.cwd(),
certDirectory
)}.
${message}`
);
}
return { key, cert };
} else {
return {
key: fs23.readFileSync(keyPath, "utf8"),
cert: fs23.readFileSync(certPath, "utf8")
};
}
}
function hasCertificateExpired(keyPath, certPath) {
const keyStat = fs23.statSync(keyPath);
const certStat = fs23.statSync(certPath);
const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
return Date.now() - created > (CERT_EXPIRY_DAYS - 2) * ONE_DAY_IN_MS;
}
function generateCertificate() {
const generate2 = (
// eslint-disable-next-line @typescript-eslint/no-require-imports
require_selfsigned().generate
);
const certAttrs = [{ name: "commonName", value: "localhost" }];
const certOptions = {
algorithm: "sha256",
days: CERT_EXPIRY_DAYS,
keySize: 2048,
extensions: [
{ name: "basicConstraints", cA: true },
{
name: "keyUsage",
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true
},
{
name: "extKeyUsage",
serverAuth: true,
clientAuth: true,
codeSigning: true,
timeStamping: true
},
{
name: "subjectAltName",
altNames: [
{ type: 2, value: "localhost" },
...(0, import_miniflare23.getAccessibleHosts)(false).map((ip) => ({ type: 7, ip }))
]
}
]
};
const { private: key, cert } = generate2(certAttrs, certOptions);
return { key, cert };
}
var fs23, path67, import_miniflare23, CERT_EXPIRY_DAYS, ONE_DAY_IN_MS, getHttpsKeyPathFromEnv, getHttpsCertPathFromEnv;
var init_https_options = __esm({
"src/https-options.ts"() {
init_import_meta_url();
fs23 = __toESM(require("fs"));
path67 = __toESM(require("path"));
import_miniflare23 = require("miniflare");
init_factory();
init_errors();
init_global_wrangler_config_path();
init_logger();
CERT_EXPIRY_DAYS = 30;
ONE_DAY_IN_MS = 864e5;
getHttpsKeyPathFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_HTTPS_KEY_PATH"
});
getHttpsCertPathFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_HTTPS_CERT_PATH"
});
__name(getHttpsOptions, "getHttpsOptions");
__name(hasCertificateExpired, "hasCertificateExpired");
__name(generateCertificate, "generateCertificate");
}
});
// src/api/startDevWorker/ProxyController.ts
function deepEquality(a5, b6) {
return JSON.stringify(a5) === JSON.stringify(b6);
}
function didMiniflareOptionsChange(prev, next) {
if (prev === void 0) {
return false;
}
return !deepEquality(prev, next);
}
var import_node_assert29, import_node_crypto13, import_node_events4, import_node_path63, import_miniflare24, ProxyController, ProxyControllerLogger;
var init_ProxyController = __esm({
"src/api/startDevWorker/ProxyController.ts"() {
init_import_meta_url();
import_node_assert29 = __toESM(require("assert"));
import_node_crypto13 = require("crypto");
import_node_events4 = __toESM(require("events"));
import_node_path63 = __toESM(require("path"));
import_miniflare24 = require("miniflare");
init_InspectorProxyWorker();
init_ProxyWorker();
init_wrapper();
init_inspect2();
init_miniflare();
init_stdio();
init_https_options();
init_logger();
init_sourcemap();
init_BaseController();
init_events();
init_utils2();
ProxyController = class extends Controller {
static {
__name(this, "ProxyController");
}
ready = createDeferred();
localServerReady = createDeferred();
proxyWorker;
proxyWorkerOptions;
inspectorProxyWorkerWebSocket;
latestConfig;
latestBundle;
secret = (0, import_node_crypto13.randomUUID)();
createProxyWorker() {
if (this._torndown) {
return;
}
(0, import_node_assert29.default)(this.latestConfig !== void 0);
const inVscodeJsDebugTerminal = !!process.env.VSCODE_INSPECTOR_OPTIONS;
const cert = this.latestConfig.dev?.server?.secure || this.latestConfig.dev.inspector !== false && this.latestConfig.dev?.inspector?.secure ? getHttpsOptions(
this.latestConfig.dev.server?.httpsKeyPath,
this.latestConfig.dev.server?.httpsCertPath
) : void 0;
const proxyWorkerOptions = {
host: this.latestConfig.dev?.server?.hostname,
port: this.latestConfig.dev?.server?.port,
https: this.latestConfig.dev?.server?.secure,
httpsCert: cert?.cert,
httpsKey: cert?.key,
stripDisablePrettyError: false,
workers: [
{
name: "ProxyWorker",
compatibilityDate: "2023-12-18",
compatibilityFlags: ["nodejs_compat"],
modulesRoot: import_node_path63.default.dirname(ProxyWorker_default),
modules: [{ type: "ESModule", path: ProxyWorker_default }],
durableObjects: {
DURABLE_OBJECT: {
className: "ProxyWorker",
unsafePreventEviction: true
}
},
// Miniflare will strip CF-Connecting-IP from outgoing fetches from a Worker (to fix https://github.com/cloudflare/workers-sdk/issues/7924)
// However, the proxy worker only makes outgoing requests to the user Worker Miniflare instance, which _should_ receive CF-Connecting-IP
stripCfConnectingIp: false,
serviceBindings: {
PROXY_CONTROLLER: /* @__PURE__ */ __name(async (req) => {
const message = await req.json();
this.onProxyWorkerMessage(message);
return new import_miniflare24.Response(null, { status: 204 });
}, "PROXY_CONTROLLER")
},
bindings: {
PROXY_CONTROLLER_AUTH_SECRET: this.secret
},
// no need to use file-system, so don't
cache: false,
unsafeEphemeralDurableObjects: true
}
],
verbose: logger.loggerLevel === "debug",
// log requests into the ProxyWorker (for local + remote mode)
log: new ProxyControllerLogger(
castLogLevel(logger.loggerLevel),
{
prefix: (
// if debugging, log requests with specic ProxyWorker prefix
logger.loggerLevel === "debug" ? "wrangler-ProxyWorker" : "wrangler"
)
},
this.localServerReady.promise
),
handleRuntimeStdio: handleRuntimeStdioWithStructuredLogs,
structuredWorkerdLogs: true,
liveReload: false
};
if (this.latestConfig.dev.inspector !== false && !inVscodeJsDebugTerminal) {
proxyWorkerOptions.workers.push({
name: "InspectorProxyWorker",
compatibilityDate: "2023-12-18",
compatibilityFlags: [
"nodejs_compat",
"increase_websocket_message_size"
],
modulesRoot: import_node_path63.default.dirname(InspectorProxyWorker_default),
modules: [{ type: "ESModule", path: InspectorProxyWorker_default }],
durableObjects: {
DURABLE_OBJECT: {
className: "InspectorProxyWorker",
unsafePreventEviction: true
}
},
serviceBindings: {
PROXY_CONTROLLER: /* @__PURE__ */ __name(async (req) => {
const body = await req.json();
return this.onInspectorProxyWorkerRequest(body);
}, "PROXY_CONTROLLER")
},
bindings: {
PROXY_CONTROLLER_AUTH_SECRET: this.secret
},
unsafeDirectSockets: [
{
host: this.latestConfig.dev?.inspector?.hostname,
port: this.latestConfig.dev?.inspector?.port ?? 0
}
],
// no need to use file-system, so don't
cache: false,
unsafeEphemeralDurableObjects: true
});
}
const proxyWorkerOptionsChanged = didMiniflareOptionsChange(
this.proxyWorkerOptions,
proxyWorkerOptions
);
const willInstantiateMiniflareInstance = !this.proxyWorker || proxyWorkerOptionsChanged;
this.proxyWorker ??= new import_miniflare24.Miniflare(proxyWorkerOptions);
this.proxyWorkerOptions = proxyWorkerOptions;
if (proxyWorkerOptionsChanged) {
logger.debug("ProxyWorker miniflare options changed, reinstantiating...");
void this.proxyWorker.setOptions(proxyWorkerOptions).catch((error2) => {
this.emitErrorEvent("Failed to start ProxyWorker", error2);
});
this.ready = createDeferred(this.ready);
}
const { proxyWorker } = this;
if (willInstantiateMiniflareInstance) {
void Promise.all([
proxyWorker.ready,
this.latestConfig.dev.inspector === false || inVscodeJsDebugTerminal ? Promise.resolve(void 0) : proxyWorker.unsafeGetDirectURL("InspectorProxyWorker")
]).then(([url4, inspectorUrl]) => {
if (!inspectorUrl || inVscodeJsDebugTerminal) {
return [url4, void 0];
}
return this.reconnectInspectorProxyWorker().then(() => [
url4,
inspectorUrl
]);
}).then(([url4, inspectorUrl]) => {
(0, import_node_assert29.default)(url4);
this.emitReadyEvent(proxyWorker, url4, inspectorUrl);
}).catch((error2) => {
if (this._torndown) {
return;
}
this.emitErrorEvent(
"Failed to start ProxyWorker or InspectorProxyWorker",
error2
);
});
}
}
async reconnectInspectorProxyWorker() {
if (this._torndown) {
return;
}
(0, import_node_assert29.default)(
this.latestConfig?.dev.inspector !== false,
"Trying to reconnect with inspector proxy worker when inspector is disabled"
);
const existingWebSocket = await this.inspectorProxyWorkerWebSocket?.promise;
if (existingWebSocket?.readyState === wrapper_default.OPEN) {
return existingWebSocket;
}
this.inspectorProxyWorkerWebSocket = createDeferred();
let webSocket = null;
try {
(0, import_node_assert29.default)(this.proxyWorker);
const inspectorProxyWorkerUrl = await this.proxyWorker.unsafeGetDirectURL(
"InspectorProxyWorker"
);
webSocket = new wrapper_default(
`${inspectorProxyWorkerUrl.href}/cdn-cgi/InspectorProxyWorker/websocket`,
{
headers: { Authorization: this.secret }
}
);
} catch (cause) {
if (this._torndown) {
return;
}
const error2 = castErrorCause(cause);
this.inspectorProxyWorkerWebSocket?.reject(error2);
this.emitErrorEvent("Could not connect to InspectorProxyWorker", error2);
return;
}
(0, import_node_assert29.default)(
webSocket,
"Expected webSocket on response from inspectorProxyWorker"
);
webSocket.addEventListener("message", (event) => {
(0, import_node_assert29.default)(typeof event.data === "string");
this.onInspectorProxyWorkerMessage(JSON.parse(event.data));
});
webSocket.addEventListener("close", () => {
});
webSocket.addEventListener("error", () => {
if (this._torndown) {
return;
}
if (this.latestConfig?.dev.inspector !== false) {
void this.reconnectInspectorProxyWorker();
}
});
await import_node_events4.default.once(webSocket, "open");
this.inspectorProxyWorkerWebSocket?.resolve(webSocket);
return webSocket;
}
runtimeMessageMutex = new import_miniflare24.Mutex();
async sendMessageToProxyWorker(message, retries = 3) {
if (this._torndown) {
return;
}
try {
await this.runtimeMessageMutex.runWith(async () => {
const { proxyWorker } = await this.ready.promise;
const ready = await proxyWorker.ready.catch(() => void 0);
if (!ready) {
return;
}
return proxyWorker.dispatchFetch(
`http://dummy/cdn-cgi/ProxyWorker/${message.type}`,
{
headers: { Authorization: this.secret },
cf: { hostMetadata: message }
}
);
});
} catch (cause) {
if (this._torndown) {
return;
}
const error2 = castErrorCause(cause);
if (retries > 0) {
return this.sendMessageToProxyWorker(message, retries - 1);
}
this.emitErrorEvent(
`Failed to send message to ProxyWorker: ${JSON.stringify(message)}`,
error2
);
}
}
async sendMessageToInspectorProxyWorker(message, retries = 3) {
if (this._torndown) {
return;
}
(0, import_node_assert29.default)(
this.latestConfig?.dev.inspector !== false,
"Trying to send message to inspector proxy worker when inspector is disabled"
);
try {
const websocket = await this.reconnectInspectorProxyWorker();
(0, import_node_assert29.default)(websocket);
websocket.send(JSON.stringify(message));
} catch (cause) {
if (this._torndown) {
return;
}
const error2 = castErrorCause(cause);
if (retries > 0) {
return this.sendMessageToInspectorProxyWorker(message, retries - 1);
}
this.emitErrorEvent(
`Failed to send message to InspectorProxyWorker: ${JSON.stringify(
message
)}`,
error2
);
}
}
// ******************
// Event Handlers
// ******************
onConfigUpdate(data) {
this.latestConfig = data.config;
this.createProxyWorker();
void this.sendMessageToProxyWorker({ type: "pause" });
}
onBundleStart(data) {
this.latestConfig = data.config;
void this.sendMessageToProxyWorker({ type: "pause" });
}
onReloadStart(data) {
this.latestConfig = data.config;
void this.sendMessageToProxyWorker({ type: "pause" });
if (this.latestConfig.dev.inspector !== false) {
void this.sendMessageToInspectorProxyWorker({ type: "reloadStart" });
}
}
onReloadComplete(data) {
this.localServerReady.resolve();
this.latestConfig = data.config;
this.latestBundle = data.bundle;
void this.sendMessageToProxyWorker({
type: "play",
proxyData: data.proxyData
});
if (this.latestConfig.dev.inspector !== false) {
void this.sendMessageToInspectorProxyWorker({
type: "reloadComplete",
proxyData: data.proxyData
});
}
}
onProxyWorkerMessage(message) {
switch (message.type) {
case "previewTokenExpired":
this.emitPreviewTokenExpiredEvent(message.proxyData);
break;
case "error":
this.emitErrorEvent("Error inside ProxyWorker", message.error);
break;
case "debug-log":
logger.debug("[ProxyWorker]", ...message.args);
break;
default:
assertNever(message);
}
}
onInspectorProxyWorkerMessage(message) {
(0, import_node_assert29.default)(
this.latestConfig?.dev.inspector !== false,
"Trying to handle inspector message when inspector is disabled"
);
switch (message.method) {
case "Runtime.consoleAPICalled": {
if (this._torndown) {
return;
}
logConsoleMessage(message.params);
break;
}
case "Runtime.exceptionThrown": {
if (this._torndown) {
return;
}
const stack = getSourceMappedStack(message.params.exceptionDetails);
logger.error(message.params.exceptionDetails.text, stack);
break;
}
default: {
assertNever(message);
}
}
}
async onInspectorProxyWorkerRequest(message) {
(0, import_node_assert29.default)(
this.latestConfig?.dev.inspector !== false,
"Trying to handle inspector request when inspector is disabled"
);
switch (message.type) {
case "runtime-websocket-error":
logger.debug(
"[InspectorProxyWorker] 'runtime websocket' error",
message.error
);
break;
case "error":
this.emitErrorEvent("Error inside InspectorProxyWorker", message.error);
break;
case "debug-log":
if (this._torndown) {
break;
}
logger.debug("[InspectorProxyWorker]", ...message.args);
break;
case "load-network-resource": {
(0, import_node_assert29.default)(this.latestConfig !== void 0);
(0, import_node_assert29.default)(this.latestBundle !== void 0);
let maybeContents;
if (message.url.startsWith("wrangler-file:")) {
maybeContents = maybeHandleNetworkLoadResource(
message.url.replace("wrangler-file:", "file:"),
this.latestBundle,
this.latestBundle.sourceMapMetadata?.tmpDir
);
}
if (maybeContents === void 0) {
return new import_miniflare24.Response(null, { status: 404 });
}
return new import_miniflare24.Response(maybeContents);
}
default:
assertNever(message);
return new import_miniflare24.Response(null, { status: 404 });
}
return new import_miniflare24.Response(null, { status: 204 });
}
_torndown = false;
async teardown() {
logger.debug("ProxyController teardown beginning...");
this._torndown = true;
const { proxyWorker } = this;
this.proxyWorker = void 0;
await Promise.all([
proxyWorker?.dispose(),
this.inspectorProxyWorkerWebSocket?.promise.then((ws) => ws.close()).catch(() => {
})
]);
logger.debug("ProxyController teardown complete");
}
// *********************
// Event Dispatchers
// *********************
emitReadyEvent(proxyWorker, url4, inspectorUrl) {
const data = {
type: "ready",
proxyWorker,
url: url4,
inspectorUrl
};
this.emit("ready", data);
this.ready.resolve(data);
}
emitPreviewTokenExpiredEvent(proxyData) {
this.emit("previewTokenExpired", {
type: "previewTokenExpired",
proxyData
});
}
emitErrorEvent(data, cause) {
if (typeof data === "string") {
data = {
type: "error",
source: "ProxyController",
cause: castErrorCause(cause),
reason: data,
data: {
config: this.latestConfig,
bundle: this.latestBundle
}
};
}
super.emitErrorEvent(data);
}
};
ProxyControllerLogger = class extends WranglerLog {
constructor(level, opts, localServerReady) {
super(level, opts);
this.localServerReady = localServerReady;
}
static {
__name(this, "ProxyControllerLogger");
}
logReady(message) {
this.localServerReady.then(() => super.logReady(message)).catch(() => {
});
}
log(message) {
if (message.includes("/cdn-cgi/") && this.level < import_miniflare24.LogLevel.DEBUG) {
return;
}
super.log(message);
}
};
__name(deepEquality, "deepEquality");
__name(didMiniflareOptionsChange, "didMiniflareOptionsChange");
}
});
// src/utils/isAbortError.ts
function isAbortError(err) {
const legacyAbortErroCheck = err.code !== "ABORT_ERR";
const abortErrorCheck = err instanceof Error && err.name == "AbortError";
return legacyAbortErroCheck || abortErrorCheck;
}
var init_isAbortError = __esm({
"src/utils/isAbortError.ts"() {
init_import_meta_url();
__name(isAbortError, "isAbortError");
}
});
// src/dev/create-worker-preview.ts
function switchHost(originalUrl, host, zonePreview) {
const url4 = new import_node_url12.URL(originalUrl);
url4.hostname = zonePreview ? host ?? url4.hostname : url4.hostname;
return url4;
}
async function createPreviewSession(complianceConfig, account, ctx, abortSignal) {
const { accountId, apiToken } = account;
const initUrl = ctx.zone ? `/zones/${ctx.zone}/workers/edge-preview` : `/accounts/${accountId}/workers/subdomain/edge-preview`;
const { exchange_url } = await fetchResult(
complianceConfig,
initUrl,
void 0,
void 0,
abortSignal,
apiToken
);
const switchedExchangeUrl = switchHost(
exchange_url,
ctx.host,
!!ctx.zone
).toString();
logger.debugWithSanitization(
"-- START EXCHANGE API REQUEST:",
` GET ${switchedExchangeUrl}`
);
logger.debug("-- END EXCHANGE API REQUEST");
const exchangeResponse = await (0, import_undici23.fetch)(switchedExchangeUrl, {
signal: abortSignal
});
const bodyText = await exchangeResponse.text();
logger.debug(
"-- START EXCHANGE API RESPONSE:",
exchangeResponse.statusText,
exchangeResponse.status
);
logger.debug("HEADERS:", JSON.stringify(exchangeResponse.headers, null, 2));
logger.debugWithSanitization("RESPONSE:", bodyText);
logger.debug("-- END EXCHANGE API RESPONSE");
try {
const { inspector_websocket, prewarm, token } = parseJSON(bodyText);
const inspector = new import_node_url12.URL(inspector_websocket);
inspector.searchParams.append("cf_workers_preview_token", token);
return {
id: import_node_crypto14.default.randomUUID(),
value: token,
host: ctx.host ?? inspector.host,
inspectorUrl: switchHost(inspector.href, ctx.host, !!ctx.zone),
prewarmUrl: switchHost(prewarm, ctx.host, !!ctx.zone)
};
} catch (e7) {
if (!(e7 instanceof ParseError)) {
throw e7;
} else {
throw new UserError(
`Could not create remote preview session on ${ctx.zone ? ` host \`${ctx.host}\` on zone \`${ctx.zone}\`` : `your account`}.`
);
}
}
}
async function createPreviewToken(complianceConfig, account, worker, ctx, session, abortSignal, minimal_mode) {
const { value, host, inspectorUrl, prewarmUrl } = session;
const { accountId } = account;
const url4 = ctx.env && !ctx.legacyEnv ? `/accounts/${accountId}/workers/services/${worker.name}/environments/${ctx.env}/edge-preview` : `/accounts/${accountId}/workers/scripts/${worker.name}/edge-preview`;
const mode = ctx.zone ? {
routes: ctx.routes && ctx.routes.length > 0 ? (
// extract all the route patterns
ctx.routes.map((route) => {
if (typeof route === "string") {
return route;
}
if (route.custom_domain) {
return `${route.pattern}/*`;
}
return route.pattern;
})
) : (
// if there aren't any patterns, then just match on all routes
["*/*"]
),
minimal_mode
} : { workers_dev: true, minimal_mode };
const formData = createWorkerUploadForm(worker);
formData.set("wrangler-session-config", JSON.stringify(mode));
const { preview_token } = await fetchResult(
complianceConfig,
url4,
{
method: "POST",
body: formData,
headers: {
"cf-preview-upload-config-token": value
}
},
void 0,
abortSignal
);
return {
value: preview_token,
host: ctx.host ?? (worker.name ? `${worker.name}.${host.split(".").slice(1).join(".")}` : host),
inspectorUrl,
prewarmUrl
};
}
async function createWorkerPreview(complianceConfig, init3, account, ctx, session, abortSignal, minimal_mode) {
const token = await createPreviewToken(
complianceConfig,
account,
init3,
ctx,
session,
abortSignal,
minimal_mode
);
const accessToken = await getAccessToken(token.prewarmUrl.hostname);
const headers = { "cf-workers-preview-token": token.value };
if (accessToken) {
headers.cookie = `CF_Authorization=${accessToken}`;
}
(0, import_undici23.fetch)(token.prewarmUrl.href, {
method: "POST",
signal: abortSignal,
headers
}).then(
(response) => {
if (!response.ok) {
logger.warn("worker failed to prewarm: ", response.statusText);
}
},
(err) => {
if (isAbortError(err)) {
logger.warn("worker failed to prewarm: ", err);
}
}
);
return token;
}
var import_node_crypto14, import_node_url12, import_undici23;
var init_create_worker_preview = __esm({
"src/dev/create-worker-preview.ts"() {
init_import_meta_url();
import_node_crypto14 = __toESM(require("crypto"));
import_node_url12 = require("url");
import_undici23 = __toESM(require_undici());
init_cfetch();
init_create_worker_upload_form();
init_errors();
init_logger();
init_parse();
init_access();
init_isAbortError();
__name(switchHost, "switchHost");
__name(createPreviewSession, "createPreviewSession");
__name(createPreviewToken, "createPreviewToken");
__name(createWorkerPreview, "createWorkerPreview");
}
});
// src/dev/remote.ts
function handlePreviewSessionUploadError(err, accountId) {
(0, import_node_assert30.default)(err && typeof err === "object");
if (isAbortError(err)) {
if ("code" in err && err.code === 10049) {
logger.log("Preview token expired, fetching a new one");
return true;
} else if (!handleUserFriendlyError(err, accountId)) {
logger.error("Error on remote worker:", err);
}
}
return false;
}
function handlePreviewSessionCreationError(err, accountId) {
(0, import_node_assert30.default)(err && typeof err === "object");
if ("code" in err && err.code === 10063) {
const errorMessage = "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
const solutionMessage = "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
logger.error(`${errorMessage}
${solutionMessage}
${onboardingLink}`);
} else if ("cause" in err && err.cause?.code === "ENOTFOUND") {
logger.error(
`Could not access \`${err.cause.hostname}\`. Make sure the domain is set up to be proxied by Cloudflare.
For more details, refer to https://developers.cloudflare.com/workers/configuration/routing/routes/#set-up-a-route`
);
} else if (err instanceof UserError) {
logger.error(err.message);
} else if (isAbortError(err)) {
logger.error("Error while creating remote dev session:", err);
}
}
async function createRemoteWorkerInit(props) {
const { entrypointSource: content, modules } = withSourceURLs(
props.bundle.path,
props.bundle.entrypointSource,
props.modules
);
void printBundleSize(
{
name: import_node_path64.default.basename(props.bundle.path),
content
},
props.modules
);
const workersSitesAssets = await syncWorkersSite(
props.complianceConfig,
props.accountId,
// When we're using the newer service environments, we wouldn't
// have added the env name on to the script name. However, we must
// include it in the kv namespace name regardless (since there's no
// concept of service environments for kv namespaces yet).
props.name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
props.isWorkersSite ? props.legacyAssetPaths : void 0,
true,
false,
void 0
);
if (workersSitesAssets.manifest) {
modules.push({
name: "__STATIC_CONTENT_MANIFEST",
filePath: void 0,
content: JSON.stringify(workersSitesAssets.manifest),
type: "text"
});
}
const assetsJwt = props.assets ? await syncAssets(
props.complianceConfig,
props.accountId,
props.assets.directory,
props.name
) : void 0;
const init3 = {
name: props.name,
main: {
name: import_node_path64.default.basename(props.bundle.path),
filePath: props.bundle.path,
type: getBundleType(props.format, import_node_path64.default.basename(props.bundle.path)),
content
},
modules,
bindings: {
...props.bindings,
kv_namespaces: (props.bindings.kv_namespaces || []).concat(
workersSitesAssets.namespace ? { binding: "__STATIC_CONTENT", id: workersSitesAssets.namespace } : []
),
text_blobs: {
...props.bindings.text_blobs,
...workersSitesAssets.manifest && props.format === "service-worker" && {
__STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST"
}
}
},
migrations: void 0,
// no migrations in dev
compatibility_date: props.compatibilityDate,
compatibility_flags: props.compatibilityFlags,
keepVars: true,
keepSecrets: true,
logpush: false,
sourceMaps: void 0,
assets: props.assets && assetsJwt ? {
jwt: assetsJwt,
routerConfig: props.assets.routerConfig,
assetConfig: props.assets.assetConfig,
_redirects: props.assets._redirects,
_headers: props.assets._headers,
run_worker_first: props.assets.run_worker_first
} : void 0,
placement: void 0,
// no placement in dev
tail_consumers: void 0,
// no tail consumers in dev - TODO revisit?
limits: void 0,
// no limits in preview - not supported yet but can be added
observability: void 0
// no observability in dev,
};
return init3;
}
async function getWorkerAccountAndContext(props) {
const workerAccount = {
accountId: props.accountId,
apiToken: props.apiToken ?? requireApiToken()
};
const zoneId = await getZoneIdForPreview(props.complianceConfig, {
host: props.host,
routes: props.routes,
accountId: props.accountId
});
const workerContext = {
env: props.env,
legacyEnv: props.legacyEnv,
zone: zoneId,
host: props.host ?? getInferredHost(props.routes, props.configPath),
routes: props.routes,
sendMetrics: props.sendMetrics
};
return { workerAccount, workerContext };
}
function handleUserFriendlyError(error2, accountId) {
switch (error2.code) {
// code 10021 is a validation error
case 10021: {
if (error2.notes[0].text === "binding DB of type d1 must have a valid `id` specified [code: 10021]") {
const errorMessage = "Error: You must use a real database in the preview_database_id configuration.";
const solutionMessage = "You can find your databases using 'wrangler d1 list', or read how to develop locally with D1 here:";
const documentationLink = `https://developers.cloudflare.com/d1/configuration/local-development`;
logger.error(
`${errorMessage}
${solutionMessage}
${documentationLink}`
);
return true;
}
return false;
}
// for error 10063 (workers.dev subdomain required)
case 10063: {
const errorMessage = "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
const solutionMessage = "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
const onboardingLink = accountId ? `https://dash.cloudflare.com/${accountId}/workers/onboarding` : "https://dash.cloudflare.com/?to=/:account/workers/onboarding";
logger.error(`${errorMessage}
${solutionMessage}
${onboardingLink}`);
return true;
}
default: {
return false;
}
}
}
var import_node_assert30, import_node_path64;
var init_remote = __esm({
"src/dev/remote.ts"() {
init_import_meta_url();
import_node_assert30 = __toESM(require("assert"));
import_node_path64 = __toESM(require("path"));
init_assets();
init_bundle_reporter();
init_bundle_type();
init_source_url();
init_dev2();
init_errors();
init_logger();
init_sites();
init_user2();
init_isAbortError();
init_zones();
__name(handlePreviewSessionUploadError, "handlePreviewSessionUploadError");
__name(handlePreviewSessionCreationError, "handlePreviewSessionCreationError");
__name(createRemoteWorkerInit, "createRemoteWorkerInit");
__name(getWorkerAccountAndContext, "getWorkerAccountAndContext");
__name(handleUserFriendlyError, "handleUserFriendlyError");
}
});
// src/api/startDevWorker/NotImplementedError.ts
function notImplemented(func, namespace) {
if (namespace) {
func = `${namespace}#${func}`;
}
logger.debug(`Not Implemented Error: ${func}`);
return new NotImplementedError(func, namespace);
}
var NotImplementedError;
var init_NotImplementedError = __esm({
"src/api/startDevWorker/NotImplementedError.ts"() {
init_import_meta_url();
init_logger();
NotImplementedError = class extends Error {
static {
__name(this, "NotImplementedError");
}
constructor(func, namespace) {
if (namespace) {
func = `${namespace}#${func}`;
}
super(`Not Implemented Error: ${func}`);
}
};
__name(notImplemented, "notImplemented");
}
});
// src/api/startDevWorker/RemoteRuntimeController.ts
var import_miniflare26, RemoteRuntimeController;
var init_RemoteRuntimeController = __esm({
"src/api/startDevWorker/RemoteRuntimeController.ts"() {
init_import_meta_url();
init_source();
import_miniflare26 = require("miniflare");
init_create_worker_preview();
init_remote();
init_errors();
init_logger();
init_access();
init_BaseController();
init_events();
init_NotImplementedError();
init_utils2();
RemoteRuntimeController = class extends RuntimeController {
static {
__name(this, "RemoteRuntimeController");
}
#abortController = new AbortController();
#currentBundleId = 0;
#mutex = new import_miniflare26.Mutex();
#session;
async #previewSession(props) {
try {
const { workerAccount, workerContext } = await getWorkerAccountAndContext(props);
return await createPreviewSession(
props.complianceConfig,
workerAccount,
workerContext,
this.#abortController.signal
);
} catch (err) {
if (err instanceof Error && err.name == "AbortError") {
return;
}
handlePreviewSessionCreationError(err, props.accountId);
}
}
async #previewToken(props) {
if (!this.#session) {
return;
}
try {
if (props.bundleId !== this.#currentBundleId) {
return;
}
const { workerAccount, workerContext } = await getWorkerAccountAndContext(
{
complianceConfig: props.complianceConfig,
accountId: props.accountId,
env: props.env,
legacyEnv: props.legacyEnv,
host: props.host,
routes: props.routes,
sendMetrics: props.sendMetrics,
configPath: props.configPath
}
);
const scriptId = props.name || (workerContext.zone ? this.#session.id : this.#session.host.split(".")[0]);
if (props.bundleId !== this.#currentBundleId) {
return;
}
const init3 = await createRemoteWorkerInit({
complianceConfig: props.complianceConfig,
bundle: props.bundle,
modules: props.modules,
accountId: props.accountId,
name: scriptId,
legacyEnv: props.legacyEnv,
env: props.env,
isWorkersSite: props.isWorkersSite,
assets: props.assets,
legacyAssetPaths: props.legacyAssetPaths,
format: props.format,
bindings: props.bindings,
compatibilityDate: props.compatibilityDate,
compatibilityFlags: props.compatibilityFlags
});
if (props.bundleId !== this.#currentBundleId) {
return;
}
const workerPreviewToken = await createWorkerPreview(
props.complianceConfig,
init3,
workerAccount,
workerContext,
this.#session,
this.#abortController.signal,
props.minimal_mode
);
return workerPreviewToken;
} catch (err) {
if (err instanceof Error && err.name == "AbortError") {
return;
}
const shouldRestartSession = handlePreviewSessionUploadError(
err,
props.accountId
);
if (shouldRestartSession) {
this.#session = await this.#previewSession(props);
return this.#previewToken(props);
}
}
}
async #onBundleComplete({ config, bundle }, id) {
logger.log(source_default.dim("\u2394 Starting remote preview..."));
try {
const routes = config.triggers?.filter(
(trigger) => trigger.type === "route"
).map((trigger) => {
const { type: _4, ...route } = trigger;
if ("custom_domain" in route || "zone_id" in route || "zone_name" in route) {
return route;
} else {
return route.pattern;
}
});
if (!config.dev?.auth) {
throw new MissingConfigError("config.dev.auth");
}
const auth = await unwrapHook(config.dev.auth);
if (this.#session) {
logger.log(source_default.dim("\u2394 Detected changes, restarted server."));
}
this.#session ??= await this.#previewSession({
complianceConfig: { compliance_region: config.complianceRegion },
accountId: auth.accountId,
apiToken: auth.apiToken,
env: config.env,
// deprecated service environments -- just pass it through for now
legacyEnv: !config.legacy?.enableServiceEnvironments,
// wrangler environment -- just pass it through for now
host: config.dev.origin?.hostname,
routes,
sendMetrics: config.sendMetrics,
configPath: config.config
});
const { bindings } = await convertBindingsToCfWorkerInitBindings(
config.bindings
);
if (id !== this.#currentBundleId) {
return;
}
const token = await this.#previewToken({
bundle,
modules: bundle.modules,
accountId: auth.accountId,
complianceConfig: { compliance_region: config.complianceRegion },
name: config.name,
legacyEnv: !config.legacy?.enableServiceEnvironments,
env: config.env,
isWorkersSite: config.legacy?.site !== void 0,
assets: config.assets,
legacyAssetPaths: config.legacy?.site?.bucket ? {
baseDirectory: config.legacy?.site?.bucket,
assetDirectory: "",
excludePatterns: config.legacy?.site?.exclude ?? [],
includePatterns: config.legacy?.site?.include ?? []
} : void 0,
format: bundle.entry.format,
// TODO: Remove this passthrough
bindings,
compatibilityDate: config.compatibilityDate,
compatibilityFlags: config.compatibilityFlags,
routes,
host: config.dev.origin?.hostname,
sendMetrics: config.sendMetrics,
configPath: config.config,
bundleId: id,
minimal_mode: config.dev.remote === "minimal"
});
if (id !== this.#currentBundleId || !token) {
return;
}
const accessToken = await getAccessToken(token.host);
this.emitReloadCompleteEvent({
type: "reloadComplete",
bundle,
config,
proxyData: {
userWorkerUrl: {
protocol: "https:",
hostname: token.host,
port: "443"
},
userWorkerInspectorUrl: {
protocol: token.inspectorUrl.protocol,
hostname: token.inspectorUrl.hostname,
port: token.inspectorUrl.port.toString(),
pathname: token.inspectorUrl.pathname
},
headers: {
"cf-workers-preview-token": token.value,
...accessToken ? { Cookie: `CF_Authorization=${accessToken}` } : {},
// Make sure we don't pass on CF-Connecting-IP to the remote edgeworker instance
// Without this line, remote previews will fail with `DNS points to prohibited IP`
"cf-connecting-ip": ""
},
liveReload: config.dev.liveReload,
proxyLogsToController: true
}
});
} catch (error2) {
if (error2 instanceof Error && error2.name == "AbortError") {
return;
}
this.emitErrorEvent({
type: "error",
reason: "Error reloading remote server",
cause: castErrorCause(error2),
source: "RemoteRuntimeController",
data: void 0
});
}
}
// ******************
// Event Handlers
// ******************
onBundleStart(_4) {
this.#abortController.abort();
this.#abortController = new AbortController();
}
onBundleComplete(ev) {
const id = ++this.#currentBundleId;
if (!ev.config.dev?.remote) {
void this.#mutex.runWith(() => this.teardown());
return;
}
this.emitReloadStartEvent({
type: "reloadStart",
config: ev.config,
bundle: ev.bundle
});
void this.#mutex.runWith(() => this.#onBundleComplete(ev, id));
}
onPreviewTokenExpired(_4) {
notImplemented(this.onPreviewTokenExpired.name, this.constructor.name);
}
async teardown() {
if (this.#session) {
logger.log(source_default.dim("\u2394 Shutting down remote preview..."));
}
logger.debug("RemoteRuntimeController teardown beginning...");
this.#session = void 0;
this.#abortController.abort();
logger.debug("RemoteRuntimeController teardown complete");
}
// *********************
// Event Dispatchers
// *********************
emitReloadStartEvent(data) {
this.emit("reloadStart", data);
}
emitReloadCompleteEvent(data) {
this.emit("reloadComplete", data);
}
};
}
});
// src/api/startDevWorker/DevEnv.ts
function createWorkerObject(devEnv) {
return {
get ready() {
return devEnv.proxy.ready.promise.then(() => void 0);
},
get url() {
return devEnv.proxy.ready.promise.then((ev) => ev.url);
},
get inspectorUrl() {
return devEnv.proxy.ready.promise.then((ev) => ev.inspectorUrl);
},
get config() {
(0, import_node_assert31.default)(devEnv.config.latestConfig);
return devEnv.config.latestConfig;
},
async setConfig(config, throwErrors) {
return devEnv.config.set(config, throwErrors);
},
patchConfig(config) {
return devEnv.config.patch(config);
},
async fetch(...args) {
const { proxyWorker } = await devEnv.proxy.ready.promise;
await devEnv.proxy.runtimeMessageMutex.drained();
return proxyWorker.dispatchFetch(...args);
},
async queue(...args) {
(0, import_node_assert31.default)(
this.config.name,
"Worker name must be defined to use `Worker.queue()`"
);
const { proxyWorker } = await devEnv.proxy.ready.promise;
const w6 = await proxyWorker.getWorker(this.config.name);
return w6.queue(...args);
},
async scheduled(...args) {
(0, import_node_assert31.default)(
this.config.name,
"Worker name must be defined to use `Worker.scheduled()`"
);
const { proxyWorker } = await devEnv.proxy.ready.promise;
const w6 = await proxyWorker.getWorker(this.config.name);
return w6.scheduled(...args);
},
async dispose() {
await devEnv.proxy.ready.promise.finally(() => devEnv.teardown());
},
raw: devEnv
};
}
var import_node_assert31, import_node_events5, DevEnv;
var init_DevEnv = __esm({
"src/api/startDevWorker/DevEnv.ts"() {
init_import_meta_url();
import_node_assert31 = __toESM(require("assert"));
import_node_events5 = require("events");
init_logger();
init_parse();
init_BundlerController();
init_ConfigController();
init_LocalRuntimeController();
init_ProxyController();
init_RemoteRuntimeController();
DevEnv = class extends import_node_events5.EventEmitter {
static {
__name(this, "DevEnv");
}
config;
bundler;
runtimes;
proxy;
async startWorker(options) {
const worker = createWorkerObject(this);
try {
await this.config.set(options, true);
} catch (e7) {
const error2 = new Error("An error occurred when starting the server", {
cause: e7
});
this.proxy.ready.reject(error2);
await worker.dispose();
throw e7;
}
return worker;
}
constructor({
config = new ConfigController(),
bundler = new BundlerController(),
runtimes = [
new LocalRuntimeController(),
new RemoteRuntimeController()
],
proxy: proxy2 = new ProxyController()
} = {}) {
super();
this.config = config;
this.bundler = bundler;
this.runtimes = runtimes;
this.proxy = proxy2;
const controllers = [config, bundler, ...runtimes, proxy2];
controllers.forEach((controller) => {
controller.on("error", (event) => this.emitErrorEvent(event));
});
this.on("error", (event) => {
logger.debug(`Error in ${event.source}: ${event.reason}
`, event.cause);
logger.debug("=> Error contextual data:", event.data);
});
config.on("configUpdate", (event) => {
bundler.onConfigUpdate(event);
proxy2.onConfigUpdate(event);
});
bundler.on("bundleStart", (event) => {
proxy2.onBundleStart(event);
runtimes.forEach((runtime) => {
runtime.onBundleStart(event);
});
});
bundler.on("bundleComplete", (event) => {
runtimes.forEach((runtime) => {
runtime.onBundleComplete(event);
});
});
runtimes.forEach((runtime) => {
runtime.on("reloadStart", (event) => {
proxy2.onReloadStart(event);
});
runtime.on("reloadComplete", (event) => {
proxy2.onReloadComplete(event);
});
runtime.on("devRegistryUpdate", (event) => {
config.onDevRegistryUpdate(event);
});
});
proxy2.on("previewTokenExpired", (event) => {
runtimes.forEach((runtime) => {
runtime.onPreviewTokenExpired(event);
});
});
}
// *********************
// Event Dispatchers
// *********************
async teardown() {
await runWithLogLevel(this.config.latestInput?.dev?.logLevel, async () => {
logger.debug("DevEnv teardown beginning...");
await Promise.all([
this.config.teardown(),
this.bundler.teardown(),
...this.runtimes.map((runtime) => runtime.teardown()),
this.proxy.teardown()
]);
this.config.removeAllListeners();
this.bundler.removeAllListeners();
this.runtimes.forEach((runtime) => runtime.removeAllListeners());
this.proxy.removeAllListeners();
this.emit("teardown");
logger.debug("DevEnv teardown complete");
});
}
emitErrorEvent(ev) {
if (ev.source === "ProxyController" && (ev.reason.startsWith("Failed to send message to") || ev.reason.startsWith("Could not connect to InspectorProxyWorker"))) {
logger.debug(`Error in ${ev.source}: ${ev.reason}
`, ev.cause);
logger.debug("=> Error contextual data:", ev.data);
} else if (ev.source === "ConfigController" && ev.cause instanceof ParseError) {
logger.log(formatMessage(ev.cause));
} else {
this.emit("error", ev);
}
}
};
__name(createWorkerObject, "createWorkerObject");
}
});
// src/api/startDevWorker/types.ts
var init_types14 = __esm({
"src/api/startDevWorker/types.ts"() {
init_import_meta_url();
}
});
// src/api/startDevWorker/index.ts
async function startWorker(options) {
const devEnv = new DevEnv();
return devEnv.startWorker(options);
}
var init_startDevWorker = __esm({
"src/api/startDevWorker/index.ts"() {
init_import_meta_url();
init_DevEnv();
init_utils2();
init_types14();
init_events();
__name(startWorker, "startWorker");
}
});
// src/api/remoteBindings/index.ts
var remoteBindings_exports = {};
__export(remoteBindings_exports, {
maybeStartOrUpdateRemoteProxySession: () => maybeStartOrUpdateRemoteProxySession,
pickRemoteBindings: () => pickRemoteBindings,
startRemoteProxySession: () => startRemoteProxySession
});
async function startRemoteProxySession(bindings, options) {
const rawBindings = Object.fromEntries(
Object.entries(bindings ?? {}).map(([key, binding]) => [
key,
{ ...binding, raw: true }
])
);
const proxyServerWorkerWranglerConfig = import_node_path65.default.resolve(
getBasePath(),
"templates/remoteBindings/wrangler.jsonc"
);
const worker = await startWorker({
name: options?.workerName,
entrypoint: ProxyServerWorker_default,
config: proxyServerWorkerWranglerConfig,
compatibilityDate: "2025-04-28",
dev: {
remote: "minimal",
auth: options?.auth,
server: {
port: await getPorts()
},
inspector: false,
logLevel: "error"
},
bindings: rawBindings
});
const remoteProxyConnectionString = await worker.url;
const updateBindings = /* @__PURE__ */ __name(async (newBindings) => {
const rawNewBindings = Object.fromEntries(
Object.entries(newBindings ?? {}).map(([key, binding]) => [
key,
{ ...binding, raw: true }
])
);
await worker.patchConfig({ bindings: rawNewBindings });
}, "updateBindings");
return {
ready: worker.ready,
remoteProxyConnectionString,
updateBindings,
dispose: worker.dispose
};
}
function pickRemoteBindings(bindings) {
return Object.fromEntries(
Object.entries(bindings ?? {}).filter(([, binding]) => {
if (binding.type === "ai") {
return true;
}
return "experimental_remote" in binding && binding["experimental_remote"];
})
);
}
async function maybeStartOrUpdateRemoteProxySession(wranglerOrWorkerConfigObject, preExistingRemoteProxySessionData, auth) {
let config;
if ("path" in wranglerOrWorkerConfigObject) {
const wranglerConfigObject = wranglerOrWorkerConfigObject;
config = readConfig({
config: wranglerConfigObject.path,
env: wranglerConfigObject.environment
});
(0, import_node_assert32.default)(config.name);
wranglerOrWorkerConfigObject = {
name: config.name,
complianceRegion: getCloudflareComplianceRegion(config),
bindings: convertConfigBindingsToStartWorkerBindings(config) ?? {}
};
}
const workerConfigObject = wranglerOrWorkerConfigObject;
const remoteBindings = pickRemoteBindings(workerConfigObject.bindings);
const authSameAsBefore = deepStrictEqual2(
auth,
preExistingRemoteProxySessionData?.auth
);
let remoteProxySession = preExistingRemoteProxySessionData?.session;
if (!authSameAsBefore) {
if (preExistingRemoteProxySessionData?.session) {
await preExistingRemoteProxySessionData.session.dispose();
}
remoteProxySession = await startRemoteProxySession(remoteBindings, {
workerName: workerConfigObject.name,
complianceRegion: workerConfigObject.complianceRegion,
auth: getAuthHook(auth, config)
});
} else {
const remoteBindingsAreSameAsBefore = deepStrictEqual2(
remoteBindings,
preExistingRemoteProxySessionData?.remoteBindings
);
if (!remoteBindingsAreSameAsBefore) {
if (!remoteProxySession) {
if (Object.keys(remoteBindings).length > 0) {
remoteProxySession = await startRemoteProxySession(remoteBindings, {
workerName: workerConfigObject.name,
complianceRegion: workerConfigObject.complianceRegion,
auth: getAuthHook(auth, config)
});
}
} else {
await remoteProxySession.updateBindings(remoteBindings);
}
}
}
await remoteProxySession?.ready;
if (!remoteProxySession) {
return null;
}
return {
session: remoteProxySession,
remoteBindings
};
}
function getAuthHook(auth, config) {
if (auth) {
return auth;
}
if (config?.account_id) {
return async () => {
return {
accountId: await requireAuth(config),
apiToken: requireApiToken()
};
};
}
return void 0;
}
function deepStrictEqual2(source, target) {
try {
import_node_assert32.default.deepStrictEqual(source, target);
return true;
} catch {
return false;
}
}
var import_node_assert32, import_node_path65;
var init_remoteBindings = __esm({
"src/api/remoteBindings/index.ts"() {
init_import_meta_url();
import_node_assert32 = __toESM(require("assert"));
import_node_path65 = __toESM(require("path"));
init_get_port();
init_ProxyServerWorker();
init_config2();
init_misc_variables();
init_paths();
init_user2();
init_startDevWorker();
__name(startRemoteProxySession, "startRemoteProxySession");
__name(pickRemoteBindings, "pickRemoteBindings");
__name(maybeStartOrUpdateRemoteProxySession, "maybeStartOrUpdateRemoteProxySession");
__name(getAuthHook, "getAuthHook");
__name(deepStrictEqual2, "deepStrictEqual");
}
});
// src/api/startDevWorker/LocalRuntimeController.ts
async function getBinaryFileContents2(file) {
if ("contents" in file) {
if (file.contents instanceof Buffer) {
return file.contents;
}
return Buffer.from(file.contents);
}
return (0, import_promises36.readFile)(file.path);
}
async function getTextFileContents(file) {
if ("contents" in file) {
if (typeof file.contents === "string") {
return file.contents;
}
if (file.contents instanceof Buffer) {
return file.contents.toString();
}
return Buffer.from(file.contents).toString();
}
return (0, import_promises36.readFile)(file.path, "utf8");
}
function getName2(config) {
return config.name;
}
async function convertToConfigBundle(event) {
const { bindings, fetchers } = await convertBindingsToCfWorkerInitBindings(
event.config.bindings
);
const crons = [];
const queueConsumers = [];
for (const trigger of event.config.triggers ?? []) {
if (trigger.type === "cron") {
crons.push(trigger.cron);
} else if (trigger.type === "queue-consumer") {
queueConsumers.push(trigger);
}
}
if (event.bundle.entry.format === "service-worker") {
for (const module3 of event.bundle.modules ?? []) {
const identifier = getIdentifier(module3.name);
if (module3.type === "text") {
bindings.vars ??= {};
bindings.vars[identifier] = await getTextFileContents({
contents: module3.content
});
} else if (module3.type === "buffer") {
bindings.data_blobs ??= {};
bindings.data_blobs[identifier] = await getBinaryFileContents2({
contents: module3.content
});
} else if (module3.type === "compiled-wasm") {
bindings.wasm_modules ??= {};
bindings.wasm_modules[identifier] = await getBinaryFileContents2({
contents: module3.content
});
}
}
event.bundle = { ...event.bundle, modules: [] };
}
return {
name: event.config.name,
bundle: event.bundle,
format: event.bundle.entry.format,
compatibilityDate: event.config.compatibilityDate,
compatibilityFlags: event.config.compatibilityFlags,
complianceRegion: event.config.complianceRegion,
bindings,
migrations: event.config.migrations,
devRegistry: event.config.dev.registry,
legacyAssetPaths: event.config.legacy?.site?.bucket ? {
baseDirectory: event.config.legacy?.site?.bucket,
assetDirectory: "",
excludePatterns: event.config.legacy?.site?.exclude ?? [],
includePatterns: event.config.legacy?.site?.include ?? []
} : void 0,
assets: event.config?.assets,
initialPort: void 0,
initialIp: "127.0.0.1",
rules: [],
...event.config.dev.inspector === false ? {
inspect: false,
inspectorPort: void 0
} : {
inspect: true,
inspectorPort: 0
},
localPersistencePath: event.config.dev.persist,
liveReload: event.config.dev?.liveReload ?? false,
crons,
queueConsumers,
localProtocol: event.config.dev?.server?.secure ? "https" : "http",
httpsCertPath: event.config.dev?.server?.httpsCertPath,
httpsKeyPath: event.config.dev?.server?.httpsKeyPath,
localUpstream: event.config.dev?.origin?.hostname,
upstreamProtocol: event.config.dev?.origin?.secure ? "https" : "http",
services: bindings.services,
serviceBindings: fetchers,
bindVectorizeToProd: event.config.dev?.bindVectorizeToProd ?? false,
imagesLocalMode: event.config.dev?.imagesLocalMode ?? false,
testScheduled: !!event.config.dev.testScheduled,
tails: event.config.tailConsumers,
containerDOClassNames: new Set(
event.config.containers?.map((c6) => c6.class_name)
),
containerBuildId: event.config.dev?.containerBuildId,
containerEngine: event.config.dev.containerEngine,
enableContainers: event.config.dev.enableContainers ?? true
};
}
async function getContainerDevOptions(containersConfig, containerBuildId) {
const containers2 = [];
for (const container of containersConfig) {
if ("image_uri" in container) {
containers2.push({
image_uri: container.image_uri,
class_name: container.class_name,
image_tag: getDevContainerImageName(
container.class_name,
containerBuildId
)
});
} else {
containers2.push({
dockerfile: container.dockerfile,
image_build_context: container.image_build_context,
image_vars: container.image_vars,
class_name: container.class_name,
image_tag: getDevContainerImageName(
container.class_name,
containerBuildId
)
});
}
}
return containers2;
}
var import_node_assert33, import_node_crypto15, import_promises36, import_miniflare27, LocalRuntimeController;
var init_LocalRuntimeController = __esm({
"src/api/startDevWorker/LocalRuntimeController.ts"() {
init_import_meta_url();
import_node_assert33 = __toESM(require("assert"));
import_node_crypto15 = require("crypto");
import_promises36 = require("fs/promises");
init_containers_shared();
init_source();
import_miniflare27 = require("miniflare");
init_miniflare();
init_misc_variables();
init_logger();
init_BaseController();
init_events();
init_utils2();
__name(getBinaryFileContents2, "getBinaryFileContents");
__name(getTextFileContents, "getTextFileContents");
__name(getName2, "getName");
__name(convertToConfigBundle, "convertToConfigBundle");
LocalRuntimeController = class extends RuntimeController {
static {
__name(this, "LocalRuntimeController");
}
// ******************
// Event Handlers
// ******************
#log = buildLog();
#currentBundleId = 0;
// This is given as a shared secret to the Proxy and User workers
// so that the User Worker can trust aspects of HTTP requests from the Proxy Worker
// if it provides the secret in a `MF-Proxy-Shared-Secret` header.
#proxyToUserWorkerAuthenticationSecret = (0, import_node_crypto15.randomUUID)();
// `buildMiniflareOptions()` is asynchronous, meaning if multiple bundle
// updates were submitted, the second may apply before the first. Therefore,
// wrap updates in a mutex, so they're always applied in invocation order.
#mutex = new import_miniflare27.Mutex();
#mf;
#remoteProxySessionData = null;
// Set of container images that have been seen in the current dev session.
// This is used to clean up containers at the end of the dev session.
containerImageTagsSeen = /* @__PURE__ */ new Set();
// Stored here, so it can be used in `cleanupContainers()`
dockerPath;
// If this doesn't match what is in config, trigger a rebuild.
// Used for the rebuild hotkey
#currentContainerBuildId;
// Used to store the information and abort handle for the
// current container that is being built
containerBeingBuilt;
onBundleStart(_4) {
process.on("exit", () => {
this.cleanupContainers();
});
}
async #onBundleComplete(data, id) {
try {
const configBundle = await convertToConfigBundle(data);
const experimentalRemoteBindings = data.config.dev.experimentalRemoteBindings ?? false;
if (experimentalRemoteBindings && !data.config.dev?.remote) {
const { maybeStartOrUpdateRemoteProxySession: maybeStartOrUpdateRemoteProxySession2, pickRemoteBindings: pickRemoteBindings2 } = await Promise.resolve().then(() => (init_remoteBindings(), remoteBindings_exports));
const remoteBindings = pickRemoteBindings2(
convertCfWorkerInitBindingsToBindings(configBundle.bindings) ?? {}
);
const auth = Object.keys(remoteBindings).length === 0 ? (
// If there are no remote bindings (this is a local only session) there's no need to get auth data
void 0
) : await unwrapHook(data.config.dev.auth);
this.#remoteProxySessionData = await maybeStartOrUpdateRemoteProxySession2(
{
name: configBundle.name,
complianceRegion: configBundle.complianceRegion,
bindings: remoteBindings
},
this.#remoteProxySessionData ?? null,
auth
);
}
if (data.config.containers?.length && data.config.dev.enableContainers && this.#currentContainerBuildId !== data.config.dev.containerBuildId) {
this.dockerPath = data.config.dev?.dockerPath ?? getDockerPath();
(0, import_node_assert33.default)(
data.config.dev.containerBuildId,
"Build ID should be set if containers are enabled and defined"
);
const containerDevOptions = await getContainerDevOptions(
data.config.containers,
data.config.dev.containerBuildId
);
for (const container of containerDevOptions) {
if (this.#currentContainerBuildId !== void 0) {
runDockerCmdWithOutput(this.dockerPath, [
"rmi",
getDevContainerImageName(
container.class_name,
this.#currentContainerBuildId
)
]);
}
this.containerImageTagsSeen.add(container.image_tag);
}
logger.log(source_default.dim("\u2394 Preparing container image(s)..."));
await prepareContainerImagesForDev({
dockerPath: this.dockerPath,
containerOptions: containerDevOptions,
onContainerImagePreparationStart: /* @__PURE__ */ __name((buildStartEvent) => {
this.containerBeingBuilt = {
...buildStartEvent,
abortRequested: false
};
}, "onContainerImagePreparationStart"),
onContainerImagePreparationEnd: /* @__PURE__ */ __name(() => {
this.containerBeingBuilt = void 0;
}, "onContainerImagePreparationEnd")
});
if (this.containerBeingBuilt) {
this.containerBeingBuilt.abortRequested = false;
}
this.#currentContainerBuildId = data.config.dev.containerBuildId;
logger.log(source_default.dim("\u2394 Container image(s) ready"));
}
const options = await buildMiniflareOptions(
this.#log,
configBundle,
this.#proxyToUserWorkerAuthenticationSecret,
this.#remoteProxySessionData?.session?.remoteProxyConnectionString,
!!experimentalRemoteBindings,
(registry) => {
logger.log(source_default.dim("\u2394 Connection status updated"));
this.emitDevRegistryUpdateEvent({
type: "devRegistryUpdate",
registry
});
}
);
options.liveReload = false;
if (this.#mf === void 0) {
logger.log(source_default.dim("\u2394 Starting local server..."));
this.#mf = new import_miniflare27.Miniflare(options);
} else {
logger.log(source_default.dim("\u2394 Reloading local server..."));
await this.#mf.setOptions(options);
}
const userWorkerUrl = await this.#mf.ready;
const userWorkerInspectorUrl = options.inspectorPort === void 0 ? void 0 : await this.#mf.getInspectorURL();
if (id !== this.#currentBundleId) {
return;
}
this.emitReloadCompleteEvent({
type: "reloadComplete",
config: data.config,
bundle: data.bundle,
proxyData: {
userWorkerUrl: {
protocol: userWorkerUrl.protocol,
hostname: userWorkerUrl.hostname,
port: userWorkerUrl.port
},
...userWorkerInspectorUrl ? {
userWorkerInspectorUrl: {
protocol: userWorkerInspectorUrl.protocol,
hostname: userWorkerInspectorUrl.hostname,
port: userWorkerInspectorUrl.port,
pathname: `/core:user:${getName2(data.config)}`
}
} : {},
userWorkerInnerUrlOverrides: {
protocol: data.config?.dev?.origin?.secure ? "https:" : "http:",
hostname: data.config?.dev?.origin?.hostname,
port: data.config?.dev?.origin?.hostname ? "" : void 0
},
headers: {
// Passing this signature from Proxy Worker allows the User Worker to trust the request.
"MF-Proxy-Shared-Secret": this.#proxyToUserWorkerAuthenticationSecret
},
liveReload: data.config.dev?.liveReload,
proxyLogsToController: data.bundle.entry.format === "service-worker"
}
});
} catch (error2) {
if (this.containerBeingBuilt?.abortRequested && error2 instanceof Error && error2.message === "Build exited with code: 1") {
return;
}
this.emitErrorEvent({
type: "error",
reason: "Error reloading local server",
cause: castErrorCause(error2),
source: "LocalRuntimeController",
data: void 0
});
}
}
onBundleComplete(data) {
const id = ++this.#currentBundleId;
if (data.config.dev?.remote) {
void this.teardown();
return;
}
this.emitReloadStartEvent({
type: "reloadStart",
config: data.config,
bundle: data.bundle
});
void this.#mutex.runWith(() => this.#onBundleComplete(data, id));
}
onPreviewTokenExpired(_4) {
}
cleanupContainers = /* @__PURE__ */ __name(() => {
if (!this.containerImageTagsSeen.size) {
return;
}
(0, import_node_assert33.default)(
this.dockerPath,
"Docker path should have been set if containers are enabled"
);
cleanupContainers(this.dockerPath, this.containerImageTagsSeen);
}, "cleanupContainers");
#teardown = /* @__PURE__ */ __name(async () => {
logger.debug("LocalRuntimeController teardown beginning...");
if (this.#mf) {
logger.log(source_default.dim("\u2394 Shutting down local server..."));
}
await this.#mf?.dispose();
this.#mf = void 0;
if (this.#remoteProxySessionData) {
logger.log(source_default.dim("\u2394 Shutting down remote connection..."));
}
await this.#remoteProxySessionData?.session?.dispose();
this.#remoteProxySessionData = null;
logger.debug("LocalRuntimeController teardown complete");
}, "#teardown");
async teardown() {
return this.#mutex.runWith(this.#teardown);
}
// *********************
// Event Dispatchers
// *********************
emitReloadStartEvent(data) {
this.emit("reloadStart", data);
}
emitReloadCompleteEvent(data) {
this.emit("reloadComplete", data);
}
emitDevRegistryUpdateEvent(data) {
this.emit("devRegistryUpdate", data);
}
};
__name(getContainerDevOptions, "getContainerDevOptions");
}
});
// src/api/startDevWorker/MultiworkerRuntimeController.ts
function ensureMatchingSql(options) {
const sameWorkerDOSqlEnabled = /* @__PURE__ */ new Map();
for (const worker of options.workers) {
for (const designator of Object.values(worker.durableObjects ?? {})) {
const isObject3 = typeof designator === "object";
const className = isObject3 ? designator.className : designator;
const enableSql = isObject3 ? designator.useSQLite : void 0;
if (!isObject3 || designator.scriptName === void 0) {
sameWorkerDOSqlEnabled.set(className, enableSql);
}
}
}
for (const worker of options.workers) {
for (const designator of Object.values(worker.durableObjects ?? {})) {
const isObject3 = typeof designator === "object";
if (isObject3 && designator.scriptName !== void 0) {
designator.useSQLite = sameWorkerDOSqlEnabled.get(designator.className);
}
}
}
return options;
}
var import_node_assert34, import_node_crypto16, import_miniflare28, MultiworkerRuntimeController;
var init_MultiworkerRuntimeController = __esm({
"src/api/startDevWorker/MultiworkerRuntimeController.ts"() {
init_import_meta_url();
import_node_assert34 = __toESM(require("assert"));
import_node_crypto16 = require("crypto");
init_containers_shared();
init_source();
import_miniflare28 = require("miniflare");
init_miniflare();
init_misc_variables();
init_logger();
init_events();
init_LocalRuntimeController();
init_utils2();
__name(ensureMatchingSql, "ensureMatchingSql");
MultiworkerRuntimeController = class extends LocalRuntimeController {
constructor(numWorkers) {
super();
this.numWorkers = numWorkers;
}
static {
__name(this, "MultiworkerRuntimeController");
}
// ******************
// Event Handlers
// ******************
#log = buildLog();
#currentBundleId = 0;
// This is given as a shared secret to the Proxy and User workers
// so that the User Worker can trust aspects of HTTP requests from the Proxy Worker
// if it provides the secret in a `MF-Proxy-Shared-Secret` header.
#proxyToUserWorkerAuthenticationSecret = (0, import_node_crypto16.randomUUID)();
// `buildMiniflareOptions()` is asynchronous, meaning if multiple bundle
// updates were submitted, the second may apply before the first. Therefore,
// wrap updates in a mutex, so they're always applied in invocation order.
#mutex = new import_miniflare28.Mutex();
#mf;
#options = /* @__PURE__ */ new Map();
#remoteProxySessionsData = /* @__PURE__ */ new Map();
// If this doesn't match what is in config, trigger a rebuild.
// Used for the rebuild hotkey
#currentContainerBuildId;
#canStartMiniflare() {
return [...this.#options.values()].some((o5) => o5.primary) && [...this.#options.values()].length === this.numWorkers;
}
#mergedMfOptions() {
const primary = [...this.#options.values()].find((o5) => o5.primary);
(0, import_node_assert34.default)(primary !== void 0);
const secondary = [...this.#options.values()].filter((o5) => !o5.primary);
return {
...primary.options,
workers: [
...primary.options.workers,
...secondary.flatMap(
(o5) => o5.options.workers.map((w6) => {
delete w6.ratelimits;
return w6;
})
)
]
};
}
async #onBundleComplete(data, id) {
try {
const configBundle = await convertToConfigBundle(data);
const experimentalRemoteBindings = data.config.dev.experimentalRemoteBindings;
if (experimentalRemoteBindings && !data.config.dev?.remote) {
const { maybeStartOrUpdateRemoteProxySession: maybeStartOrUpdateRemoteProxySession2 } = await Promise.resolve().then(() => (init_remoteBindings(), remoteBindings_exports));
const remoteProxySession = await maybeStartOrUpdateRemoteProxySession2(
{
name: configBundle.name,
complianceRegion: configBundle.complianceRegion,
bindings: convertCfWorkerInitBindingsToBindings(configBundle.bindings) ?? {}
},
this.#remoteProxySessionsData.get(data.config.name) ?? null
);
this.#remoteProxySessionsData.set(
data.config.name,
remoteProxySession ?? null
);
}
if (data.config.containers?.length && this.#currentContainerBuildId !== data.config.dev.containerBuildId) {
logger.log(source_default.dim("\u2394 Preparing container image(s)..."));
(0, import_node_assert34.default)(
data.config.dev.containerBuildId,
"Build ID should be set if containers are enabled and defined"
);
const containerOptions = await getContainerDevOptions(
data.config.containers,
data.config.dev.containerBuildId
);
this.dockerPath = data.config.dev?.dockerPath ?? getDockerPath();
for (const container of containerOptions ?? []) {
this.containerImageTagsSeen.add(container.image_tag);
}
await prepareContainerImagesForDev({
dockerPath: this.dockerPath,
containerOptions,
onContainerImagePreparationStart: /* @__PURE__ */ __name((buildStartEvent) => {
this.containerBeingBuilt = {
...buildStartEvent,
abortRequested: false
};
}, "onContainerImagePreparationStart"),
onContainerImagePreparationEnd: /* @__PURE__ */ __name(() => {
this.containerBeingBuilt = void 0;
}, "onContainerImagePreparationEnd")
});
if (this.containerBeingBuilt) {
this.containerBeingBuilt.abortRequested = false;
}
this.#currentContainerBuildId = data.config.dev.containerBuildId;
logger.log(source_default.dim("\u2394 Container image(s) ready"));
}
const options = await buildMiniflareOptions(
this.#log,
await convertToConfigBundle(data),
this.#proxyToUserWorkerAuthenticationSecret,
this.#remoteProxySessionsData.get(data.config.name)?.session?.remoteProxyConnectionString,
!!experimentalRemoteBindings,
(registry) => {
this.emitDevRegistryUpdateEvent({
type: "devRegistryUpdate",
registry
});
}
);
this.#options.set(data.config.name, {
options,
primary: Boolean(data.config.dev.multiworkerPrimary)
});
if (this.#canStartMiniflare()) {
const mergedMfOptions = ensureMatchingSql(this.#mergedMfOptions());
if (this.#mf === void 0) {
logger.log(source_default.dim("\u2394 Starting local server..."));
this.#mf = new import_miniflare28.Miniflare(mergedMfOptions);
} else {
logger.log(source_default.dim("\u2394 Reloading local server..."));
await this.#mf.setOptions(mergedMfOptions);
}
const userWorkerUrl = await this.#mf.ready;
const userWorkerInspectorUrl = await this.#mf.getInspectorURL();
if (id !== this.#currentBundleId) {
return;
}
this.emitReloadCompleteEvent({
type: "reloadComplete",
config: data.config,
bundle: data.bundle,
proxyData: {
userWorkerUrl: {
protocol: userWorkerUrl.protocol,
hostname: userWorkerUrl.hostname,
port: userWorkerUrl.port
},
userWorkerInspectorUrl: {
protocol: userWorkerInspectorUrl.protocol,
hostname: userWorkerInspectorUrl.hostname,
port: userWorkerInspectorUrl.port,
pathname: `/core:user:${data.config.name}`
},
userWorkerInnerUrlOverrides: {
protocol: data.config?.dev?.origin?.secure ? "https:" : "http:",
hostname: data.config?.dev?.origin?.hostname,
port: data.config?.dev?.origin?.hostname ? "" : void 0
},
headers: {
// Passing this signature from Proxy Worker allows the User Worker to trust the request.
"MF-Proxy-Shared-Secret": this.#proxyToUserWorkerAuthenticationSecret
},
liveReload: data.config.dev?.liveReload,
proxyLogsToController: data.bundle.entry.format === "service-worker"
}
});
}
} catch (error2) {
this.emitErrorEvent({
type: "error",
reason: "Error reloading local server",
cause: castErrorCause(error2),
source: "MultiworkerRuntimeController",
data: void 0
});
}
}
onBundleComplete(data) {
const id = ++this.#currentBundleId;
if (data.config.dev?.remote) {
this.emitErrorEvent({
type: "error",
reason: "--remote workers not supported with the multiworker runtime",
cause: new Error(
"--remote workers not supported with the multiworker runtime"
),
source: "MultiworkerRuntimeController",
data: void 0
});
return;
}
this.emitReloadStartEvent({
type: "reloadStart",
config: data.config,
bundle: data.bundle
});
void this.#mutex.runWith(() => this.#onBundleComplete(data, id));
}
#teardown = /* @__PURE__ */ __name(async () => {
logger.debug("MultiworkerRuntimeController teardown beginning...");
if (this.#mf) {
logger.log(source_default.dim("\u2394 Shutting down local server..."));
}
await this.#mf?.dispose();
this.#mf = void 0;
if (this.#remoteProxySessionsData.size > 0) {
logger.log(source_default.dim("\u2394 Shutting down remote connections..."));
}
await Promise.all(
[...this.#remoteProxySessionsData.values()].map(
(remoteProxySessionData) => remoteProxySessionData?.session?.dispose()
)
);
this.#remoteProxySessionsData.clear();
logger.debug("MultiworkerRuntimeController teardown complete");
}, "#teardown");
async teardown() {
return this.#mutex.runWith(this.#teardown);
}
};
}
});
// src/api/startDevWorker/NoOpProxyController.ts
var NoOpProxyController;
var init_NoOpProxyController = __esm({
"src/api/startDevWorker/NoOpProxyController.ts"() {
init_import_meta_url();
init_ProxyController();
NoOpProxyController = class extends ProxyController {
static {
__name(this, "NoOpProxyController");
}
onConfigUpdate(_data5) {
}
onBundleStart(_data5) {
}
onReloadStart(_data5) {
}
onReloadComplete(_data5) {
}
async teardown() {
}
};
}
});
// src/utils/onKeyPress.ts
function onKeyPress(callback) {
const stream2 = new import_stream16.PassThrough();
process.stdin.pipe(stream2);
if (isInteractive2()) {
import_node_readline5.default.emitKeypressEvents(stream2);
process.stdin.setRawMode(true);
}
const handler = /* @__PURE__ */ __name(async (_char, key) => {
if (key) {
callback(key);
}
}, "handler");
stream2.on("keypress", handler);
return () => {
if (isInteractive2()) {
process.stdin.setRawMode(false);
}
stream2.off("keypress", handler);
stream2.destroy();
};
}
var import_node_readline5, import_stream16;
var init_onKeyPress = __esm({
"src/utils/onKeyPress.ts"() {
init_import_meta_url();
import_node_readline5 = __toESM(require("readline"));
import_stream16 = require("stream");
init_is_interactive();
__name(onKeyPress, "onKeyPress");
}
});
// src/cli-hotkeys.ts
function cli_hotkeys_default(options) {
function formatInstructions() {
const instructions = options.filter(
(option) => !unwrapHook(option.disabled) && option.label !== void 0
).map(({ keys, label }) => `[${keys[0]}] ${dim(unwrapHook(label))}`);
let stringifiedInstructions = instructions.join(" ");
const length = stripAnsi2(stringifiedInstructions).length;
const ADDITIONAL_CHARS = 6;
const willWrap = length + ADDITIONAL_CHARS > process.stdout.columns;
if (willWrap) {
stringifiedInstructions = instructions.join("\n");
}
const maxLineLength = Math.max(
...stringifiedInstructions.split("\n").map((line) => stripAnsi2(line).length)
);
stringifiedInstructions = stringifiedInstructions.split("\n").map(
(line) => `\u2502 ${line + " ".repeat(Math.max(0, maxLineLength - stripAnsi2(line).length))} \u2502`
).join("\n");
return `\u256D\u2500\u2500${"\u2500".repeat(maxLineLength)}\u2500\u2500\u256E
` + stringifiedInstructions + `
\u2570\u2500\u2500${"\u2500".repeat(maxLineLength)}\u2500\u2500\u256F`;
}
__name(formatInstructions, "formatInstructions");
const unregisterKeyPress = onKeyPress(async (key) => {
const entries = [];
if (key.name) {
entries.push(key.name.toLowerCase());
}
if (key.meta) {
entries.unshift("meta");
}
if (key.ctrl) {
entries.unshift("ctrl");
}
if (key.shift) {
entries.unshift("shift");
}
const char = entries.join("+");
for (const { keys, handler, disabled } of options) {
if (unwrapHook(disabled)) {
continue;
}
if (keys.includes(char)) {
try {
await handler();
} catch {
logger.error(`Error while handling hotkey [${char}]`);
}
}
}
});
function printInstructions() {
const bottomFloat = formatInstructions();
if (bottomFloat) {
console.log(bottomFloat);
}
}
__name(printInstructions, "printInstructions");
printInstructions();
return () => {
unregisterKeyPress();
};
}
var init_cli_hotkeys = __esm({
"src/cli-hotkeys.ts"() {
init_import_meta_url();
init_colors();
init_strip_ansi();
init_utils2();
init_logger();
init_onKeyPress();
__name(cli_hotkeys_default, "default");
}
});
// src/dev/hotkeys.ts
function registerDevHotKeys(devEnvs, args) {
const primaryDevEnv = devEnvs[0];
const unregisterHotKeys = cli_hotkeys_default([
{
keys: ["b"],
label: "open a browser",
handler: /* @__PURE__ */ __name(async () => {
const { url: url4 } = await primaryDevEnv.proxy.ready.promise;
await openInBrowser(url4.href);
}, "handler")
},
{
keys: ["d"],
label: "open devtools",
// Don't display this hotkey if we're in a VSCode debug session
disabled: !!process.env.VSCODE_INSPECTOR_OPTIONS,
handler: /* @__PURE__ */ __name(async () => {
const { inspectorUrl } = await primaryDevEnv.proxy.ready.promise;
if (!inspectorUrl) {
logger.warn("DevTools is not available while in a debug terminal");
} else {
await openInspector(
parseInt(inspectorUrl.port),
primaryDevEnv.config.latestConfig?.name
);
}
}, "handler")
},
{
keys: ["r"],
label: "rebuild container(s)",
disabled: /* @__PURE__ */ __name(() => {
return devEnvs.every(
(devEnv) => !devEnv.config.latestConfig?.dev?.enableContainers || !devEnv.config.latestConfig?.containers?.length
);
}, "disabled"),
handler: debounce(async () => {
for (const devEnv of devEnvs) {
devEnv.runtimes.forEach((runtime) => {
if (runtime instanceof LocalRuntimeController) {
if (runtime.containerBeingBuilt) {
runtime.containerBeingBuilt.abort();
runtime.containerBeingBuilt.abortRequested = true;
}
}
});
devEnv.runtimes.map((runtime) => {
if (runtime instanceof LocalRuntimeController) {
runtime.cleanupContainers();
}
});
const newContainerBuildId = generateContainerBuildId();
await devEnv.config.patch({
dev: {
...devEnv.config.latestConfig?.dev,
containerBuildId: newContainerBuildId
}
});
}
}, 250)
},
{
keys: ["l"],
disabled: /* @__PURE__ */ __name(() => args.forceLocal ?? false, "disabled"),
handler: /* @__PURE__ */ __name(async () => {
await primaryDevEnv.config.patch({
dev: {
...primaryDevEnv.config.latestConfig?.dev,
remote: !primaryDevEnv.config.latestConfig?.dev?.remote
}
});
}, "handler")
},
{
keys: ["c"],
label: "clear console",
handler: /* @__PURE__ */ __name(async () => {
const someContainerIsBeingBuilt = primaryDevEnv.runtimes.some(
(runtime) => runtime instanceof LocalRuntimeController && runtime.containerBeingBuilt
);
if (!someContainerIsBeingBuilt) {
logger.console("clear");
}
}, "handler")
},
{
keys: ["x", "q", "ctrl+c"],
label: "to exit",
handler: /* @__PURE__ */ __name(async () => {
primaryDevEnv.runtimes.forEach((runtime) => {
if (runtime instanceof LocalRuntimeController) {
if (runtime.containerBeingBuilt) {
runtime.containerBeingBuilt.abort();
runtime.containerBeingBuilt.abortRequested = true;
}
}
});
await primaryDevEnv.teardown();
}, "handler")
}
]);
return unregisterHotKeys;
}
var init_hotkeys = __esm({
"src/dev/hotkeys.ts"() {
init_import_meta_url();
init_containers_shared();
init_LocalRuntimeController();
init_cli_hotkeys();
init_logger();
init_open_in_browser();
init_debounce();
init_inspect2();
__name(registerDevHotKeys, "registerDevHotKeys");
}
});
// src/utils/mergeWithOverride.ts
function mergeWithOverride(source, override, keyProperty) {
const sourceMap = /* @__PURE__ */ new Map();
source.forEach((el) => sourceMap.set(el[keyProperty], el));
override.forEach((el) => sourceMap.set(el[keyProperty], el));
return Array.from(sourceMap.values());
}
var init_mergeWithOverride = __esm({
"src/utils/mergeWithOverride.ts"() {
init_import_meta_url();
__name(mergeWithOverride, "mergeWithOverride");
}
});
// ../workers-shared/utils/configuration/constructConfiguration.ts
function constructRedirects({
redirects,
redirectsFile,
logger: logger4
}) {
if (!redirects) {
return {};
}
const num_valid = redirects.rules.length;
const num_invalid = redirects.invalid.length;
const redirectsRelativePath = redirectsFile ? (0, import_node_path66.relative)(process.cwd(), redirectsFile) : "";
logger4.log(
`\u2728 Parsed ${num_valid} valid redirect rule${num_valid === 1 ? "" : "s"}.`
);
if (num_invalid > 0) {
let invalidRedirectRulesList = ``;
for (const { line, lineNumber, message } of redirects.invalid) {
invalidRedirectRulesList += `\u25B6\uFE0E ${message}
`;
if (line) {
invalidRedirectRulesList += ` at ${redirectsRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}
`;
}
}
logger4.warn(
`Found ${num_invalid} invalid redirect rule${num_invalid === 1 ? "" : "s"}:
${invalidRedirectRulesList}`
);
}
if (num_valid === 0) {
return {};
}
const staticRedirects = {};
const dynamicRedirects = {};
let canCreateStaticRule = true;
for (const rule of redirects.rules) {
if (!rule.from.match(SPLAT_REGEX) && !rule.from.match(PLACEHOLDER_REGEX)) {
if (canCreateStaticRule) {
staticRedirects[rule.from] = {
status: rule.status,
to: rule.to,
lineNumber: rule.lineNumber
};
continue;
} else {
logger4.info(
`The redirect rule ${rule.from} \u2192 ${rule.status} ${rule.to} could be made more performant by bringing it above any lines with splats or placeholders.`
);
}
}
dynamicRedirects[rule.from] = { status: rule.status, to: rule.to };
canCreateStaticRule = false;
}
return {
redirects: {
version: REDIRECTS_VERSION,
staticRules: staticRedirects,
rules: dynamicRedirects
}
};
}
function constructHeaders({
headers,
headersFile,
logger: logger4
}) {
if (!headers) {
return {};
}
const num_valid = headers.rules.length;
const num_invalid = headers.invalid.length;
const headersRelativePath = headersFile ? (0, import_node_path66.relative)(process.cwd(), headersFile) : "";
logger4.log(
`\u2728 Parsed ${num_valid} valid header rule${num_valid === 1 ? "" : "s"}.`
);
if (num_invalid > 0) {
let invalidHeaderRulesList = ``;
for (const { line, lineNumber, message } of headers.invalid) {
invalidHeaderRulesList += `\u25B6\uFE0E ${message}
`;
if (line) {
invalidHeaderRulesList += ` at ${headersRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}
`;
}
}
logger4.warn(
`Found ${num_invalid} invalid header rule${num_invalid === 1 ? "" : "s"}:
${invalidHeaderRulesList}`
);
}
if (num_valid === 0) {
return {};
}
const rules = {};
for (const rule of headers.rules) {
const configuredRule = {};
if (Object.keys(rule.headers).length) {
configuredRule.set = rule.headers;
}
if (rule.unsetHeaders.length) {
configuredRule.unset = rule.unsetHeaders;
}
rules[rule.path] = configuredRule;
}
return {
headers: {
version: HEADERS_VERSION,
rules
}
};
}
var import_node_path66;
var init_constructConfiguration = __esm({
"../workers-shared/utils/configuration/constructConfiguration.ts"() {
init_import_meta_url();
import_node_path66 = require("path");
init_constants3();
__name(constructRedirects, "constructRedirects");
__name(constructHeaders, "constructHeaders");
}
});
// ../pages-shared/metadata-generator/constants.ts
var ANALYTICS_VERSION;
var init_constants20 = __esm({
"../pages-shared/metadata-generator/constants.ts"() {
init_import_meta_url();
ANALYTICS_VERSION = 1;
}
});
// ../pages-shared/metadata-generator/createMetadataObject.ts
function createMetadataObject({
redirects,
headers,
redirectsFile,
headersFile,
webAnalyticsToken,
deploymentId,
failOpen,
logger: logger4 = noopLogger
}) {
return {
...constructRedirects({ redirects, redirectsFile, logger: logger4 }),
...constructHeaders({ headers, headersFile, logger: logger4 }),
...constructWebAnalytics({ webAnalyticsToken, logger: logger4 }),
deploymentId,
failOpen
};
}
function constructWebAnalytics({
webAnalyticsToken
}) {
if (!webAnalyticsToken) {
return {};
}
return {
analytics: {
version: ANALYTICS_VERSION,
token: webAnalyticsToken
}
};
}
var noopLogger;
var init_createMetadataObject = __esm({
"../pages-shared/metadata-generator/createMetadataObject.ts"() {
init_import_meta_url();
init_constructConfiguration();
init_constants20();
noopLogger = {
debug: /* @__PURE__ */ __name((_message) => {
}, "debug"),
log: /* @__PURE__ */ __name((_message) => {
}, "log"),
info: /* @__PURE__ */ __name((_message) => {
}, "info"),
warn: /* @__PURE__ */ __name((_message) => {
}, "warn"),
error: /* @__PURE__ */ __name((_error) => {
}, "error")
};
__name(createMetadataObject, "createMetadataObject");
__name(constructWebAnalytics, "constructWebAnalytics");
}
});
// ../pages-shared/environment-polyfills/index.ts
var polyfill;
var init_environment_polyfills = __esm({
"../pages-shared/environment-polyfills/index.ts"() {
init_import_meta_url();
polyfill = /* @__PURE__ */ __name((environment) => {
Object.entries(environment).map(([name2, value]) => {
Object.defineProperty(globalThis, name2, {
value,
configurable: true,
enumerable: true,
writable: true
});
});
}, "polyfill");
}
});
// ../../node_modules/.pnpm/html-rewriter-wasm@0.4.1/node_modules/html-rewriter-wasm/dist/html_rewriter.js
var require_html_rewriter = __commonJS({
"../../node_modules/.pnpm/html-rewriter-wasm@0.4.1/node_modules/html-rewriter-wasm/dist/html_rewriter.js"(exports2, module3) {
init_import_meta_url();
var imports = {};
imports["__wbindgen_placeholder__"] = module3.exports;
var wasm;
var { awaitPromise, setWasmExports, wrap: wrap4 } = require(String.raw`./asyncify.js`);
var { TextDecoder: TextDecoder2, TextEncoder: TextEncoder4 } = require(String.raw`util`);
var heap = new Array(32).fill(void 0);
heap.push(void 0, null, true, false);
function getObject(idx) {
return heap[idx];
}
__name(getObject, "getObject");
var heap_next = heap.length;
function dropObject(idx) {
if (idx < 36) return;
heap[idx] = heap_next;
heap_next = idx;
}
__name(dropObject, "dropObject");
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
__name(takeObject, "takeObject");
var cachedTextDecoder = new TextDecoder2("utf-8", { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
var cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
__name(getUint8Memory0, "getUint8Memory0");
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
__name(getStringFromWasm0, "getStringFromWasm0");
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
__name(addHeapObject, "addHeapObject");
function debugString(val2) {
const type = typeof val2;
if (type == "number" || type == "boolean" || val2 == null) {
return `${val2}`;
}
if (type == "string") {
return `"${val2}"`;
}
if (type == "symbol") {
const description = val2.description;
if (description == null) {
return "Symbol";
} else {
return `Symbol(${description})`;
}
}
if (type == "function") {
const name2 = val2.name;
if (typeof name2 == "string" && name2.length > 0) {
return `Function(${name2})`;
} else {
return "Function";
}
}
if (Array.isArray(val2)) {
const length = val2.length;
let debug = "[";
if (length > 0) {
debug += debugString(val2[0]);
}
for (let i5 = 1; i5 < length; i5++) {
debug += ", " + debugString(val2[i5]);
}
debug += "]";
return debug;
}
const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val2));
let className;
if (builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
return toString.call(val2);
}
if (className == "Object") {
try {
return "Object(" + JSON.stringify(val2) + ")";
} catch (_4) {
return "Object";
}
}
if (val2 instanceof Error) {
return `${val2.name}: ${val2.message}
${val2.stack}`;
}
return className;
}
__name(debugString, "debugString");
var WASM_VECTOR_LEN = 0;
var cachedTextEncoder = new TextEncoder4("utf-8");
var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
} : function(arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
};
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === void 0) {
const buf = cachedTextEncoder.encode(arg);
const ptr2 = malloc(buf.length);
getUint8Memory0().subarray(ptr2, ptr2 + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr2;
}
let len = arg.length;
let ptr = malloc(len);
const mem = getUint8Memory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 127) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3);
const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
__name(passStringToWasm0, "passStringToWasm0");
var cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
__name(getInt32Memory0, "getInt32Memory0");
function isLikeNone(x6) {
return x6 === void 0 || x6 === null;
}
__name(isLikeNone, "isLikeNone");
var stack_pointer = 32;
function addBorrowedObject(obj) {
if (stack_pointer == 1) throw new Error("out of js stack");
heap[--stack_pointer] = obj;
return stack_pointer;
}
__name(addBorrowedObject, "addBorrowedObject");
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
__name(passArray8ToWasm0, "passArray8ToWasm0");
function handleError(f6, args) {
try {
return f6.apply(this, args);
} catch (e7) {
wasm.__wbindgen_exn_store(addHeapObject(e7));
}
}
__name(handleError, "handleError");
var Comment = class _Comment {
static {
__name(this, "Comment");
}
static __wrap(ptr) {
const obj = Object.create(_Comment.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_comment_free(ptr);
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
before(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.comment_before(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
after(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.comment_after(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
replace(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.comment_replace(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
*/
remove() {
wasm.comment_remove(this.ptr);
return this;
}
/**
* @returns {boolean}
*/
get removed() {
var ret = wasm.comment_removed(this.ptr);
return ret !== 0;
}
/**
* @returns {string}
*/
get text() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.comment_text(retptr, this.ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_free(r0, r1);
}
}
/**
* @param {string} text
*/
set text(text) {
var ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.comment_set_text(this.ptr, ptr0, len0);
}
};
module3.exports.Comment = Comment;
var Doctype = class _Doctype {
static {
__name(this, "Doctype");
}
static __wrap(ptr) {
const obj = Object.create(_Doctype.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_doctype_free(ptr);
}
/**
* @returns {any}
*/
get name() {
var ret = wasm.doctype_name(this.ptr);
return takeObject(ret);
}
/**
* @returns {any}
*/
get publicId() {
var ret = wasm.doctype_public_id(this.ptr);
return takeObject(ret);
}
/**
* @returns {any}
*/
get systemId() {
var ret = wasm.doctype_system_id(this.ptr);
return takeObject(ret);
}
};
module3.exports.Doctype = Doctype;
var DocumentEnd = class _DocumentEnd {
static {
__name(this, "DocumentEnd");
}
static __wrap(ptr) {
const obj = Object.create(_DocumentEnd.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_documentend_free(ptr);
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
append(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.documentend_append(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
};
module3.exports.DocumentEnd = DocumentEnd;
var Element2 = class _Element {
static {
__name(this, "Element");
}
static __wrap(ptr) {
const obj = Object.create(_Element.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_element_free(ptr);
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
before(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_before(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
after(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_after(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
replace(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_replace(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
*/
remove() {
wasm.element_remove(this.ptr);
return this;
}
/**
* @returns {boolean}
*/
get removed() {
var ret = wasm.element_removed(this.ptr);
return ret !== 0;
}
/**
* @returns {string}
*/
get tagName() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.element_tag_name(retptr, this.ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_free(r0, r1);
}
}
/**
* @param {string} name
*/
set tagName(name2) {
var ptr0 = passStringToWasm0(name2, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_set_tag_name(this.ptr, ptr0, len0);
}
/**
* @returns {any}
*/
get namespaceURI() {
var ret = wasm.element_namespace_uri(this.ptr);
return takeObject(ret);
}
/**
* @returns {any}
*/
get attributes() {
var ret = wasm.element_attributes(this.ptr);
return takeObject(ret)[Symbol.iterator]();
}
/**
* @param {string} name
* @returns {any}
*/
getAttribute(name2) {
var ptr0 = passStringToWasm0(name2, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.element_getAttribute(this.ptr, ptr0, len0);
return takeObject(ret);
}
/**
* @param {string} name
* @returns {boolean}
*/
hasAttribute(name2) {
var ptr0 = passStringToWasm0(name2, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.element_hasAttribute(this.ptr, ptr0, len0);
return ret !== 0;
}
/**
* @param {string} name
* @param {string} value
*/
setAttribute(name2, value) {
var ptr0 = passStringToWasm0(name2, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ptr1 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
wasm.element_setAttribute(this.ptr, ptr0, len0, ptr1, len1);
return this;
}
/**
* @param {string} name
*/
removeAttribute(name2) {
var ptr0 = passStringToWasm0(name2, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_removeAttribute(this.ptr, ptr0, len0);
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
prepend(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_prepend(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
append(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_append(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
setInnerContent(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.element_setInnerContent(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
*/
removeAndKeepContent() {
wasm.element_removeAndKeepContent(this.ptr);
return this;
}
/**
* @param {any} handler
*/
onEndTag(handler) {
wasm.element_onEndTag(this.ptr, addHeapObject(handler.bind(this)));
}
};
module3.exports.Element = Element2;
var EndTag = class _EndTag {
static {
__name(this, "EndTag");
}
static __wrap(ptr) {
const obj = Object.create(_EndTag.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_endtag_free(ptr);
}
/**
* @returns {string}
*/
get name() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.endtag_name(retptr, this.ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_free(r0, r1);
}
}
/**
* @param {string} name
*/
set name(name2) {
var ptr0 = passStringToWasm0(name2, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.endtag_set_name(this.ptr, ptr0, len0);
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
before(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.endtag_before(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
after(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.endtag_after(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
*/
remove() {
wasm.endtag_remove(this.ptr);
return this;
}
};
module3.exports.EndTag = EndTag;
var HTMLRewriter3 = class _HTMLRewriter {
static {
__name(this, "HTMLRewriter");
}
static __wrap(ptr) {
const obj = Object.create(_HTMLRewriter.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_htmlrewriter_free(ptr);
}
/**
* @param {any} output_sink
* @param {any | undefined} options
*/
constructor(output_sink, options) {
try {
var ret = wasm.htmlrewriter_new(addBorrowedObject(output_sink), isLikeNone(options) ? 0 : addHeapObject(options));
return _HTMLRewriter.__wrap(ret);
} finally {
heap[stack_pointer++] = void 0;
}
}
/**
* @param {string} selector
* @param {any} handlers
*/
on(selector, handlers2) {
var ptr0 = passStringToWasm0(selector, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.htmlrewriter_on(this.ptr, ptr0, len0, addHeapObject(handlers2));
return this;
}
/**
* @param {any} handlers
*/
onDocument(handlers2) {
wasm.htmlrewriter_onDocument(this.ptr, addHeapObject(handlers2));
return this;
}
/**
* @param {Uint8Array} chunk
*/
async write(chunk) {
var ptr0 = passArray8ToWasm0(chunk, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
await wrap4(this, wasm.htmlrewriter_write, this.ptr, ptr0, len0);
}
/**
*/
async end() {
await wrap4(this, wasm.htmlrewriter_end, this.ptr);
}
/**
* @returns {number}
*/
get asyncifyStackPtr() {
var ret = wasm.htmlrewriter_asyncify_stack_ptr(this.ptr);
return ret;
}
};
module3.exports.HTMLRewriter = HTMLRewriter3;
var TextChunk = class _TextChunk {
static {
__name(this, "TextChunk");
}
static __wrap(ptr) {
const obj = Object.create(_TextChunk.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_textchunk_free(ptr);
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
before(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.textchunk_before(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
after(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.textchunk_after(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
* @param {string} content
* @param {any | undefined} content_type
*/
replace(content, content_type) {
var ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.textchunk_replace(this.ptr, ptr0, len0, isLikeNone(content_type) ? 0 : addHeapObject(content_type));
return this;
}
/**
*/
remove() {
wasm.textchunk_remove(this.ptr);
return this;
}
/**
* @returns {boolean}
*/
get removed() {
var ret = wasm.textchunk_removed(this.ptr);
return ret !== 0;
}
/**
* @returns {string}
*/
get text() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.textchunk_text(retptr, this.ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_free(r0, r1);
}
}
/**
* @returns {boolean}
*/
get lastInTextNode() {
var ret = wasm.textchunk_last_in_text_node(this.ptr);
return ret !== 0;
}
};
module3.exports.TextChunk = TextChunk;
module3.exports.__wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
module3.exports.__wbg_html_cd9a0f328493678b = function(arg0) {
var ret = getObject(arg0).html;
return isLikeNone(ret) ? 16777215 : ret ? 1 : 0;
};
module3.exports.__wbindgen_string_new = function(arg0, arg1) {
var ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
module3.exports.__wbg_documentend_new = function(arg0) {
var ret = DocumentEnd.__wrap(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_awaitPromise_39a1101fd8518869 = function(arg0, arg1) {
awaitPromise(arg0, getObject(arg1));
};
module3.exports.__wbindgen_object_clone_ref = function(arg0) {
var ret = getObject(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_element_c38470ed972aea27 = function(arg0) {
var ret = getObject(arg0).element;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_comments_ba86bc03331d9378 = function(arg0) {
var ret = getObject(arg0).comments;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_text_7800bf26cb443911 = function(arg0) {
var ret = getObject(arg0).text;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_element_new = function(arg0) {
var ret = Element2.__wrap(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_comment_new = function(arg0) {
var ret = Comment.__wrap(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_textchunk_new = function(arg0) {
var ret = TextChunk.__wrap(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_doctype_ac58c0964a59b61b = function(arg0) {
var ret = getObject(arg0).doctype;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_comments_94d876f6c0502e82 = function(arg0) {
var ret = getObject(arg0).comments;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_text_4606a16c30e4ae91 = function(arg0) {
var ret = getObject(arg0).text;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_end_34efb9402eac8a4e = function(arg0) {
var ret = getObject(arg0).end;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
module3.exports.__wbg_doctype_new = function(arg0) {
var ret = Doctype.__wrap(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_endtag_new = function(arg0) {
var ret = EndTag.__wrap(arg0);
return addHeapObject(ret);
};
module3.exports.__wbg_enableEsiTags_de6b91cc61a25874 = function(arg0) {
var ret = getObject(arg0).enableEsiTags;
return isLikeNone(ret) ? 16777215 : ret ? 1 : 0;
};
module3.exports.__wbg_String_60c4ba333b5ca1c6 = function(arg0, arg1) {
var ret = String(getObject(arg1));
var ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
module3.exports.__wbg_new_4fee7e2900033464 = function() {
var ret = new Array();
return addHeapObject(ret);
};
module3.exports.__wbg_push_ba9b5e3c25cff8f9 = function(arg0, arg1) {
var ret = getObject(arg0).push(getObject(arg1));
return ret;
};
module3.exports.__wbg_call_6c4ea719458624eb = function() {
return handleError(function(arg0, arg1, arg2) {
var ret = getObject(arg0).call(getObject(arg1), getObject(arg2));
return addHeapObject(ret);
}, arguments);
};
module3.exports.__wbg_new_917809a3e20a4b00 = function(arg0, arg1) {
var ret = new TypeError(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
module3.exports.__wbg_instanceof_Promise_c6535fc791fcc4d2 = function(arg0) {
var obj = getObject(arg0);
var ret = obj instanceof Promise || Object.prototype.toString.call(obj) === "[object Promise]";
return ret;
};
module3.exports.__wbg_buffer_89a8560ab6a3d9c6 = function(arg0) {
var ret = getObject(arg0).buffer;
return addHeapObject(ret);
};
module3.exports.__wbg_newwithbyteoffsetandlength_e45d8b33c02dc3b5 = function(arg0, arg1, arg2) {
var ret = new Uint8Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
module3.exports.__wbg_new_bd2e1d010adb8a1a = function(arg0) {
var ret = new Uint8Array(getObject(arg0));
return addHeapObject(ret);
};
module3.exports.__wbindgen_debug_string = function(arg0, arg1) {
var ret = debugString(getObject(arg1));
var ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
module3.exports.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
module3.exports.__wbindgen_rethrow = function(arg0) {
throw takeObject(arg0);
};
module3.exports.__wbindgen_memory = function() {
var ret = wasm.memory;
return addHeapObject(ret);
};
var path72 = require("path").join(__dirname, "html_rewriter_bg.wasm");
var bytes = require("fs").readFileSync(path72);
var wasmModule = new WebAssembly.Module(bytes);
var wasmInstance = new WebAssembly.Instance(wasmModule, imports);
wasm = wasmInstance.exports;
setWasmExports(wasm);
module3.exports.__wasm = wasm;
}
});
// ../pages-shared/environment-polyfills/html-rewriter.ts
var html_rewriter_exports = {};
__export(html_rewriter_exports, {
HTMLRewriter: () => HTMLRewriter2
});
var import_web2, import_miniflare29, HTMLRewriter2;
var init_html_rewriter = __esm({
"../pages-shared/environment-polyfills/html-rewriter.ts"() {
init_import_meta_url();
import_web2 = require("stream/web");
import_miniflare29 = require("miniflare");
HTMLRewriter2 = class {
static {
__name(this, "HTMLRewriter");
}
#elementHandlers = [];
#documentHandlers = [];
on(selector, handlers2) {
this.#elementHandlers.push([selector, handlers2]);
return this;
}
onDocument(handlers2) {
this.#documentHandlers.push(handlers2);
return this;
}
transform(response) {
const body = response.body;
if (body === null) {
return new import_miniflare29.Response(body, response);
}
response = new import_miniflare29.Response(response.body, response);
let rewriter;
const transformStream = new import_web2.TransformStream({
start: /* @__PURE__ */ __name(async (controller) => {
const {
HTMLRewriter: BaseHTMLRewriter
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
} = await Promise.resolve().then(() => __toESM(require_html_rewriter()));
rewriter = new BaseHTMLRewriter((output) => {
if (output.length !== 0) {
controller.enqueue(output);
}
});
for (const [selector, handlers2] of this.#elementHandlers) {
rewriter.on(selector, handlers2);
}
for (const handlers2 of this.#documentHandlers) {
rewriter.onDocument(handlers2);
}
}, "start"),
// The finally() below will ensure the rewriter is always freed.
// chunk is guaranteed to be a Uint8Array as we're using the
// @miniflare/core Response class, which transforms to a byte stream.
transform: /* @__PURE__ */ __name((chunk) => rewriter.write(chunk), "transform"),
flush: /* @__PURE__ */ __name(() => rewriter.end(), "flush")
});
const promise = body.pipeTo(transformStream.writable);
promise.catch(() => {
}).finally(() => rewriter.free());
const res = new import_miniflare29.Response(transformStream.readable, response);
res.headers.delete("Content-Length");
return res;
}
};
}
});
// ../pages-shared/environment-polyfills/miniflare.ts
var miniflare_exports2 = {};
__export(miniflare_exports2, {
default: () => miniflare_default
});
var miniflare_default;
var init_miniflare2 = __esm({
"../pages-shared/environment-polyfills/miniflare.ts"() {
init_import_meta_url();
init_environment_polyfills();
miniflare_default = /* @__PURE__ */ __name(async () => {
const { HTMLRewriter: HTMLRewriter3 } = await Promise.resolve().then(() => (init_html_rewriter(), html_rewriter_exports));
const mf = await import("miniflare");
polyfill({
fetch: mf.fetch,
Headers: mf.Headers,
Request: mf.Request,
Response: mf.Response,
HTMLRewriter: HTMLRewriter3
});
}, "default");
}
});
// ../workers-shared/utils/responses.ts
var init_responses = __esm({
"../workers-shared/utils/responses.ts"() {
init_import_meta_url();
}
});
// ../workers-shared/utils/tracing.ts
var init_tracing2 = __esm({
"../workers-shared/utils/tracing.ts"() {
init_import_meta_url();
}
});
// ../workers-shared/asset-worker/src/compatibility-flags.ts
var init_compatibility_flags = __esm({
"../workers-shared/asset-worker/src/compatibility-flags.ts"() {
init_import_meta_url();
}
});
// ../workers-shared/asset-worker/src/constants.ts
var init_constants21 = __esm({
"../workers-shared/asset-worker/src/constants.ts"() {
init_import_meta_url();
}
});
// ../workers-shared/asset-worker/src/utils/headers.ts
var init_headers = __esm({
"../workers-shared/asset-worker/src/utils/headers.ts"() {
init_import_meta_url();
init_tracing2();
init_compatibility_flags();
init_constants21();
init_handler2();
init_rules_engine();
}
});
// ../workers-shared/asset-worker/src/handler.ts
var init_handler2 = __esm({
"../workers-shared/asset-worker/src/handler.ts"() {
init_import_meta_url();
init_responses();
init_tracing2();
init_compatibility_flags();
init_headers();
init_rules_engine();
}
});
// ../workers-shared/asset-worker/src/utils/rules-engine.ts
var ESCAPE_REGEX_CHARACTERS2, escapeRegex2, HOST_PLACEHOLDER_REGEX, PLACEHOLDER_REGEX2, replacer, generateRuleRegExp, generateRulesMatcher;
var init_rules_engine = __esm({
"../workers-shared/asset-worker/src/utils/rules-engine.ts"() {
init_import_meta_url();
init_handler2();
ESCAPE_REGEX_CHARACTERS2 = /[-/\\^$*+?.()|[\]{}]/g;
escapeRegex2 = /* @__PURE__ */ __name((str) => {
return str.replace(ESCAPE_REGEX_CHARACTERS2, "\\$&");
}, "escapeRegex");
HOST_PLACEHOLDER_REGEX = /(?<=^https:\\\/\\\/[^/]*?):([A-Za-z]\w*)(?=\\)/g;
PLACEHOLDER_REGEX2 = /:([A-Za-z]\w*)/g;
replacer = /* @__PURE__ */ __name((str, replacements) => {
for (const [replacement, value] of Object.entries(replacements)) {
str = str.replaceAll(`:${replacement}`, value);
}
return str;
}, "replacer");
generateRuleRegExp = /* @__PURE__ */ __name((rule) => {
rule = rule.split("*").map(escapeRegex2).join("(?<splat>.*)");
const host_matches = rule.matchAll(HOST_PLACEHOLDER_REGEX);
for (const host_match of host_matches) {
rule = rule.split(host_match[0]).join(`(?<${host_match[1]}>[^/.]+)`);
}
const path_matches = rule.matchAll(PLACEHOLDER_REGEX2);
for (const path_match of path_matches) {
rule = rule.split(path_match[0]).join(`(?<${path_match[1]}>[^/]+)`);
}
rule = "^" + rule + "$";
return RegExp(rule);
}, "generateRuleRegExp");
generateRulesMatcher = /* @__PURE__ */ __name((rules, replacerFn = (match2) => match2) => {
if (!rules) {
return () => [];
}
const compiledRules = Object.entries(rules).map(([rule, match2]) => {
const crossHost = rule.startsWith("https://");
try {
const regExp = generateRuleRegExp(rule);
return [{ crossHost, regExp }, match2];
} catch {
}
}).filter((value) => value !== void 0);
return ({ request: request4 }) => {
const { pathname, hostname: hostname2 } = new URL(request4.url);
return compiledRules.map(([{ crossHost, regExp }, match2]) => {
const test = crossHost ? `https://${hostname2}${pathname}` : pathname;
const result = regExp.exec(test);
if (result) {
return replacerFn(match2, result.groups || {});
}
}).filter((value) => value !== void 0);
};
}, "generateRulesMatcher");
}
});
// ../pages-shared/asset-server/responses.ts
function mergeHeaders(base, extra) {
const baseHeaders = new Headers(base ?? {});
const extraHeaders = new Headers(extra ?? {});
return new Headers({
...Object.fromEntries(baseHeaders.entries()),
...Object.fromEntries(extraHeaders.entries())
});
}
function stripLeadingDoubleSlashes(location) {
return location.replace(/^(\/|%2F|%2f|%5C|%5c|%09|\s|\\)+(.*)/, "/$2");
}
var OkResponse2, MovedPermanentlyResponse2, FoundResponse2, NotModifiedResponse2, PermanentRedirectResponse2, NotFoundResponse2, MethodNotAllowedResponse2, NotAcceptableResponse, InternalServerErrorResponse2, SeeOtherResponse2, TemporaryRedirectResponse2;
var init_responses2 = __esm({
"../pages-shared/asset-server/responses.ts"() {
init_import_meta_url();
__name(mergeHeaders, "mergeHeaders");
__name(stripLeadingDoubleSlashes, "stripLeadingDoubleSlashes");
OkResponse2 = class extends Response {
static {
__name(this, "OkResponse");
}
constructor(...[body, init3]) {
super(body, {
...init3,
status: 200,
statusText: "OK"
});
}
};
MovedPermanentlyResponse2 = class extends Response {
static {
__name(this, "MovedPermanentlyResponse");
}
constructor(location, init3, {
preventLeadingDoubleSlash = true
} = {
preventLeadingDoubleSlash: true
}) {
location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
super(`Redirecting to ${location}`, {
...init3,
status: 301,
statusText: "Moved Permanently",
headers: mergeHeaders(init3?.headers, {
location
})
});
}
};
FoundResponse2 = class extends Response {
static {
__name(this, "FoundResponse");
}
constructor(location, init3, {
preventLeadingDoubleSlash = true
} = {
preventLeadingDoubleSlash: true
}) {
location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
super(`Redirecting to ${location}`, {
...init3,
status: 302,
statusText: "Found",
headers: mergeHeaders(init3?.headers, {
location
})
});
}
};
NotModifiedResponse2 = class extends Response {
static {
__name(this, "NotModifiedResponse");
}
constructor(...[_body, _init]) {
super(void 0, {
status: 304,
statusText: "Not Modified"
});
}
};
PermanentRedirectResponse2 = class extends Response {
static {
__name(this, "PermanentRedirectResponse");
}
constructor(location, init3, {
preventLeadingDoubleSlash = true
} = {
preventLeadingDoubleSlash: true
}) {
location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
super(void 0, {
...init3,
status: 308,
statusText: "Permanent Redirect",
headers: mergeHeaders(init3?.headers, {
location
})
});
}
};
NotFoundResponse2 = class extends Response {
static {
__name(this, "NotFoundResponse");
}
constructor(...[body, init3]) {
super(body, {
...init3,
status: 404,
statusText: "Not Found"
});
}
};
MethodNotAllowedResponse2 = class extends Response {
static {
__name(this, "MethodNotAllowedResponse");
}
constructor(...[body, init3]) {
super(body, {
...init3,
status: 405,
statusText: "Method Not Allowed"
});
}
};
NotAcceptableResponse = class extends Response {
static {
__name(this, "NotAcceptableResponse");
}
constructor(...[body, init3]) {
super(body, {
...init3,
status: 406,
statusText: "Not Acceptable"
});
}
};
InternalServerErrorResponse2 = class extends Response {
static {
__name(this, "InternalServerErrorResponse");
}
constructor(err, init3) {
let body = void 0;
if (globalThis.DEBUG) {
body = `${err.message}
${err.stack}`;
}
super(body, {
...init3,
status: 500,
statusText: "Internal Server Error"
});
}
};
SeeOtherResponse2 = class extends Response {
static {
__name(this, "SeeOtherResponse");
}
constructor(location, init3, {
preventLeadingDoubleSlash = true
} = {
preventLeadingDoubleSlash: true
}) {
location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
super(`Redirecting to ${location}`, {
...init3,
status: 303,
statusText: "See Other",
headers: mergeHeaders(init3?.headers, { location })
});
}
};
TemporaryRedirectResponse2 = class extends Response {
static {
__name(this, "TemporaryRedirectResponse");
}
constructor(location, init3, {
preventLeadingDoubleSlash = true
} = {
preventLeadingDoubleSlash: true
}) {
location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
super(`Redirecting to ${location}`, {
...init3,
status: 307,
statusText: "Temporary Redirect",
headers: mergeHeaders(init3?.headers, { location })
});
}
};
}
});
// ../pages-shared/asset-server/handler.ts
var handler_exports = {};
__export(handler_exports, {
ANALYTICS_VERSION: () => ANALYTICS_VERSION2,
ASSET_PRESERVATION_CACHE: () => ASSET_PRESERVATION_CACHE,
CACHE_CONTROL_BROWSER: () => CACHE_CONTROL_BROWSER2,
CACHE_PRESERVATION_WRITE_FREQUENCY: () => CACHE_PRESERVATION_WRITE_FREQUENCY,
HEADERS_VERSION: () => HEADERS_VERSION3,
HEADERS_VERSION_V1: () => HEADERS_VERSION_V1,
REDIRECTS_VERSION: () => REDIRECTS_VERSION3,
generateHandler: () => generateHandler,
isPreservationCacheResponseExpiring: () => isPreservationCacheResponseExpiring,
normaliseHeaders: () => normaliseHeaders,
parseQualityWeightedList: () => parseQualityWeightedList
});
function normaliseHeaders(headers) {
if (headers.version === HEADERS_VERSION3) {
return headers.rules;
} else if (headers.version === HEADERS_VERSION_V1) {
return Object.keys(headers.rules).reduce(
(acc, key) => {
acc[key] = {
set: headers.rules[key]
};
return acc;
},
{}
);
} else {
return {};
}
}
function generateETagHeader(assetKey) {
const strongETag = `"${assetKey}"`;
const weakETag = `W/"${assetKey}"`;
return { strongETag, weakETag };
}
function checkIfNoneMatch(request4, strongETag, weakETag) {
const ifNoneMatch = request4.headers.get("if-none-match");
return ifNoneMatch === weakETag || ifNoneMatch === strongETag;
}
async function generateHandler({
request: request4,
metadata,
xServerEnvHeader,
xDeploymentIdHeader,
xWebAnalyticsHeader,
logError,
setMetrics,
findAssetEntryForPath,
getAssetKey,
negotiateContent,
fetchAsset,
generateNotFoundResponse = /* @__PURE__ */ __name(async (notFoundRequest, notFoundFindAssetEntryForPath, notFoundServeAsset) => {
let assetEntry;
if (assetEntry = await notFoundFindAssetEntryForPath("/index.html")) {
return notFoundServeAsset(assetEntry, { preserve: false });
}
return new NotFoundResponse2();
}, "generateNotFoundResponse"),
attachAdditionalHeaders = /* @__PURE__ */ __name(() => {
}, "attachAdditionalHeaders"),
caches,
waitUntil
}) {
const url4 = new URL(request4.url);
const { protocol, host, search } = url4;
let { pathname } = url4;
const earlyHintsCache = metadata.deploymentId ? await caches?.open(`eh:${metadata.deploymentId}`) : void 0;
const headerRules = metadata.headers ? normaliseHeaders(metadata.headers) : {};
const staticRules = metadata.redirects?.version === REDIRECTS_VERSION3 ? metadata.redirects.staticRules || {} : {};
const staticRedirectsMatcher2 = /* @__PURE__ */ __name(() => {
const withHostMatch = staticRules[`https://${host}${pathname}`];
const withoutHostMatch = staticRules[pathname];
if (withHostMatch && withoutHostMatch) {
if (withHostMatch.lineNumber < withoutHostMatch.lineNumber) {
return withHostMatch;
} else {
return withoutHostMatch;
}
}
return withHostMatch || withoutHostMatch;
}, "staticRedirectsMatcher");
const generateRedirectsMatcher2 = /* @__PURE__ */ __name(() => generateRulesMatcher(
metadata.redirects?.version === REDIRECTS_VERSION3 ? metadata.redirects.rules : {},
({ status: status2, to }, replacements) => ({
status: status2,
to: replacer(to, replacements)
})
), "generateRedirectsMatcher");
let assetEntry;
async function generateResponse() {
const match2 = staticRedirectsMatcher2() || generateRedirectsMatcher2()({ request: request4 })[0];
if (match2) {
if (match2.status === 200) {
pathname = new URL(match2.to, request4.url).pathname;
} else {
const { status: status2, to } = match2;
const destination = new URL(to, request4.url);
const location = destination.origin === new URL(request4.url).origin ? `${destination.pathname}${destination.search || search}${destination.hash}` : `${destination.href.slice(0, destination.href.length - (destination.search.length + destination.hash.length))}${destination.search ? destination.search : search}${destination.hash}`;
switch (status2) {
case 301:
return new MovedPermanentlyResponse2(location, void 0, {
preventLeadingDoubleSlash: false
});
case 303:
return new SeeOtherResponse2(location, void 0, {
preventLeadingDoubleSlash: false
});
case 307:
return new TemporaryRedirectResponse2(location, void 0, {
preventLeadingDoubleSlash: false
});
case 308:
return new PermanentRedirectResponse2(location, void 0, {
preventLeadingDoubleSlash: false
});
case 302:
default:
return new FoundResponse2(location, void 0, {
preventLeadingDoubleSlash: false
});
}
}
}
if (!request4.method.match(/^(get|head)$/i)) {
return new MethodNotAllowedResponse2();
}
try {
pathname = globalThis.decodeURIComponent(pathname);
} catch {
}
if (pathname.endsWith("/")) {
if (assetEntry = await findAssetEntryForPath(`${pathname}index.html`)) {
return serveAsset(assetEntry);
} else if (pathname.endsWith("/index/")) {
return new PermanentRedirectResponse2(
`/${pathname.slice(1, -"index/".length)}${search}`
);
} else if (assetEntry = await findAssetEntryForPath(
`${pathname.replace(/\/$/, ".html")}`
)) {
return new PermanentRedirectResponse2(
`/${pathname.slice(1, -1)}${search}`
);
} else {
return notFound();
}
}
if (assetEntry = await findAssetEntryForPath(pathname)) {
if (pathname.endsWith(".html")) {
const extensionlessPath = pathname.slice(0, -".html".length);
if (extensionlessPath.endsWith("/index")) {
return new PermanentRedirectResponse2(
`${extensionlessPath.replace(/\/index$/, "/")}${search}`
);
} else if (await findAssetEntryForPath(extensionlessPath) || extensionlessPath === "/") {
return serveAsset(assetEntry);
} else {
return new PermanentRedirectResponse2(`${extensionlessPath}${search}`);
}
} else {
return serveAsset(assetEntry);
}
} else if (pathname.endsWith("/index")) {
return new PermanentRedirectResponse2(
`/${pathname.slice(1, -"index".length)}${search}`
);
} else if (assetEntry = await findAssetEntryForPath(`${pathname}.html`)) {
return serveAsset(assetEntry);
}
if (assetEntry = await findAssetEntryForPath(`${pathname}/index.html`)) {
return new PermanentRedirectResponse2(`${pathname}/${search}`);
} else {
return notFound();
}
}
__name(generateResponse, "generateResponse");
function isNullBodyStatus(status2) {
return [101, 204, 205, 304].includes(status2);
}
__name(isNullBodyStatus, "isNullBodyStatus");
async function attachHeaders(response) {
const existingHeaders = new Headers(response.headers);
const eTag = existingHeaders.get("eTag")?.match(/^"(.*)"$/)?.[1];
const extraHeaders = new Headers({
"access-control-allow-origin": "*",
"referrer-policy": "strict-origin-when-cross-origin",
...existingHeaders.has("content-type") ? { "x-content-type-options": "nosniff" } : {}
});
const headers = new Headers({
// But we intentionally override existing headers
...Object.fromEntries(existingHeaders.entries()),
...Object.fromEntries(extraHeaders.entries())
});
if (earlyHintsCache && isHTMLContentType(response.headers.get("Content-Type")) && eTag) {
const preEarlyHintsHeaders = new Headers(headers);
const earlyHintsCacheKey = `${protocol}//${host}/${eTag}`;
const earlyHintsResponse = await earlyHintsCache.match(earlyHintsCacheKey);
if (earlyHintsResponse) {
const earlyHintsLinkHeader = earlyHintsResponse.headers.get("Link");
if (earlyHintsLinkHeader) {
headers.set("Link", earlyHintsLinkHeader);
if (setMetrics) {
setMetrics({ earlyHintsResult: "used-hit" });
}
} else {
if (setMetrics) {
setMetrics({ earlyHintsResult: "notused-hit" });
}
}
} else {
if (setMetrics) {
setMetrics({ earlyHintsResult: "notused-miss" });
}
const clonedResponse = response.clone();
if (waitUntil) {
waitUntil(
(async () => {
try {
const links = [];
const transformedResponse = new HTMLRewriter().on(
"link[rel~=preconnect],link[rel~=preload],link[rel~=modulepreload]",
{
element(element) {
for (const [attributeName] of element.attributes) {
if (!ALLOWED_EARLY_HINT_LINK_ATTRIBUTES.includes(
attributeName.toLowerCase()
)) {
return;
}
}
const href = element.getAttribute("href") || void 0;
const rel = element.getAttribute("rel") || void 0;
const as2 = element.getAttribute("as") || void 0;
if (href && !href.startsWith("data:") && rel) {
links.push({ href, rel, as: as2 });
}
}
}
).transform(clonedResponse);
await transformedResponse.text();
links.forEach(({ href, rel, as: as2 }) => {
let link = `<${href}>; rel="${rel}"`;
if (as2) {
link += `; as=${as2}`;
}
preEarlyHintsHeaders.append("Link", link);
});
const linkHeader = preEarlyHintsHeaders.get("Link");
const earlyHintsHeaders = new Headers({
"Cache-Control": "max-age=2592000"
// 30 days
});
if (linkHeader) {
earlyHintsHeaders.append("Link", linkHeader);
}
await earlyHintsCache.put(
earlyHintsCacheKey,
new Response(null, { headers: earlyHintsHeaders })
);
} catch {
await earlyHintsCache.put(
earlyHintsCacheKey,
new Response(null, {
headers: {
"Cache-Control": "max-age=86400"
// 1 day
}
})
);
}
})()
);
}
}
} else {
if (setMetrics) {
setMetrics({ earlyHintsResult: "disabled" });
}
}
const headersMatcher = generateRulesMatcher(
headerRules,
({ set = {}, unset = [] }, replacements) => {
const replacedSet = {};
Object.keys(set).forEach((key) => {
replacedSet[key] = replacer(set[key], replacements);
});
return {
set: replacedSet,
unset
};
}
);
const matches = headersMatcher({ request: request4 });
const setMap = /* @__PURE__ */ new Set();
matches.forEach(({ set = {}, unset = [] }) => {
unset.forEach((key) => {
headers.delete(key);
});
Object.keys(set).forEach((key) => {
if (setMap.has(key.toLowerCase())) {
headers.append(key, set[key]);
} else {
headers.set(key, set[key]);
setMap.add(key.toLowerCase());
}
});
});
return new Response(
isNullBodyStatus(response.status) ? null : response.body,
{
headers,
status: response.status,
statusText: response.statusText
}
);
}
__name(attachHeaders, "attachHeaders");
const responseWithoutHeaders = await generateResponse();
if (responseWithoutHeaders.status >= 500) {
return responseWithoutHeaders;
}
const responseWithHeaders = await attachHeaders(responseWithoutHeaders);
if (responseWithHeaders.status === 404) {
if (responseWithHeaders.headers.has("cache-control")) {
responseWithHeaders.headers.delete("cache-control");
}
responseWithHeaders.headers.append("cache-control", "no-store");
}
return responseWithHeaders;
async function serveAsset(servingAssetEntry, options = { preserve: true }) {
let content;
try {
content = negotiateContent(request4, servingAssetEntry);
} catch {
return new NotAcceptableResponse();
}
const assetKey = getAssetKey(servingAssetEntry, content);
const { strongETag, weakETag } = generateETagHeader(assetKey);
const isIfNoneMatch = checkIfNoneMatch(request4, strongETag, weakETag);
if (isIfNoneMatch) {
return new NotModifiedResponse2();
}
try {
const asset = await fetchAsset(assetKey);
const headers = {
etag: strongETag,
"content-type": asset.contentType
};
let encodeBody = "automatic";
if (xServerEnvHeader) {
headers["x-server-env"] = xServerEnvHeader;
}
if (xDeploymentIdHeader && metadata.deploymentId) {
headers["x-deployment-id"] = metadata.deploymentId;
}
if (content.encoding) {
encodeBody = "manual";
headers["cache-control"] = "no-transform";
headers["content-encoding"] = content.encoding;
}
const response = new OkResponse2(
request4.method === "HEAD" ? null : asset.body,
{
headers,
encodeBody
}
);
if (isCacheable(request4)) {
response.headers.append("cache-control", CACHE_CONTROL_BROWSER2);
}
attachAdditionalHeaders(response, content, servingAssetEntry, asset);
if (isPreview(new URL(request4.url))) {
response.headers.set("x-robots-tag", "noindex");
}
if (options.preserve && waitUntil && caches) {
waitUntil(
(async () => {
try {
const assetPreservationCache = await caches.open(
ASSET_PRESERVATION_CACHE
);
const match2 = await assetPreservationCache.match(request4);
if (!match2 || assetKey !== await match2.text() || isPreservationCacheResponseExpiring(match2)) {
const preservedResponse = new Response(assetKey, response);
preservedResponse.headers.set(
"cache-control",
CACHE_CONTROL_PRESERVATION
);
preservedResponse.headers.set("x-robots-tag", "noindex");
await assetPreservationCache.put(
request4.url,
preservedResponse
);
}
} catch (err) {
logError(err);
}
})()
);
}
if (isHTMLContentType(asset.contentType) && metadata.analytics?.version === ANALYTICS_VERSION2) {
if (xWebAnalyticsHeader) {
response.headers.set("x-cf-pages-analytics", "1");
}
return new HTMLRewriter().on("body", {
element(e7) {
e7.append(
`<!-- Cloudflare Pages Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "${metadata.analytics?.token}"}'></script><!-- Cloudflare Pages Analytics -->`,
{ html: true }
);
}
}).transform(response);
}
return response;
} catch (err) {
logError(err);
return new InternalServerErrorResponse2(err);
}
}
__name(serveAsset, "serveAsset");
async function notFound() {
if (caches) {
try {
const assetPreservationCache = await caches.open(
ASSET_PRESERVATION_CACHE
);
const preservedResponse = await assetPreservationCache.match(
request4.url
);
if (preservedResponse) {
if (setMetrics) {
setMetrics({ preservationCacheResult: "checked-hit" });
}
const assetKey = await preservedResponse.text();
if (isNullBodyStatus(preservedResponse.status)) {
return new Response(null, preservedResponse);
}
if (assetKey) {
const { strongETag, weakETag } = generateETagHeader(assetKey);
const isIfNoneMatch = checkIfNoneMatch(
request4,
strongETag,
weakETag
);
if (isIfNoneMatch) {
if (setMetrics) {
setMetrics({ preservationCacheResult: "not-modified" });
}
return new NotModifiedResponse2();
}
const asset = await fetchAsset(assetKey);
if (asset) {
return new Response(asset.body, preservedResponse);
} else {
logError(
new Error(
`preservation cache contained assetKey that does not exist in storage: ${assetKey}`
)
);
}
} else {
logError(new Error(`cached response had no assetKey: ${assetKey}`));
}
} else {
if (setMetrics) {
setMetrics({ preservationCacheResult: "checked-miss" });
}
}
} catch (err) {
logError(err);
}
} else {
if (setMetrics) {
setMetrics({ preservationCacheResult: "disabled" });
}
}
let cwd2 = pathname;
while (cwd2) {
cwd2 = cwd2.slice(0, cwd2.lastIndexOf("/"));
if (assetEntry = await findAssetEntryForPath(`${cwd2}/404.html`)) {
let content;
try {
content = negotiateContent(request4, assetEntry);
} catch {
return new NotAcceptableResponse();
}
const assetKey = getAssetKey(assetEntry, content);
try {
const { body, contentType } = await fetchAsset(assetKey);
const response = new NotFoundResponse2(body);
response.headers.set("content-type", contentType);
return response;
} catch (err) {
logError(err);
return new InternalServerErrorResponse2(err);
}
}
}
return await generateNotFoundResponse(
request4,
findAssetEntryForPath,
serveAsset
);
}
__name(notFound, "notFound");
}
function parseQualityWeightedList(list = "") {
const items = {};
list.replace(/\s/g, "").split(",").forEach((el) => {
const [item, weight] = el.split(";q=");
items[item] = weight ? parseFloat(weight) : 1;
});
return items;
}
function isCacheable(request4) {
return !request4.headers.has("authorization") && !request4.headers.has("range");
}
function isPreview(url4) {
if (url4.hostname.endsWith(".pages.dev")) {
return url4.hostname.split(".").length > 3 ? true : false;
}
return false;
}
function isPreservationCacheResponseExpiring(response) {
const ageHeader = response.headers.get("age");
if (!ageHeader) {
return false;
}
try {
const age = parseInt(ageHeader);
const jitter = Math.floor(Math.random() * 43200);
if (age > CACHE_PRESERVATION_WRITE_FREQUENCY + jitter) {
return true;
}
} catch {
return false;
}
return false;
}
function isHTMLContentType(contentType) {
return contentType?.toLowerCase().startsWith("text/html") || false;
}
var ASSET_PRESERVATION_CACHE, CACHE_CONTROL_PRESERVATION, CACHE_PRESERVATION_WRITE_FREQUENCY, CACHE_CONTROL_BROWSER2, REDIRECTS_VERSION3, HEADERS_VERSION3, HEADERS_VERSION_V1, ANALYTICS_VERSION2, ALLOWED_EARLY_HINT_LINK_ATTRIBUTES;
var init_handler3 = __esm({
"../pages-shared/asset-server/handler.ts"() {
init_import_meta_url();
init_rules_engine();
init_responses2();
ASSET_PRESERVATION_CACHE = "assetPreservationCacheV2";
CACHE_CONTROL_PRESERVATION = "public, s-maxage=604800";
CACHE_PRESERVATION_WRITE_FREQUENCY = 86400;
CACHE_CONTROL_BROWSER2 = "public, max-age=0, must-revalidate";
REDIRECTS_VERSION3 = 1;
HEADERS_VERSION3 = 2;
HEADERS_VERSION_V1 = 1;
ANALYTICS_VERSION2 = 1;
ALLOWED_EARLY_HINT_LINK_ATTRIBUTES = ["rel", "as", "href"];
__name(normaliseHeaders, "normaliseHeaders");
__name(generateETagHeader, "generateETagHeader");
__name(checkIfNoneMatch, "checkIfNoneMatch");
__name(generateHandler, "generateHandler");
__name(parseQualityWeightedList, "parseQualityWeightedList");
__name(isCacheable, "isCacheable");
__name(isPreview, "isPreview");
__name(isPreservationCacheResponseExpiring, "isPreservationCacheResponseExpiring");
__name(isHTMLContentType, "isHTMLContentType");
}
});
// src/miniflare-cli/assets.ts
var assets_exports = {};
__export(assets_exports, {
default: () => generateASSETSBinding
});
async function generateASSETSBinding(options) {
const assetsFetch = options.directory !== void 0 ? await generateAssetsFetch(options.directory, options.log) : invalidAssetsFetch;
return async function(miniflareRequest) {
if (options.proxyPort) {
try {
const url4 = new URL(miniflareRequest.url);
url4.host = `localhost:${options.proxyPort}`;
const proxyRequest = new import_miniflare30.Request(url4, miniflareRequest);
if (proxyRequest.headers.get("Upgrade") === "websocket") {
proxyRequest.headers.delete("Sec-WebSocket-Accept");
proxyRequest.headers.delete("Sec-WebSocket-Key");
}
return await (0, import_miniflare30.fetch)(proxyRequest, {
dispatcher: new ProxyDispatcher(miniflareRequest.headers.get("Host"))
});
} catch (thrown) {
options.log.error(new Error(`Could not proxy request: ${thrown}`));
return new import_miniflare30.Response(`[wrangler] Could not proxy request: ${thrown}`, {
status: 502
});
}
} else {
try {
return await assetsFetch(miniflareRequest);
} catch (thrown) {
options.log.error(new Error(`Could not serve static asset: ${thrown}`));
return new import_miniflare30.Response(
`[wrangler] Could not serve static asset: ${thrown}`,
{ status: 502 }
);
}
}
};
}
async function generateAssetsFetch(directory, log2) {
directory = (0, import_node_path67.resolve)(directory);
const polyfill2 = (await Promise.resolve().then(() => (init_miniflare2(), miniflare_exports2))).default;
await polyfill2();
const { generateHandler: generateHandler2, parseQualityWeightedList: parseQualityWeightedList2 } = await Promise.resolve().then(() => (init_handler3(), handler_exports));
const headersFile = (0, import_node_path67.join)(directory, "_headers");
const redirectsFile = (0, import_node_path67.join)(directory, "_redirects");
const workerFile = (0, import_node_path67.join)(directory, "_worker.js");
const ignoredFiles = [headersFile, redirectsFile, workerFile];
let redirects;
if ((0, import_node_fs36.existsSync)(redirectsFile)) {
const contents = (0, import_node_fs36.readFileSync)(redirectsFile, "utf-8");
redirects = parseRedirects(contents);
}
let headers;
if ((0, import_node_fs36.existsSync)(headersFile)) {
const contents = (0, import_node_fs36.readFileSync)(headersFile, "utf-8");
headers = parseHeaders(contents);
}
let metadata = createMetadataObject({
redirects,
headers,
headersFile,
redirectsFile,
logger: log2
});
watch([headersFile, redirectsFile], { persistent: true }).on(
"change",
(path72) => {
switch (path72) {
case headersFile: {
log2.log("_headers modified. Re-evaluating...");
const contents = (0, import_node_fs36.readFileSync)(headersFile).toString();
headers = parseHeaders(contents);
break;
}
case redirectsFile: {
log2.log("_redirects modified. Re-evaluating...");
const contents = (0, import_node_fs36.readFileSync)(redirectsFile).toString();
redirects = parseRedirects(contents);
break;
}
}
metadata = createMetadataObject({
redirects,
headers,
redirectsFile,
headersFile,
logger: log2
});
}
);
const generateResponse = /* @__PURE__ */ __name(async (request4) => {
const assetKeyEntryMap = /* @__PURE__ */ new Map();
return await generateHandler2({
request: request4,
metadata,
xServerEnvHeader: "dev",
xWebAnalyticsHeader: false,
logError: logger.error,
findAssetEntryForPath: /* @__PURE__ */ __name(async (path72) => {
const filepath = (0, import_node_path67.resolve)((0, import_node_path67.join)(directory, path72));
if (!filepath.startsWith(directory)) {
return null;
}
if ((0, import_node_fs36.existsSync)(filepath) && (0, import_node_fs36.lstatSync)(filepath).isFile() && !ignoredFiles.includes(filepath)) {
const hash = hashFile(filepath);
assetKeyEntryMap.set(hash, filepath);
return hash;
}
return null;
}, "findAssetEntryForPath"),
getAssetKey: /* @__PURE__ */ __name((assetEntry) => {
return assetEntry;
}, "getAssetKey"),
negotiateContent: /* @__PURE__ */ __name((contentRequest) => {
let rawAcceptEncoding;
if (contentRequest.cf && "clientAcceptEncoding" in contentRequest.cf && contentRequest.cf.clientAcceptEncoding) {
rawAcceptEncoding = contentRequest.cf.clientAcceptEncoding;
} else {
rawAcceptEncoding = contentRequest.headers.get("Accept-Encoding") || void 0;
}
const acceptEncoding = parseQualityWeightedList2(rawAcceptEncoding);
if (acceptEncoding["identity"] === 0 || acceptEncoding["*"] === 0 && acceptEncoding["identity"] === void 0) {
throw new Error("No acceptable encodings available");
}
return { encoding: null };
}, "negotiateContent"),
fetchAsset: /* @__PURE__ */ __name(async (assetKey) => {
const filepath = assetKeyEntryMap.get(assetKey);
if (!filepath) {
throw new Error(
"Could not fetch asset. Please file an issue on GitHub (https://github.com/cloudflare/workers-sdk/issues/new/choose) with reproduction steps."
);
}
const body = (0, import_node_fs36.readFileSync)(filepath);
let contentType = (0, import_mime3.getType)(filepath) || "application/octet-stream";
if (contentType.startsWith("text/") && !contentType.includes("charset")) {
contentType = `${contentType}; charset=utf-8`;
}
return { body, contentType };
}, "fetchAsset")
});
}, "generateResponse");
return async (input, init3) => {
const request4 = new import_miniflare30.Request(input, init3);
return await generateResponse(request4);
};
}
var import_node_assert35, import_node_fs36, import_node_path67, import_mime3, import_miniflare30, import_undici24, ProxyDispatcher, invalidAssetsFetch;
var init_assets2 = __esm({
"src/miniflare-cli/assets.ts"() {
init_import_meta_url();
import_node_assert35 = __toESM(require("assert"));
import_node_fs36 = require("fs");
import_node_path67 = require("path");
init_createMetadataObject();
init_workers_shared();
init_esm4();
import_mime3 = __toESM(require_mime());
import_miniflare30 = require("miniflare");
import_undici24 = __toESM(require_undici());
init_logger();
init_hash();
__name(generateASSETSBinding, "generateASSETSBinding");
ProxyDispatcher = class _ProxyDispatcher extends import_undici24.Dispatcher {
constructor(host) {
super();
this.host = host;
}
static {
__name(this, "ProxyDispatcher");
}
dispatcher = (0, import_undici24.getGlobalDispatcher)();
dispatch(options, handler) {
if (this.host !== null) {
_ProxyDispatcher.reinstateHostHeader(options.headers, this.host);
}
return this.dispatcher.dispatch(options, handler);
}
close() {
return this.dispatcher.close();
}
destroy() {
return this.dispatcher.destroy();
}
/**
* Ensure that the request contains a Host header, which would have been deleted
* by the `fetch()` function before calling `dispatcher.dispatch()`.
*/
static reinstateHostHeader(headers, host) {
(0, import_node_assert35.default)(headers, "Expected all proxy requests to contain headers.");
(0, import_node_assert35.default)(
!Array.isArray(headers),
"Expected proxy request headers to be a hash object"
);
(0, import_node_assert35.default)(
Object.keys(headers).every((h6) => h6.toLowerCase() !== "host"),
"Expected Host header to have been deleted."
);
headers["Host"] = host;
}
};
__name(generateAssetsFetch, "generateAssetsFetch");
invalidAssetsFetch = /* @__PURE__ */ __name(() => {
throw new Error(
"Trying to fetch assets directly when there is no `directory` option specified."
);
}, "invalidAssetsFetch");
}
});
// src/dev.ts
async function getPagesAssetsFetcher(options) {
if (options !== void 0) {
const generateASSETSBinding3 = (init_assets2(), __toCommonJS(assets_exports)).default;
return {
ASSETS: {
type: "fetcher",
fetcher: await generateASSETSBinding3({
log: logger,
...options
})
}
};
}
}
async function setupDevEnv(devEnv, configPath, auth, args) {
await devEnv.config.set(
{
name: args.name,
config: configPath,
entrypoint: args.script,
compatibilityDate: args.compatibilityDate,
compatibilityFlags: args.compatibilityFlags,
triggers: args.routes?.map((r7) => ({
type: "route",
pattern: r7
})),
env: args.env,
envFiles: args.envFile,
build: {
bundle: args.bundle !== void 0 ? args.bundle : void 0,
define: collectKeyValues(args.define),
jsxFactory: args.jsxFactory,
jsxFragment: args.jsxFragment,
tsconfig: args.tsconfig,
minify: args.minify,
processEntrypoint: args.processEntrypoint,
additionalModules: args.additionalModules,
moduleRoot: args.moduleRoot,
moduleRules: args.rules,
nodejsCompatMode: /* @__PURE__ */ __name((parsedConfig) => validateNodeCompatMode(
args.compatibilityDate ?? parsedConfig.compatibility_date,
args.compatibilityFlags ?? parsedConfig.compatibility_flags ?? [],
{
noBundle: args.noBundle ?? parsedConfig.no_bundle
}
), "nodejsCompatMode")
},
bindings: {
...await getPagesAssetsFetcher(args.enablePagesAssetsServiceBinding),
...collectPlainTextVars(args.var),
...convertCfWorkerInitBindingsToBindings({
kv_namespaces: args.kv,
vars: args.vars,
send_email: void 0,
wasm_modules: void 0,
text_blobs: void 0,
browser: void 0,
ai: args.ai,
images: void 0,
version_metadata: args.version_metadata,
data_blobs: void 0,
durable_objects: { bindings: args.durableObjects ?? [] },
workflows: void 0,
queues: void 0,
r2_buckets: args.r2,
d1_databases: args.d1Databases,
vectorize: void 0,
hyperdrive: void 0,
secrets_store_secrets: void 0,
unsafe_hello_world: void 0,
services: args.services,
analytics_engine_datasets: void 0,
dispatch_namespaces: void 0,
mtls_certificates: void 0,
pipelines: void 0,
logfwdr: void 0,
unsafe: void 0,
assets: void 0
})
},
dev: {
auth,
remote: !args.forceLocal && args.remote,
server: {
hostname: args.ip,
port: args.port,
secure: args.localProtocol === void 0 ? void 0 : args.localProtocol === "https",
httpsCertPath: args.httpsCertPath,
httpsKeyPath: args.httpsKeyPath
},
inspector: {
port: args.inspectorPort
},
origin: {
hostname: args.host ?? args.localUpstream,
secure: args.upstreamProtocol === void 0 ? void 0 : args.upstreamProtocol === "https"
},
persist: args.persistTo,
liveReload: args.liveReload,
testScheduled: args.testScheduled,
logLevel: args.logLevel,
registry: args.disableDevRegistry ? void 0 : getRegistryPath(),
bindVectorizeToProd: args.experimentalVectorizeBindToProd,
imagesLocalMode: args.experimentalImagesLocalMode,
multiworkerPrimary: args.multiworkerPrimary,
enableContainers: args.enableContainers,
dockerPath: args.dockerPath,
// initialise with a random id
containerBuildId: generateContainerBuildId()
},
legacy: {
site: /* @__PURE__ */ __name((configParam) => {
const legacyAssetPaths = getResolvedSiteAssetPaths(args, configParam);
return Boolean(args.site || configParam.site) && legacyAssetPaths ? {
bucket: import_node_path68.default.join(
legacyAssetPaths.baseDirectory,
legacyAssetPaths?.assetDirectory
),
include: legacyAssetPaths.includePatterns,
exclude: legacyAssetPaths.excludePatterns
} : void 0;
}, "site"),
enableServiceEnvironments: !(args.legacyEnv ?? true)
},
assets: args.assets
},
true
);
return devEnv;
}
async function startDev(args) {
let configFileWatcher;
let assetsWatcher;
let devEnv;
let teardownRegistryPromise;
let unregisterHotKeys;
try {
if (args.logLevel) {
logger.loggerLevel = args.logLevel;
}
const authHook = /* @__PURE__ */ __name(async (config) => {
const hotkeysDisplayed = !!unregisterHotKeys;
let accountId = args.accountId;
if (!accountId) {
unregisterHotKeys?.();
accountId = await requireAuth(config);
if (hotkeysDisplayed) {
(0, import_node_assert36.default)(devEnv !== void 0);
unregisterHotKeys = registerDevHotKeys(
Array.isArray(devEnv) ? devEnv : [devEnv],
args
);
}
}
return {
accountId,
apiToken: requireApiToken()
};
}, "authHook");
if (args.remote) {
logger.log(
bold(
esm_default2`
Support for remote bindings in ${green("`wrangler dev`")} is now available in public beta as a replacement for ${green("`wrangler dev --remote`")}. Try it out now by running ${green("`wrangler dev --x-remote-bindings`")} with the ${green("`experimental_remote`")} option enabled on your resources and let us know how it goes!
This gives you access to remote resources in development while retaining all the usual benefits of local dev: fast iteration speed, breakpoint debugging, and more.
Refer to https://developers.cloudflare.com/workers/development-testing/#remote-bindings for more information.`
)
);
}
if (Array.isArray(args.config)) {
const runtime = new MultiworkerRuntimeController(args.config.length);
const primaryDevEnv2 = new DevEnv({ runtimes: [runtime] });
devEnv = [
await setupDevEnv(primaryDevEnv2, args.config[0], authHook, {
...args,
multiworkerPrimary: true
})
];
devEnv.push(
...await Promise.all(
args.config.slice(1).map((c6) => {
return setupDevEnv(
new DevEnv({
runtimes: [runtime],
proxy: new NoOpProxyController()
}),
c6,
authHook,
{
disableDevRegistry: args.disableDevRegistry,
multiworkerPrimary: false
}
);
})
)
);
if (isInteractive2() && args.showInteractiveDevSession !== false) {
unregisterHotKeys = registerDevHotKeys(devEnv, args);
}
} else {
devEnv = new DevEnv();
await setupDevEnv(devEnv, args.config, authHook, args);
if (isInteractive2() && args.showInteractiveDevSession !== false) {
unregisterHotKeys = registerDevHotKeys([devEnv], args);
}
}
const [primaryDevEnv, ...secondary] = Array.isArray(devEnv) ? devEnv : [devEnv];
void primaryDevEnv.proxy.ready.promise.then(({ url: url4 }) => {
if (args.onReady) {
args.onReady(url4.hostname, parseInt(url4.port));
}
if ((args.enableIpc || !args.onReady) && process.send && typeof vitest === "undefined") {
process.send(
JSON.stringify({
event: "DEV_SERVER_READY",
ip: url4.hostname,
port: parseInt(url4.port)
})
);
}
});
return {
devEnv: primaryDevEnv,
secondary,
unregisterHotKeys,
teardownRegistryPromise
};
} catch (e7) {
await Promise.allSettled([
configFileWatcher?.close(),
assetsWatcher?.close(),
...Array.isArray(devEnv) ? devEnv.map((d6) => d6.teardown()) : [devEnv?.teardown()],
(async () => {
if (teardownRegistryPromise) {
(0, import_node_assert36.default)(devEnv === void 0 || !Array.isArray(devEnv));
const teardownRegistry = await teardownRegistryPromise;
await teardownRegistry(devEnv?.config.latestConfig?.name);
}
unregisterHotKeys?.();
})()
]);
throw e7;
}
}
function maskVars(bindings, configParam) {
const maskedVars = { ...bindings.vars };
for (const key of Object.keys(maskedVars)) {
if (maskedVars[key] !== configParam.vars[key]) {
maskedVars[key] = "(hidden)";
}
}
return maskedVars;
}
async function getHostAndRoutes(args, config) {
const host = args.host || config.dev.host;
const routes = (args.routes || config.route && [config.route] || config.routes)?.map((r7) => {
if (typeof r7 !== "object") {
return r7;
}
if ("custom_domain" in r7 || "zone_id" in r7 || "zone_name" in r7) {
return r7;
} else {
return r7.pattern;
}
});
if (routes) {
const assetOptions = getAssetsOptions({ assets: args.assets }, config);
validateRoutes3(routes, assetOptions);
}
return { host, routes };
}
function getInferredHost(routes, configPath) {
if (routes?.length) {
const firstRoute = routes[0];
const host = getHostFromRoute(firstRoute);
if (host === void 0) {
throw new UserError(
`Cannot infer host from first route: ${JSON.stringify(
firstRoute
)}.
You can explicitly set the \`dev.host\` configuration in your ${configFileName(configPath)} file, for example:
\`\`\`
${formatConfigSnippet(
{
dev: {
host: "example.com"
}
},
configPath
)}
\`\`\`
`
);
}
return host;
}
}
function getResolvedSiteAssetPaths(args, configParam) {
return getSiteAssetPaths(
configParam,
args.site,
args.siteInclude,
args.siteExclude
);
}
function getBindings2(configParam, env6, envFiles, local, args, remoteBindingsEnabled = getFlag("REMOTE_BINDINGS")) {
const kvConfig = (configParam.kv_namespaces || []).map(
({ binding, preview_id, id, experimental_remote }) => {
if (!preview_id && !local) {
throw new UserError(
`In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your ${configFileName(configParam.configPath)} file`,
{
telemetryMessage: "no preview kv namespace configured in remote dev"
}
);
}
return {
binding,
id: preview_id ?? id,
experimental_remote: remoteBindingsEnabled && experimental_remote
};
}
);
const kvArgs = args.kv || [];
const mergedKVBindings = mergeWithOverride(kvConfig, kvArgs, "binding");
const doConfig = (configParam.durable_objects || { bindings: [] }).bindings;
const doArgs = args.durableObjects || [];
const mergedDOBindings = mergeWithOverride(doConfig, doArgs, "name");
const d1Config = (configParam.d1_databases ?? []).map((d1Db) => {
const database_id = d1Db.preview_database_id ? d1Db.preview_database_id : d1Db.database_id;
if (local) {
return {
...d1Db,
experimental_remote: remoteBindingsEnabled && d1Db.experimental_remote,
database_id
};
}
if (!d1Db.preview_database_id && !process.env.NO_D1_WARNING) {
logger.log(
`--------------------
\u{1F4A1} Recommendation: for development, use a preview D1 database rather than the one you'd use in production.
\u{1F4A1} Create a new D1 database with "wrangler d1 create <name>" and add its id as preview_database_id to the d1_database "${d1Db.binding}" in your ${configFileName(configParam.configPath)} file
--------------------
`
);
}
return { ...d1Db, database_id };
});
const d1Args = args.d1Databases || [];
const mergedD1Bindings = mergeWithOverride(d1Config, d1Args, "binding");
const r2Config = configParam.r2_buckets?.map(
({
binding,
preview_bucket_name,
bucket_name,
jurisdiction,
experimental_remote
}) => {
if (!preview_bucket_name && !local) {
throw new UserError(
`In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your ${configFileName(configParam.configPath)} file`,
{
telemetryMessage: "no preview r2 bucket configured in remote dev"
}
);
}
return {
binding,
bucket_name: preview_bucket_name ?? bucket_name,
jurisdiction,
experimental_remote: remoteBindingsEnabled && experimental_remote
};
}
) || [];
const r2Args = args.r2 || [];
const mergedR2Bindings = mergeWithOverride(r2Config, r2Args, "binding");
const servicesConfig = configParam.services || [];
const servicesArgs = args.services || [];
const mergedServiceBindings = mergeWithOverride(
servicesConfig,
servicesArgs,
"binding"
).map(
(service) => ({
...service,
experimental_remote: remoteBindingsEnabled && "experimental_remote" in service && !!service.experimental_remote
})
);
const hyperdriveBindings = configParam.hyperdrive.map((hyperdrive) => {
const connectionStringFromEnv = process.env[`WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING_${hyperdrive.binding}`];
if (local && connectionStringFromEnv === void 0 && hyperdrive.localConnectionString === void 0) {
throw new UserError(
`When developing locally, you should use a local Postgres connection string to emulate Hyperdrive functionality. Please setup Postgres locally and set the value of the 'WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING_${hyperdrive.binding}' variable or "${hyperdrive.binding}"'s "localConnectionString" to the Postgres connection string.`,
{ telemetryMessage: "no local hyperdrive connection string" }
);
}
if (connectionStringFromEnv) {
logger.log(
`Found a non-empty WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING variable for binding. Hyperdrive will connect to this database during local development.`
);
hyperdrive.localConnectionString = connectionStringFromEnv;
}
return hyperdrive;
});
const queuesBindings = [
...(configParam.queues.producers || []).map((queue) => {
return {
binding: queue.binding,
queue_name: queue.queue,
delivery_delay: queue.delivery_delay,
experimental_remote: remoteBindingsEnabled && queue.experimental_remote
};
})
];
const bindings = {
// top-level fields
wasm_modules: configParam.wasm_modules,
text_blobs: configParam.text_blobs,
data_blobs: configParam.data_blobs,
// inheritable fields
dispatch_namespaces: configParam.dispatch_namespaces,
logfwdr: configParam.logfwdr,
// non-inheritable fields
vars: {
// Use a copy of combinedVars since we're modifying it later
...getVarsForDev(
configParam.userConfigPath,
envFiles,
configParam.vars,
env6
),
...args.vars
},
durable_objects: {
bindings: mergedDOBindings
},
workflows: configParam.workflows,
kv_namespaces: mergedKVBindings,
queues: queuesBindings,
r2_buckets: mergedR2Bindings,
d1_databases: mergedD1Bindings,
vectorize: configParam.vectorize,
hyperdrive: hyperdriveBindings,
secrets_store_secrets: configParam.secrets_store_secrets,
services: mergedServiceBindings,
analytics_engine_datasets: configParam.analytics_engine_datasets,
browser: configParam.browser,
ai: args.ai || configParam.ai,
images: configParam.images,
version_metadata: args.version_metadata || configParam.version_metadata,
unsafe: {
bindings: configParam.unsafe.bindings,
metadata: configParam.unsafe.metadata,
capnp: configParam.unsafe.capnp
},
mtls_certificates: configParam.mtls_certificates,
pipelines: configParam.pipelines,
send_email: configParam.send_email,
assets: configParam.assets?.binding ? { binding: configParam.assets?.binding } : void 0,
unsafe_hello_world: configParam.unsafe_hello_world
};
return bindings;
}
function getAssetChangeMessage(eventName, assetPath) {
let message = `${assetPath} changed`;
switch (eventName) {
case "add":
message = `File ${assetPath} was added`;
break;
case "addDir":
message = `Directory ${assetPath} was added`;
break;
case "unlink":
message = `File ${assetPath} was removed`;
break;
case "unlinkDir":
message = `Directory ${assetPath} was removed`;
break;
}
return message;
}
var import_node_assert36, import_node_events6, import_node_path68, import_env2, dev;
var init_dev2 = __esm({
"src/dev.ts"() {
init_import_meta_url();
import_node_assert36 = __toESM(require("assert"));
import_node_events6 = __toESM(require("events"));
import_node_path68 = __toESM(require("path"));
init_colors();
init_containers_shared();
import_env2 = __toESM(require_dist());
init_esm2();
init_api3();
init_MultiworkerRuntimeController();
init_NoOpProxyController();
init_utils2();
init_assets();
init_config2();
init_create_command();
init_deploy8();
init_node_compat();
init_dev_vars();
init_hotkeys();
init_misc_variables();
init_errors();
init_experimental_flags();
init_is_interactive();
init_logger();
init_sites();
init_user2();
init_collectKeyValues();
init_mergeWithOverride();
init_zones();
dev = createCommand({
behaviour: {
provideConfig: false,
overrideExperimentalFlags: /* @__PURE__ */ __name((args) => ({
MULTIWORKER: Array.isArray(args.config),
RESOURCES_PROVISION: args.experimentalProvision ?? false,
REMOTE_BINDINGS: args.experimentalRemoteBindings ?? false,
DEPLOY_REMOTE_DIFF_CHECK: false
}), "overrideExperimentalFlags")
},
metadata: {
description: "\u{1F442} Start a local server for developing your Worker",
owner: "Workers: Authoring and Testing",
status: "stable"
},
positionalArgs: ["script"],
args: {
script: {
describe: "The path to an entry point for your Worker",
type: "string"
},
name: {
describe: "Name of the Worker",
type: "string",
requiresArg: true
},
"compatibility-date": {
describe: "Date to use for compatibility checks",
type: "string",
requiresArg: true
},
"compatibility-flags": {
describe: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
requiresArg: true,
array: true
},
latest: {
describe: "Use the latest version of the Workers runtime",
type: "boolean",
default: true
},
assets: {
describe: "Static assets to be served. Replaces Workers Sites.",
type: "string",
requiresArg: true
},
// We want to have a --no-bundle flag, but yargs requires that
// we also have a --bundle flag (that it adds the --no to by itself)
// So we make a --bundle flag, but hide it, and then add a --no-bundle flag
// that's visible to the user but doesn't "do" anything.
bundle: {
describe: "Run wrangler's compilation step before publishing",
type: "boolean",
hidden: true
},
"no-bundle": {
describe: "Skip internal build steps and directly deploy script",
type: "boolean",
default: false
},
ip: {
describe: "IP address to listen on",
type: "string"
},
port: {
describe: "Port to listen on",
type: "number"
},
"inspector-port": {
describe: "Port for devtools to connect to",
type: "number"
},
routes: {
describe: "Routes to upload",
alias: "route",
type: "string",
requiresArg: true,
array: true
},
host: {
type: "string",
requiresArg: true,
describe: "Host to forward requests to, defaults to the zone of project"
},
"local-protocol": {
describe: "Protocol to listen to requests on, defaults to http.",
choices: ["http", "https"]
},
"https-key-path": {
describe: "Path to a custom certificate key",
type: "string",
requiresArg: true
},
"https-cert-path": {
describe: "Path to a custom certificate",
type: "string",
requiresArg: true
},
"local-upstream": {
type: "string",
describe: "Host to act as origin in local mode, defaults to dev.host or route"
},
"enable-containers": {
type: "boolean",
describe: "Whether to build and enable containers during development",
hidden: true
},
site: {
describe: "Root folder of static assets for Workers Sites",
type: "string",
requiresArg: true,
hidden: true,
deprecated: true
},
"site-include": {
describe: "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
type: "string",
requiresArg: true,
array: true,
hidden: true,
deprecated: true
},
"site-exclude": {
describe: "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
type: "string",
requiresArg: true,
array: true,
hidden: true,
deprecated: true
},
"upstream-protocol": {
describe: "Protocol to forward requests to host on, defaults to https.",
choices: ["http", "https"]
},
var: {
describe: "A key-value pair to be injected into the script as a variable",
type: "string",
requiresArg: true,
array: true
},
define: {
describe: "A key-value pair to be substituted in the script",
type: "string",
requiresArg: true,
array: true
},
alias: {
describe: "A module pair to be substituted in the script",
type: "string",
requiresArg: true,
array: true
},
"jsx-factory": {
describe: "The function that is called for each JSX element",
type: "string",
requiresArg: true
},
"jsx-fragment": {
describe: "The function that is called for each JSX fragment",
type: "string",
requiresArg: true
},
tsconfig: {
describe: "Path to a custom tsconfig.json file",
type: "string",
requiresArg: true
},
remote: {
alias: "r",
describe: "Run on the global Cloudflare network with access to production resources",
type: "boolean",
default: false
},
local: {
alias: "l",
describe: "Run on my machine",
type: "boolean",
deprecated: true,
hidden: true
},
minify: {
describe: "Minify the script",
type: "boolean"
},
"node-compat": {
describe: "Enable Node.js compatibility",
type: "boolean",
hidden: true,
deprecated: true
},
"persist-to": {
describe: "Specify directory to use for local persistence (defaults to .wrangler/state)",
type: "string",
requiresArg: true
},
"live-reload": {
describe: "Auto reload HTML pages when change is detected in local mode",
type: "boolean"
},
"legacy-env": {
type: "boolean",
describe: "Use legacy environments",
hidden: true
},
"test-scheduled": {
describe: "Test scheduled events by visiting /__scheduled in browser",
type: "boolean",
default: false
},
"log-level": {
choices: ["debug", "info", "log", "warn", "error", "none"],
describe: "Specify logging level"
},
"show-interactive-dev-session": {
describe: "Show interactive dev session (defaults to true if the terminal supports interactivity)",
type: "boolean"
},
"experimental-vectorize-bind-to-prod": {
type: "boolean",
describe: "Bind to production Vectorize indexes in local development mode",
default: false
},
"experimental-images-local-mode": {
type: "boolean",
describe: "Use a local lower-fidelity implementation of the Images binding",
default: false
}
},
async validateArgs(args) {
if (args.nodeCompat) {
throw new UserError(
`The --node-compat flag is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`
);
}
if (args.liveReload && args.remote) {
throw new UserError(
"--live-reload is only supported in local mode. Please just use one of either --remote or --live-reload."
);
}
if ((0, import_env2.isWebContainer)()) {
logger.error(
`Oh no! \u{1F61F} You tried to run \`wrangler dev\` in a StackBlitz WebContainer. \u{1F92F}
This is currently not supported \u{1F62D}, but we think that we'll get it to work soon... hang in there! \u{1F97A}`
);
process.exitCode = 1;
return;
}
},
async handler(args) {
const devInstance = await startDev(args);
(0, import_node_assert36.default)(devInstance.devEnv !== void 0);
await import_node_events6.default.once(devInstance.devEnv, "teardown");
await Promise.all(devInstance.secondary.map((d6) => d6.teardown()));
if (devInstance.teardownRegistryPromise) {
const teardownRegistry = await devInstance.teardownRegistryPromise;
await teardownRegistry(devInstance.devEnv.config.latestConfig?.name);
}
devInstance.unregisterHotKeys?.();
}
});
__name(getPagesAssetsFetcher, "getPagesAssetsFetcher");
__name(setupDevEnv, "setupDevEnv");
__name(startDev, "startDev");
__name(maskVars, "maskVars");
__name(getHostAndRoutes, "getHostAndRoutes");
__name(getInferredHost, "getInferredHost");
__name(getResolvedSiteAssetPaths, "getResolvedSiteAssetPaths");
__name(getBindings2, "getBindings");
__name(getAssetChangeMessage, "getAssetChangeMessage");
}
});
// src/api/dev.ts
async function unstable_dev(script, options, apiOptions) {
const experimentalOptions = {
// Defaults for "experimental" options
disableDevRegistry: false,
disableExperimentalWarning: false,
showInteractiveDevSession: false,
testMode: true,
// Override all options, including overwriting with "undefined"
...options?.experimental
};
const {
// there are two types of "experimental" options:
// 1. options to unstable_dev that we're still testing or are unsure of
processEntrypoint = false,
additionalModules,
disableDevRegistry,
disableExperimentalWarning,
forceLocal,
liveReload,
showInteractiveDevSession,
testMode,
testScheduled,
vectorizeBindToProd,
imagesLocalMode,
// 2. options for alpha/beta products/libs
d1Databases,
enablePagesAssetsServiceBinding
} = experimentalOptions;
if (apiOptions) {
logger.error(
"unstable_dev's third argument (apiOptions) has been deprecated in favor of an `experimental` property within the second argument (options).\nPlease update your code from:\n`await unstable_dev('...', {...}, {...});`\nto:\n`await unstable_dev('...', {..., experimental: {...}});`"
);
}
if (!disableExperimentalWarning) {
logger.warn(
`unstable_dev() is experimental
unstable_dev()'s behaviour will likely change in future releases`
);
}
let readyResolve;
const readyPromise = new Promise((resolve25) => {
readyResolve = resolve25;
});
const defaultLogLevel = testMode ? "warn" : "log";
const local = options?.local ?? true;
const dockerPath = options?.experimental?.dockerPath ?? getDockerPath();
const devOptions = {
script,
inspect: false,
_: [],
$0: "",
remote: !local,
local: void 0,
d1Databases,
disableDevRegistry,
testScheduled: testScheduled ?? false,
enablePagesAssetsServiceBinding,
forceLocal,
liveReload,
showInteractiveDevSession,
onReady: /* @__PURE__ */ __name((address2, port2) => {
readyResolve({ address: address2, port: port2 });
}, "onReady"),
config: options?.config,
env: options?.env,
envFile: options?.envFiles,
processEntrypoint,
additionalModules,
bundle: options?.bundle,
compatibilityDate: options?.compatibilityDate,
compatibilityFlags: options?.compatibilityFlags,
ip: "127.0.0.1",
inspectorPort: options?.inspectorPort ?? 0,
v: void 0,
cwd: void 0,
localProtocol: options?.localProtocol,
httpsKeyPath: options?.httpsKeyPath,
httpsCertPath: options?.httpsCertPath,
assets: void 0,
site: options?.site,
// Root folder of static assets for Workers Sites
siteInclude: options?.siteInclude,
// Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.
siteExclude: options?.siteExclude,
// Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.
persist: options?.persist,
// Enable persistence for local mode, using default path: .wrangler/state
persistTo: options?.persistTo,
// Specify directory to use for local persistence (implies --persist)
name: void 0,
noBundle: false,
latest: false,
routes: void 0,
host: void 0,
localUpstream: void 0,
upstreamProtocol: void 0,
var: void 0,
define: void 0,
alias: void 0,
jsxFactory: void 0,
jsxFragment: void 0,
tsconfig: void 0,
minify: void 0,
legacyEnv: void 0,
...options,
logLevel: options?.logLevel ?? defaultLogLevel,
port: options?.port ?? 0,
experimentalProvision: void 0,
experimentalRemoteBindings: false,
experimentalVectorizeBindToProd: vectorizeBindToProd ?? false,
experimentalImagesLocalMode: imagesLocalMode ?? false,
enableIpc: options?.experimental?.enableIpc,
nodeCompat: void 0,
enableContainers: options?.experimental?.enableContainers ?? false,
dockerPath,
containerEngine: options?.experimental?.containerEngine
};
const devServer = await run(
{
// TODO: can we make this work?
MULTIWORKER: false,
RESOURCES_PROVISION: false,
REMOTE_BINDINGS: false,
DEPLOY_REMOTE_DIFF_CHECK: false
},
() => startDev(devOptions)
);
const { port, address } = await readyPromise;
return {
port,
address,
stop: /* @__PURE__ */ __name(async () => {
await devServer.devEnv.teardown.bind(devServer.devEnv)();
const teardownRegistry = await devServer.teardownRegistryPromise;
await teardownRegistry?.(devServer.devEnv.config.latestConfig?.name);
devServer.unregisterHotKeys?.();
}, "stop"),
fetch: /* @__PURE__ */ __name(async (input, init3) => {
return await (0, import_undici25.fetch)(
...parseRequestInput(address, port, input, init3, options?.localProtocol)
);
}, "fetch"),
waitUntilExit: /* @__PURE__ */ __name(async () => {
await import_node_events7.default.once(devServer.devEnv, "teardown");
}, "waitUntilExit")
};
}
function parseRequestInput(readyAddress, readyPort, input = "/", init3, protocol = "http") {
if (typeof input === "string") {
input = new URL(input, "http://placeholder");
}
const forward = new import_undici25.Request(input, init3);
const url4 = new URL(forward.url);
forward.headers.set("MF-Original-URL", url4.toString());
forward.headers.set("MF-Disable-Pretty-Error", "true");
url4.protocol = protocol;
url4.hostname = readyAddress;
url4.port = readyPort.toString();
if (forward.body !== null && forward.headers.get("Content-Length") === "0") {
forward.headers.delete("Content-Length");
}
return [url4, forward];
}
var import_node_events7, import_undici25;
var init_dev3 = __esm({
"src/api/dev.ts"() {
init_import_meta_url();
import_node_events7 = __toESM(require("events"));
import_undici25 = __toESM(require_undici());
init_dev2();
init_misc_variables();
init_experimental_flags();
init_logger();
__name(unstable_dev, "unstable_dev");
__name(parseRequestInput, "parseRequestInput");
}
});
// src/api/pages/index.ts
var unstable_pages;
var init_pages2 = __esm({
"src/api/pages/index.ts"() {
init_import_meta_url();
init_deploy5();
unstable_pages = {
deploy: deploy2
};
}
});
// src/api/integrations/platform/caches.ts
var CacheStorage, Cache;
var init_caches = __esm({
"src/api/integrations/platform/caches.ts"() {
init_import_meta_url();
CacheStorage = class {
static {
__name(this, "CacheStorage");
}
constructor() {
const unsupportedMethods = ["has", "delete", "keys", "match"];
unsupportedMethods.forEach((method) => {
Object.defineProperty(this, method, {
enumerable: false,
value: /* @__PURE__ */ __name(() => {
throw new Error(
`Failed to execute '${method}' on 'CacheStorage': the method is not implemented.`
);
}, "value")
});
});
Object.defineProperty(this, "default", {
enumerable: true,
value: this.default
});
}
async open(cacheName) {
return new Cache();
}
get default() {
return new Cache();
}
};
Cache = class {
static {
__name(this, "Cache");
}
async delete(request4, options) {
return false;
}
async match(request4, options) {
return void 0;
}
async put(request4, response) {
}
};
}
});
// src/api/integrations/platform/executionContext.ts
var ExecutionContext;
var init_executionContext = __esm({
"src/api/integrations/platform/executionContext.ts"() {
init_import_meta_url();
ExecutionContext = class _ExecutionContext {
static {
__name(this, "ExecutionContext");
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any, unused-imports/no-unused-vars
waitUntil(promise) {
if (!(this instanceof _ExecutionContext)) {
throw new Error("Illegal invocation");
}
}
passThroughOnException() {
if (!(this instanceof _ExecutionContext)) {
throw new Error("Illegal invocation");
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
props = {};
};
}
});
// src/api/integrations/platform/index.ts
async function getPlatformProxy(options = {}) {
const experimentalRemoteBindings = !!options.experimental?.remoteBindings;
const env6 = options.environment;
const config = readConfig({
config: options.configPath,
env: env6
});
let remoteProxySession = void 0;
if (experimentalRemoteBindings && config.configPath) {
remoteProxySession = (await maybeStartOrUpdateRemoteProxySession({
path: config.configPath,
environment: env6
}) ?? {}).session;
}
const miniflareOptions = await getMiniflareOptionsFromConfig({
config,
options,
remoteProxyConnectionString: remoteProxySession?.remoteProxyConnectionString,
remoteBindingsEnabled: experimentalRemoteBindings
});
const mf = new import_miniflare31.Miniflare(miniflareOptions);
const bindings = await mf.getBindings();
const cf2 = await mf.getCf();
deepFreeze(cf2);
return {
env: bindings,
cf: cf2,
ctx: new ExecutionContext(),
caches: new CacheStorage(),
dispose: /* @__PURE__ */ __name(async () => {
await remoteProxySession?.dispose();
await mf.dispose();
}, "dispose")
};
}
async function getMiniflareOptionsFromConfig(args) {
const {
config,
options,
remoteProxyConnectionString,
remoteBindingsEnabled
} = args;
const bindings = getBindings2(
config,
options.environment,
options.envFiles,
true,
{},
remoteBindingsEnabled
);
if (config["durable_objects"]) {
const { localBindings } = partitionDurableObjectBindings(config);
if (localBindings.length > 0) {
logger.warn(dedent2`
You have defined bindings to the following internal Durable Objects:
${localBindings.map((b6) => `- ${JSON.stringify(b6)}`).join("\n")}
These will not work in local development, but they should work in production.
If you want to develop these locally, you can define your DO in a separate Worker, with a separate configuration file.
For detailed instructions, refer to the Durable Objects section here: https://developers.cloudflare.com/workers/wrangler/api#supported-bindings
`);
}
}
const { bindingOptions, externalWorkers } = buildMiniflareBindingOptions(
{
name: config.name,
complianceRegion: config.compliance_region,
bindings,
queueConsumers: void 0,
services: bindings.services,
serviceBindings: {},
migrations: config.migrations,
imagesLocalMode: true,
tails: [],
containerDOClassNames: new Set(
config.containers?.map((c6) => c6.class_name)
),
containerBuildId: void 0,
enableContainers: config.dev.enable_containers
},
remoteProxyConnectionString,
remoteBindingsEnabled
);
let processedAssetOptions;
try {
processedAssetOptions = getAssetsOptions({ assets: void 0 }, config);
} catch (e7) {
const isNonExistentError = e7 instanceof NonExistentAssetsDirError;
if (!isNonExistentError) {
throw e7;
}
}
const assetOptions = processedAssetOptions ? buildAssetOptions({ assets: processedAssetOptions }) : {};
const defaultPersistRoot = getMiniflarePersistRoot(options.persist);
const miniflareOptions = {
workers: [
{
script: "",
modules: true,
name: config.name,
...bindingOptions,
...assetOptions
},
...externalWorkers
],
defaultPersistRoot
};
return {
script: "",
modules: true,
...miniflareOptions,
unsafeDevRegistryPath: getRegistryPath(),
unsafeDevRegistryDurableObjectProxy: true
};
}
function getMiniflarePersistRoot(persist) {
if (persist === false) {
return;
}
const defaultPersistPath = ".wrangler/state/v3";
const persistPath = typeof persist === "object" ? persist.path : defaultPersistPath;
return persistPath;
}
function deepFreeze(obj) {
Object.freeze(obj);
Object.entries(obj).forEach(([, prop]) => {
if (prop !== null && typeof prop === "object" && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
});
}
function unstable_getMiniflareWorkerOptions(configOrConfigPath, env6, options) {
const config = typeof configOrConfigPath === "string" ? readConfig({ config: configOrConfigPath, env: env6 }) : configOrConfigPath;
const modulesRules = config.rules.concat(DEFAULT_MODULE_RULES).map((rule) => ({
type: rule.type,
include: rule.globs,
fallthrough: rule.fallthrough
}));
const containerDOClassNames = new Set(
config.containers?.map((c6) => c6.class_name)
);
const bindings = getBindings2(config, env6, options?.envFiles, true, {}, true);
const enableContainers = options?.overrides?.enableContainers !== void 0 ? options?.overrides?.enableContainers : config.dev.enable_containers;
const { bindingOptions, externalWorkers } = buildMiniflareBindingOptions(
{
name: config.name,
complianceRegion: config.compliance_region,
bindings,
queueConsumers: config.queues.consumers,
services: [],
serviceBindings: {},
migrations: config.migrations,
imagesLocalMode: !!options?.imagesLocalMode,
tails: config.tail_consumers,
containerDOClassNames,
containerBuildId: options?.containerBuildId,
enableContainers
},
options?.remoteProxyConnectionString,
options?.remoteBindingsEnabled ?? false
);
if (bindings.services !== void 0) {
bindingOptions.serviceBindings = Object.fromEntries(
bindings.services.map((binding) => {
const name2 = binding.service === config.name ? import_miniflare31.kCurrentWorker : binding.service;
if (options?.remoteProxyConnectionString && binding.experimental_remote) {
return [
binding.binding,
{
name: name2,
entrypoint: binding.entrypoint,
remoteProxyConnectionString: options.remoteProxyConnectionString
}
];
}
return [binding.binding, { name: name2, entrypoint: binding.entrypoint }];
})
);
}
if (bindings.durable_objects !== void 0) {
const classNameToUseSQLite = getClassNamesWhichUseSQLite(config.migrations);
bindingOptions.durableObjects = Object.fromEntries(
bindings.durable_objects.bindings.map((binding) => {
const useSQLite = classNameToUseSQLite.get(binding.class_name);
return [
binding.name,
{
className: binding.class_name,
scriptName: binding.script_name,
useSQLite,
container: enableContainers && config.containers?.length ? getImageNameFromDOClassName({
doClassName: binding.class_name,
containerDOClassNames,
containerBuildId: options?.containerBuildId
}) : void 0
}
];
})
);
}
const sitesAssetPaths = getSiteAssetPaths(config);
const sitesOptions = buildSitesOptions({ legacyAssetPaths: sitesAssetPaths });
const processedAssetOptions = getAssetsOptions(
{ assets: void 0 },
config,
options?.overrides?.assets
);
const assetOptions = processedAssetOptions ? buildAssetOptions({ assets: processedAssetOptions }) : {};
const useContainers = config.dev?.enable_containers && config.containers?.length;
const workerOptions = {
compatibilityDate: config.compatibility_date,
compatibilityFlags: config.compatibility_flags,
modulesRules,
containerEngine: useContainers ? config.dev.container_engine ?? resolveDockerHost(getDockerPath()) : void 0,
...bindingOptions,
...sitesOptions,
...assetOptions
};
return {
workerOptions,
define: config.define,
main: config.main,
externalWorkers
};
}
var import_miniflare31;
var init_platform = __esm({
"src/api/integrations/platform/index.ts"() {
init_import_meta_url();
init_containers_shared();
import_miniflare31 = require("miniflare");
init_assets();
init_config2();
init_entry();
init_rules();
init_dev2();
init_class_names_sqlite();
init_miniflare();
init_misc_variables();
init_logger();
init_sites();
init_dedent();
init_remoteBindings();
init_caches();
init_executionContext();
init_dev_vars();
__name(getPlatformProxy, "getPlatformProxy");
__name(getMiniflareOptionsFromConfig, "getMiniflareOptionsFromConfig");
__name(getMiniflarePersistRoot, "getMiniflarePersistRoot");
__name(deepFreeze, "deepFreeze");
__name(unstable_getMiniflareWorkerOptions, "unstable_getMiniflareWorkerOptions");
}
});
// src/api/integrations/index.ts
var init_integrations4 = __esm({
"src/api/integrations/index.ts"() {
init_import_meta_url();
init_platform();
}
});
// src/api/index.ts
var init_api3 = __esm({
"src/api/index.ts"() {
init_import_meta_url();
init_dev3();
init_pages2();
init_mtls_certificate();
init_startDevWorker();
init_integrations4();
init_remoteBindings();
}
});
// src/cli.ts
var cli_exports2 = {};
__export(cli_exports2, {
experimental_getWranglerCommands: () => experimental_getWranglerCommands,
experimental_maybeStartOrUpdateRemoteProxySession: () => maybeStartOrUpdateRemoteProxySession,
experimental_patchConfig: () => experimental_patchConfig,
experimental_pickRemoteBindings: () => pickRemoteBindings,
experimental_readRawConfig: () => experimental_readRawConfig,
experimental_startRemoteProxySession: () => startRemoteProxySession,
getPlatformProxy: () => getPlatformProxy,
unstable_DevEnv: () => DevEnv,
unstable_convertConfigBindingsToStartWorkerBindings: () => convertConfigBindingsToStartWorkerBindings,
unstable_dev: () => unstable_dev,
unstable_generateASSETSBinding: () => generateASSETSBinding2,
unstable_getMiniflareWorkerOptions: () => unstable_getMiniflareWorkerOptions,
unstable_getVarsForDev: () => getVarsForDev,
unstable_pages: () => unstable_pages,
unstable_readConfig: () => readConfig,
unstable_splitSqlQuery: () => splitSqlQuery,
unstable_startWorker: () => startWorker
});
module.exports = __toCommonJS(cli_exports2);
init_import_meta_url();
var import_process5 = __toESM(require("process"));
// ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/helpers/helpers.mjs
init_import_meta_url();
init_apply_extends();
init_process_argv();
init_lib();
init_esm();
// src/cli.ts
init_api3();
init_errors();
init_src2();
init_integrations4();
init_splitter();
init_config2();
init_patch_config();
init_api3();
// src/experimental-commands-api.ts
init_import_meta_url();
init_src2();
function experimental_getWranglerCommands() {
const { registry, globalFlags } = createCLIParser([]);
return { registry: registry.getDefinitionTreeRoot(), globalFlags };
}
__name(experimental_getWranglerCommands, "experimental_getWranglerCommands");
// src/cli.ts
if (typeof vitest === "undefined" && require.main === module) {
main(hideBin(import_process5.default.argv)).catch((e7) => {
const exitCode = e7 instanceof FatalError && e7.code || 1;
import_process5.default.exit(exitCode);
});
}
var generateASSETSBinding2 = (
// eslint-disable-next-line @typescript-eslint/no-require-imports
(init_assets2(), __toCommonJS(assets_exports)).default
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
experimental_getWranglerCommands,
experimental_maybeStartOrUpdateRemoteProxySession,
experimental_patchConfig,
experimental_pickRemoteBindings,
experimental_readRawConfig,
experimental_startRemoteProxySession,
getPlatformProxy,
unstable_DevEnv,
unstable_convertConfigBindingsToStartWorkerBindings,
unstable_dev,
unstable_generateASSETSBinding,
unstable_getMiniflareWorkerOptions,
unstable_getVarsForDev,
unstable_pages,
unstable_readConfig,
unstable_splitSqlQuery,
unstable_startWorker
});
/*!
* Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*! Bundled license information:
yargs-parser/build/lib/string-utils.js:
(**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*)
yargs-parser/build/lib/tokenize-arg-string.js:
(**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*)
yargs-parser/build/lib/yargs-parser-types.js:
(**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*)
yargs-parser/build/lib/yargs-parser.js:
(**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*)
yargs-parser/build/lib/index.js:
(**
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
* CJS and ESM environments.
*
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*)
undici/lib/web/fetch/body.js:
(*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
undici/lib/web/websocket/frame.js:
(*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)
@webcontainer/env/dist/index.js:
(**
* @license Copyright 2022 Stackblitz, Inc. All Rights Reserved.
* Portions of this software are patent pending in USA and EU jurisdictions.
* More info available at https://stackblitz.com/terms-of-service.
*)
deep-extend/lib/deep-extend.js:
(*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*)
safe-buffer/index.js:
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
*/